book.tex 823 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. %
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. %\newcommand{\pythonColor}[0]{\color{purple}}
  31. \newcommand{\pythonColor}[0]{}
  32. % material that is specific to the Python edition of the book
  33. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  34. %% For multiple indices:
  35. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  36. \makeindex{subject}
  37. %\makeindex{authors}
  38. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  39. \if\edition\racketEd
  40. \lstset{%
  41. language=Lisp,
  42. basicstyle=\ttfamily\small,
  43. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  44. deletekeywords={read,mapping,vector},
  45. escapechar=|,
  46. columns=flexible,
  47. %moredelim=[is][\color{red}]{~}{~},
  48. showstringspaces=false
  49. }
  50. \fi
  51. \if\edition\pythonEd
  52. \lstset{%
  53. language=Python,
  54. basicstyle=\ttfamily\small,
  55. morekeywords={match,case,bool,int,let},
  56. deletekeywords={},
  57. escapechar=|,
  58. columns=flexible,
  59. %moredelim=[is][\color{red}]{~}{~},
  60. showstringspaces=false
  61. }
  62. \fi
  63. %%% Any shortcut own defined macros place here
  64. %% sample of author macro:
  65. \input{defs}
  66. \newtheorem{exercise}[theorem]{Exercise}
  67. \numberwithin{theorem}{chapter}
  68. \numberwithin{definition}{chapter}
  69. \numberwithin{equation}{chapter}
  70. % Adjusted settings
  71. \setlength{\columnsep}{4pt}
  72. %% \begingroup
  73. %% \setlength{\intextsep}{0pt}%
  74. %% \setlength{\columnsep}{0pt}%
  75. %% \begin{wrapfigure}{r}{0.5\textwidth}
  76. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  77. %% \caption{Basic layout}
  78. %% \end{wrapfigure}
  79. %% \lipsum[1]
  80. %% \endgroup
  81. \newbox\oiintbox
  82. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  83. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  84. \def\oiint{\copy\oiintbox}
  85. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  86. %\usepackage{showframe}
  87. \def\ShowFrameLinethickness{0.125pt}
  88. \addbibresource{book.bib}
  89. \if\edition\pythonEd
  90. \addbibresource{python.bib}
  91. \fi
  92. \begin{document}
  93. \frontmatter
  94. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  95. \HalfTitle{Essentials of Compilation}
  96. \halftitlepage
  97. \clearemptydoublepage
  98. \Title{Essentials of Compilation}
  99. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  100. %\edition{First Edition}
  101. \BookAuthor{Jeremy G. Siek}
  102. \imprint{The MIT Press\\
  103. Cambridge, Massachusetts\\
  104. London, England}
  105. \begin{copyrightpage}
  106. \textcopyright\ 2023 Massachusetts Institute of Technology \\[2ex]
  107. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  108. Subject to such license, all rights are reserved. \\[2ex]
  109. \includegraphics{CCBY-logo}
  110. The MIT Press would like to thank the anonymous peer reviewers who
  111. provided comments on drafts of this book. The generous work of
  112. academic experts is essential for establishing the authority and
  113. quality of our publications. We acknowledge with gratitude the
  114. contributions of these otherwise uncredited readers.
  115. This book was set in Times LT Std Roman by the author. Printed and
  116. bound in the United States of America.
  117. Library of Congress Cataloging-in-Publication Data\\
  118. \ \\
  119. Names: Siek, Jeremy, author. \\
  120. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  121. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  122. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  123. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  124. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  125. LC record available at https://lccn.loc.gov/2022015399\\
  126. LC ebook record available at https://lccn.loc.gov/2022015400\\
  127. \ \\
  128. 10 9 8 7 6 5 4 3 2 1
  129. %% Jeremy G. Siek. Available for free viewing
  130. %% or personal downloading under the
  131. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  132. %% license.
  133. %% Copyright in this monograph has been licensed exclusively to The MIT
  134. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  135. %% version to the public in 2022. All inquiries regarding rights should
  136. %% be addressed to The MIT Press, Rights and Permissions Department.
  137. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  138. %% All rights reserved. No part of this book may be reproduced in any
  139. %% form by any electronic or mechanical means (including photocopying,
  140. %% recording, or information storage and retrieval) without permission in
  141. %% writing from the publisher.
  142. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  143. %% United States of America.
  144. %% Library of Congress Cataloging-in-Publication Data is available.
  145. %% ISBN:
  146. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  147. \end{copyrightpage}
  148. \dedication{This book is dedicated to Katie, my partner in everything,
  149. my children, who grew up during the writing of this book, and the
  150. programming language students at Indiana University, whose
  151. thoughtful questions made this a better book.}
  152. %% \begin{epigraphpage}
  153. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  154. %% \textit{Book Name if any}}
  155. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  156. %% \end{epigraphpage}
  157. \tableofcontents
  158. %\listoffigures
  159. %\listoftables
  160. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  161. \chapter*{Preface}
  162. \addcontentsline{toc}{fmbm}{Preface}
  163. There is a magical moment when a programmer presses the \emph{run}
  164. button and the software begins to execute. Somehow a program written
  165. in a high-level language is running on a computer that is capable only
  166. of shuffling bits. Here we reveal the wizardry that makes that moment
  167. possible. Beginning with the groundbreaking work of Backus and
  168. colleagues in the 1950s, computer scientists developed techniques for
  169. constructing programs called \emph{compilers} that automatically
  170. translate high-level programs into machine code.
  171. We take you on a journey through constructing your own compiler for a
  172. small but powerful language. Along the way we explain the essential
  173. concepts, algorithms, and data structures that underlie compilers. We
  174. develop your understanding of how programs are mapped onto computer
  175. hardware, which is helpful in reasoning about properties at the
  176. junction of hardware and software, such as execution time, software
  177. errors, and security vulnerabilities. For those interested in
  178. pursuing compiler construction as a career, our goal is to provide a
  179. stepping-stone to advanced topics such as just-in-time compilation,
  180. program analysis, and program optimization. For those interested in
  181. designing and implementing programming languages, we connect language
  182. design choices to their impact on the compiler and the generated code.
  183. A compiler is typically organized as a sequence of stages that
  184. progressively translate a program to the code that runs on
  185. hardware. We take this approach to the extreme by partitioning our
  186. compiler into a large number of \emph{nanopasses}, each of which
  187. performs a single task. This enables the testing of each pass in
  188. isolation and focuses our attention, making the compiler far easier to
  189. understand.
  190. The most familiar approach to describing compilers is to dedicate each
  191. chapter to one pass. The problem with that approach is that it
  192. obfuscates how language features motivate design choices in a
  193. compiler. We instead take an \emph{incremental} approach in which we
  194. build a complete compiler in each chapter, starting with a small input
  195. language that includes only arithmetic and variables. We add new
  196. language features in subsequent chapters, extending the compiler as
  197. necessary.
  198. Our choice of language features is designed to elicit fundamental
  199. concepts and algorithms used in compilers.
  200. \begin{itemize}
  201. \item We begin with integer arithmetic and local variables in
  202. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  203. the fundamental tools of compiler construction: \emph{abstract
  204. syntax trees} and \emph{recursive functions}.
  205. {\if\edition\pythonEd\pythonColor
  206. \item In Chapter~\ref{ch:parsing} we learn how to use the Lark
  207. parser framework to create a parser for the language of integer
  208. arithmetic and local variables. We learn about the parsing
  209. algorithms inside Lark, including Earley and LALR(1).
  210. %
  211. \fi}
  212. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  213. \emph{graph coloring} to assign variables to machine registers.
  214. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  215. motivates an elegant recursive algorithm for translating them into
  216. conditional \code{goto} statements.
  217. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  218. variables}. This elicits the need for \emph{dataflow
  219. analysis} in the register allocator.
  220. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  221. \emph{garbage collection}.
  222. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  223. without lexical scoping, similar to functions in the C programming
  224. language~\citep{Kernighan:1988nx}. The reader learns about the
  225. procedure call stack and \emph{calling conventions} and how they interact
  226. with register allocation and garbage collection. The chapter also
  227. describes how to generate efficient tail calls.
  228. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  229. scoping, that is, \emph{lambda} expressions. The reader learns about
  230. \emph{closure conversion}, in which lambdas are translated into a
  231. combination of functions and tuples.
  232. % Chapter about classes and objects?
  233. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  234. point the input languages are statically typed. The reader extends
  235. the statically typed language with an \code{Any} type that serves
  236. as a target for compiling the dynamically typed language.
  237. %% {\if\edition\pythonEd\pythonColor
  238. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  239. %% \emph{classes}.
  240. %% \fi}
  241. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  242. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  243. in which different regions of a program may be static or dynamically
  244. typed. The reader implements runtime support for \emph{proxies} that
  245. allow values to safely move between regions.
  246. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  247. leveraging the \code{Any} type and type casts developed in chapters
  248. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  249. \end{itemize}
  250. There are many language features that we do not include. Our choices
  251. balance the incidental complexity of a feature versus the fundamental
  252. concepts that it exposes. For example, we include tuples and not
  253. records because although they both elicit the study of heap allocation and
  254. garbage collection, records come with more incidental complexity.
  255. Since 2009, drafts of this book have served as the textbook for
  256. sixteen-week compiler courses for upper-level undergraduates and
  257. first-year graduate students at the University of Colorado and Indiana
  258. University.
  259. %
  260. Students come into the course having learned the basics of
  261. programming, data structures and algorithms, and discrete
  262. mathematics.
  263. %
  264. At the beginning of the course, students form groups of two to four
  265. people. The groups complete approximately one chapter every two
  266. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  267. according to the students interests while respecting the dependencies
  268. between chapters shown in
  269. Figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  270. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  271. implementation of efficient tail calls.
  272. %
  273. The last two weeks of the course involve a final project in which
  274. students design and implement a compiler extension of their choosing.
  275. The last few chapters can be used in support of these projects. Many
  276. chapters include a challenge problem that we assign to the graduate
  277. students.
  278. For compiler courses at universities on the quarter system
  279. (about ten weeks in length), we recommend completing the course
  280. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  281. some scaffolding code to the students for each compiler pass.
  282. %
  283. The course can be adapted to emphasize functional languages by
  284. skipping chapter~\ref{ch:Lwhile} (loops) and including
  285. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  286. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  287. %
  288. %% \python{A course that emphasizes object-oriented languages would
  289. %% include Chapter~\ref{ch:Lobject}.}
  290. This book has been used in compiler courses at California Polytechnic
  291. State University, Portland State University, Rose–Hulman Institute of
  292. Technology, University of Freiburg, University of Massachusetts
  293. Lowell, and the University of Vermont.
  294. \begin{figure}[tp]
  295. \begin{tcolorbox}[colback=white]
  296. {\if\edition\racketEd
  297. \begin{tikzpicture}[baseline=(current bounding box.center)]
  298. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  299. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  300. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  301. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  302. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  303. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  304. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  305. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  306. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  307. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  308. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  309. \path[->] (C1) edge [above] node {} (C2);
  310. \path[->] (C2) edge [above] node {} (C3);
  311. \path[->] (C3) edge [above] node {} (C4);
  312. \path[->] (C4) edge [above] node {} (C5);
  313. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  314. \path[->] (C5) edge [above] node {} (C7);
  315. \path[->] (C6) edge [above] node {} (C7);
  316. \path[->] (C4) edge [above] node {} (C8);
  317. \path[->] (C4) edge [above] node {} (C9);
  318. \path[->] (C7) edge [above] node {} (C10);
  319. \path[->] (C8) edge [above] node {} (C10);
  320. \path[->] (C10) edge [above] node {} (C11);
  321. \end{tikzpicture}
  322. \fi}
  323. {\if\edition\pythonEd\pythonColor
  324. \begin{tikzpicture}[baseline=(current bounding box.center)]
  325. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  326. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  327. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  328. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  329. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  330. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  331. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  332. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  333. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  334. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  335. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  336. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  337. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  338. \path[->] (Prelim) edge [above] node {} (Var);
  339. \path[->] (Var) edge [above] node {} (Reg);
  340. \path[->] (Var) edge [above] node {} (Parse);
  341. \path[->] (Reg) edge [above] node {} (Cond);
  342. \path[->] (Cond) edge [above] node {} (Tuple);
  343. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  344. \path[->] (Cond) edge [above] node {} (Fun);
  345. \path[->] (Tuple) edge [above] node {} (Lam);
  346. \path[->] (Fun) edge [above] node {} (Lam);
  347. \path[->] (Cond) edge [above] node {} (Dyn);
  348. \path[->] (Cond) edge [above] node {} (Loop);
  349. \path[->] (Lam) edge [above] node {} (Gradual);
  350. \path[->] (Dyn) edge [above] node {} (Gradual);
  351. % \path[->] (Dyn) edge [above] node {} (CO);
  352. \path[->] (Gradual) edge [above] node {} (Generic);
  353. \end{tikzpicture}
  354. \fi}
  355. \end{tcolorbox}
  356. \caption{Diagram of chapter dependencies.}
  357. \label{fig:chapter-dependences}
  358. \end{figure}
  359. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  360. the implementation of the compiler and for the input language, so the
  361. reader should be proficient with Racket or Scheme. There are many
  362. excellent resources for learning Scheme and
  363. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  364. %
  365. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  366. both for the implementation of the compiler and for the input language, so the
  367. reader should be proficient with Python. There are many
  368. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  369. %
  370. The support code for this book is in the GitHub repository at
  371. the following location:
  372. \begin{center}\small\texttt
  373. https://github.com/IUCompilerCourse/
  374. \end{center}
  375. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  376. is helpful but not necessary for the reader to have taken a computer
  377. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  378. assembly language that are needed in the compiler.
  379. %
  380. We follow the System V calling
  381. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  382. that we generate works with the runtime system (written in C) when it
  383. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  384. operating systems on Intel hardware.
  385. %
  386. On the Windows operating system, \code{gcc} uses the Microsoft x64
  387. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  388. assembly code that we generate does \emph{not} work with the runtime
  389. system on Windows. One workaround is to use a virtual machine with
  390. Linux as the guest operating system.
  391. \section*{Acknowledgments}
  392. The tradition of compiler construction at Indiana University goes back
  393. to research and courses on programming languages by Daniel Friedman in
  394. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  395. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  396. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  397. the compiler course and continued the development of Chez Scheme.
  398. %
  399. The compiler course evolved to incorporate novel pedagogical ideas
  400. while also including elements of real-world compilers. One of
  401. Friedman's ideas was to split the compiler into many small
  402. passes. Another idea, called ``the game,'' was to test the code
  403. generated by each pass using interpreters.
  404. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  405. developed infrastructure to support this approach and evolved the
  406. course to use even smaller
  407. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  408. design decisions in this book are inspired by the assignment
  409. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  410. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  411. organization of the course made it difficult for students to
  412. understand the rationale for the compiler design. Ghuloum proposed the
  413. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  414. based.
  415. I thank the many students who served as teaching assistants for the
  416. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  417. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  418. garbage collector and x86 interpreter, Michael Vollmer for work on
  419. efficient tail calls, and Michael Vitousek for help with the first
  420. offering of the incremental compiler course at IU.
  421. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  422. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  423. Michael Wollowski for teaching courses based on drafts of this book
  424. and for their feedback. I thank the National Science Foundation for
  425. the grants that helped to support this work: Grant Numbers 1518844,
  426. 1763922, and 1814460.
  427. I thank Ronald Garcia for helping me survive Dybvig's compiler
  428. course in the early 2000s and especially for finding the bug that
  429. sent our garbage collector on a wild goose chase!
  430. \mbox{}\\
  431. \noindent Jeremy G. Siek \\
  432. Bloomington, Indiana
  433. \mainmatter
  434. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  435. \chapter{Preliminaries}
  436. \label{ch:trees-recur}
  437. \setcounter{footnote}{0}
  438. In this chapter we review the basic tools needed to implement a
  439. compiler. Programs are typically input by a programmer as text, that
  440. is, a sequence of characters. The program-as-text representation is
  441. called \emph{concrete syntax}. We use concrete syntax to concisely
  442. write down and talk about programs. Inside the compiler, we use
  443. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  444. that efficiently supports the operations that the compiler needs to
  445. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  446. syntax}\index{subject}{abstract syntax
  447. tree}\index{subject}{AST}\index{subject}{program}
  448. The process of translating concrete syntax to abstract syntax is
  449. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  450. chapter~\ref{ch:parsing}}.
  451. \racket{This book does not cover the theory and implementation of parsing.
  452. We refer the readers interested in parsing to the thorough treatment
  453. of parsing by \citet{Aho:2006wb}.}%
  454. %
  455. \racket{A parser is provided in the support code for translating from
  456. concrete to abstract syntax.}%
  457. %
  458. \python{For now we use Python's \code{ast} module to translate from concrete
  459. to abstract syntax.}
  460. ASTs can be represented inside the compiler in many different ways,
  461. depending on the programming language used to write the compiler.
  462. %
  463. \racket{We use Racket's
  464. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  465. feature to represent ASTs (section~\ref{sec:ast}).}
  466. %
  467. \python{We use Python classes and objects to represent ASTs, especially the
  468. classes defined in the standard \code{ast} module for the Python
  469. source language.}%
  470. %
  471. We use grammars to define the abstract syntax of programming languages
  472. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  473. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  474. recursive functions to construct and deconstruct ASTs
  475. (section~\ref{sec:recursion}). This chapter provides a brief
  476. introduction to these components.
  477. \racket{\index{subject}{struct}}
  478. \python{\index{subject}{class}\index{subject}{object}}
  479. \section{Abstract Syntax Trees}
  480. \label{sec:ast}
  481. Compilers use abstract syntax trees to represent programs because they
  482. often need to ask questions such as, for a given part of a program,
  483. what kind of language feature is it? What are its subparts? Consider
  484. the program on the left and the diagram of its AST on the
  485. right~\eqref{eq:arith-prog}. This program is an addition operation
  486. that has two subparts, a \racket{read}\python{input} operation and a
  487. negation. The negation has another subpart, the integer constant
  488. \code{8}. By using a tree to represent the program, we can easily
  489. follow the links to go from one part of a program to its subparts.
  490. \begin{center}
  491. \begin{minipage}{0.4\textwidth}
  492. {\if\edition\racketEd
  493. \begin{lstlisting}
  494. (+ (read) (- 8))
  495. \end{lstlisting}
  496. \fi}
  497. {\if\edition\pythonEd\pythonColor
  498. \begin{lstlisting}
  499. input_int() + -8
  500. \end{lstlisting}
  501. \fi}
  502. \end{minipage}
  503. \begin{minipage}{0.4\textwidth}
  504. \begin{equation}
  505. \begin{tikzpicture}
  506. \node[draw] (plus) at (0 , 0) {\key{+}};
  507. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  508. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  509. \node[draw] (8) at (1 , -2) {\key{8}};
  510. \draw[->] (plus) to (read);
  511. \draw[->] (plus) to (minus);
  512. \draw[->] (minus) to (8);
  513. \end{tikzpicture}
  514. \label{eq:arith-prog}
  515. \end{equation}
  516. \end{minipage}
  517. \end{center}
  518. We use the standard terminology for trees to describe ASTs: each
  519. rectangle above is called a \emph{node}. The arrows connect a node to its
  520. \emph{children}, which are also nodes. The top-most node is the
  521. \emph{root}. Every node except for the root has a \emph{parent} (the
  522. node of which it is the child). If a node has no children, it is a
  523. \emph{leaf} node; otherwise it is an \emph{internal} node.
  524. \index{subject}{node}
  525. \index{subject}{children}
  526. \index{subject}{root}
  527. \index{subject}{parent}
  528. \index{subject}{leaf}
  529. \index{subject}{internal node}
  530. %% Recall that an \emph{symbolic expression} (S-expression) is either
  531. %% \begin{enumerate}
  532. %% \item an atom, or
  533. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  534. %% where $e_1$ and $e_2$ are each an S-expression.
  535. %% \end{enumerate}
  536. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  537. %% null value \code{'()}, etc. We can create an S-expression in Racket
  538. %% simply by writing a backquote (called a quasi-quote in Racket)
  539. %% followed by the textual representation of the S-expression. It is
  540. %% quite common to use S-expressions to represent a list, such as $a, b
  541. %% ,c$ in the following way:
  542. %% \begin{lstlisting}
  543. %% `(a . (b . (c . ())))
  544. %% \end{lstlisting}
  545. %% Each element of the list is in the first slot of a pair, and the
  546. %% second slot is either the rest of the list or the null value, to mark
  547. %% the end of the list. Such lists are so common that Racket provides
  548. %% special notation for them that removes the need for the periods
  549. %% and so many parenthesis:
  550. %% \begin{lstlisting}
  551. %% `(a b c)
  552. %% \end{lstlisting}
  553. %% The following expression creates an S-expression that represents AST
  554. %% \eqref{eq:arith-prog}.
  555. %% \begin{lstlisting}
  556. %% `(+ (read) (- 8))
  557. %% \end{lstlisting}
  558. %% When using S-expressions to represent ASTs, the convention is to
  559. %% represent each AST node as a list and to put the operation symbol at
  560. %% the front of the list. The rest of the list contains the children. So
  561. %% in the above case, the root AST node has operation \code{`+} and its
  562. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  563. %% diagram \eqref{eq:arith-prog}.
  564. %% To build larger S-expressions one often needs to splice together
  565. %% several smaller S-expressions. Racket provides the comma operator to
  566. %% splice an S-expression into a larger one. For example, instead of
  567. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  568. %% we could have first created an S-expression for AST
  569. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  570. %% S-expression.
  571. %% \begin{lstlisting}
  572. %% (define ast1.4 `(- 8))
  573. %% (define ast1_1 `(+ (read) ,ast1.4))
  574. %% \end{lstlisting}
  575. %% In general, the Racket expression that follows the comma (splice)
  576. %% can be any expression that produces an S-expression.
  577. {\if\edition\racketEd
  578. We define a Racket \code{struct} for each kind of node. For this
  579. chapter we require just two kinds of nodes: one for integer constants
  580. (aka literals\index{subject}{literals})
  581. and one for primitive operations. The following is the \code{struct}
  582. definition for integer constants.\footnote{All the AST structures are
  583. defined in the file \code{utilities.rkt} in the support code.}
  584. \begin{lstlisting}
  585. (struct Int (value))
  586. \end{lstlisting}
  587. An integer node contains just one thing: the integer value.
  588. We establish the convention that \code{struct} names, such
  589. as \code{Int}, are capitalized.
  590. To create an AST node for the integer $8$, we write \INT{8}.
  591. \begin{lstlisting}
  592. (define eight (Int 8))
  593. \end{lstlisting}
  594. We say that the value created by \INT{8} is an
  595. \emph{instance} of the
  596. \code{Int} structure.
  597. The following is the \code{struct} definition for primitive operations.
  598. \begin{lstlisting}
  599. (struct Prim (op args))
  600. \end{lstlisting}
  601. A primitive operation node includes an operator symbol \code{op} and a
  602. list of child arguments called \code{args}. For example, to create an
  603. AST that negates the number $8$, we write the following.
  604. \begin{lstlisting}
  605. (define neg-eight (Prim '- (list eight)))
  606. \end{lstlisting}
  607. Primitive operations may have zero or more children. The \code{read}
  608. operator has zero:
  609. \begin{lstlisting}
  610. (define rd (Prim 'read '()))
  611. \end{lstlisting}
  612. The addition operator has two children:
  613. \begin{lstlisting}
  614. (define ast1_1 (Prim '+ (list rd neg-eight)))
  615. \end{lstlisting}
  616. We have made a design choice regarding the \code{Prim} structure.
  617. Instead of using one structure for many different operations
  618. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  619. structure for each operation, as follows:
  620. \begin{lstlisting}
  621. (struct Read ())
  622. (struct Add (left right))
  623. (struct Neg (value))
  624. \end{lstlisting}
  625. The reason that we choose to use just one structure is that many parts
  626. of the compiler can use the same code for the different primitive
  627. operators, so we might as well just write that code once by using a
  628. single structure.
  629. %
  630. \fi}
  631. {\if\edition\pythonEd\pythonColor
  632. We use a Python \code{class} for each kind of node.
  633. The following is the class definition for
  634. constants (aka literals\index{subject}{literals})
  635. from the Python \code{ast} module.
  636. \begin{lstlisting}
  637. class Constant:
  638. def __init__(self, value):
  639. self.value = value
  640. \end{lstlisting}
  641. An integer constant node includes just one thing: the integer value.
  642. To create an AST node for the integer $8$, we write \INT{8}.
  643. \begin{lstlisting}
  644. eight = Constant(8)
  645. \end{lstlisting}
  646. We say that the value created by \INT{8} is an
  647. \emph{instance} of the \code{Constant} class.
  648. The following is the class definition for unary operators.
  649. \begin{lstlisting}
  650. class UnaryOp:
  651. def __init__(self, op, operand):
  652. self.op = op
  653. self.operand = operand
  654. \end{lstlisting}
  655. The specific operation is specified by the \code{op} parameter. For
  656. example, the class \code{USub} is for unary subtraction.
  657. (More unary operators are introduced in later chapters.) To create an AST that
  658. negates the number $8$, we write the following.
  659. \begin{lstlisting}
  660. neg_eight = UnaryOp(USub(), eight)
  661. \end{lstlisting}
  662. The call to the \code{input\_int} function is represented by the
  663. \code{Call} and \code{Name} classes.
  664. \begin{lstlisting}
  665. class Call:
  666. def __init__(self, func, args):
  667. self.func = func
  668. self.args = args
  669. class Name:
  670. def __init__(self, id):
  671. self.id = id
  672. \end{lstlisting}
  673. To create an AST node that calls \code{input\_int}, we write
  674. \begin{lstlisting}
  675. read = Call(Name('input_int'), [])
  676. \end{lstlisting}
  677. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  678. the \code{BinOp} class for binary operators.
  679. \begin{lstlisting}
  680. class BinOp:
  681. def __init__(self, left, op, right):
  682. self.op = op
  683. self.left = left
  684. self.right = right
  685. \end{lstlisting}
  686. Similar to \code{UnaryOp}, the specific operation is specified by the
  687. \code{op} parameter, which for now is just an instance of the
  688. \code{Add} class. So to create the AST
  689. node that adds negative eight to some user input, we write the following.
  690. \begin{lstlisting}
  691. ast1_1 = BinOp(read, Add(), neg_eight)
  692. \end{lstlisting}
  693. \fi}
  694. To compile a program such as \eqref{eq:arith-prog}, we need to know
  695. that the operation associated with the root node is addition and we
  696. need to be able to access its two
  697. children. \racket{Racket}\python{Python} provides pattern matching to
  698. support these kinds of queries, as we see in
  699. section~\ref{sec:pattern-matching}.
  700. We often write down the concrete syntax of a program even when we
  701. actually have in mind the AST, because the concrete syntax is more
  702. concise. We recommend that you always think of programs as abstract
  703. syntax trees.
  704. \section{Grammars}
  705. \label{sec:grammar}
  706. \index{subject}{integer}
  707. %\index{subject}{constant}
  708. A programming language can be thought of as a \emph{set} of programs.
  709. The set is infinite (that is, one can always create larger programs),
  710. so one cannot simply describe a language by listing all the
  711. programs in the language. Instead we write down a set of rules, a
  712. \emph{context-free grammar}, for building programs. Grammars are often used to
  713. define the concrete syntax of a language, but they can also be used to
  714. describe the abstract syntax. We write our rules in a variant of
  715. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  716. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  717. we describe a small language, named \LangInt{}, that consists of
  718. integers and arithmetic operations.\index{subject}{grammar}
  719. \index{subject}{context-free grammar}
  720. The first grammar rule for the abstract syntax of \LangInt{} says that an
  721. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  722. \begin{equation}
  723. \Exp ::= \INT{\Int} \label{eq:arith-int}
  724. \end{equation}
  725. %
  726. Each rule has a left-hand side and a right-hand side.
  727. If you have an AST node that matches the
  728. right-hand side, then you can categorize it according to the
  729. left-hand side.
  730. %
  731. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  732. are \emph{terminal} symbols and must literally appear in the program for the
  733. rule to be applicable.\index{subject}{terminal}
  734. %
  735. Our grammars do not mention \emph{white space}, that is, delimiter
  736. characters like spaces, tabs, and new lines. White space may be
  737. inserted between symbols for disambiguation and to improve
  738. readability. \index{subject}{white space}
  739. %
  740. A name such as $\Exp$ that is defined by the grammar rules is a
  741. \emph{nonterminal}. \index{subject}{nonterminal}
  742. %
  743. The name $\Int$ is also a nonterminal, but instead of defining it with
  744. a grammar rule, we define it with the following explanation. An
  745. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  746. $-$ (for negative integers), such that the sequence of decimals
  747. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  748. enables the representation of integers using 63 bits, which simplifies
  749. several aspects of compilation.
  750. %
  751. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  752. datatype on a 64-bit machine.}
  753. %
  754. \python{In contrast, integers in Python have unlimited precision, but
  755. the techniques needed to handle unlimited precision fall outside the
  756. scope of this book.}
  757. The second grammar rule is the \READOP{} operation, which receives an
  758. input integer from the user of the program.
  759. \begin{equation}
  760. \Exp ::= \READ{} \label{eq:arith-read}
  761. \end{equation}
  762. The third rule categorizes the negation of an $\Exp$ node as an
  763. $\Exp$.
  764. \begin{equation}
  765. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  766. \end{equation}
  767. We can apply these rules to categorize the ASTs that are in the
  768. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  769. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  770. following AST is an $\Exp$.
  771. \begin{center}
  772. \begin{minipage}{0.5\textwidth}
  773. \NEG{\INT{\code{8}}}
  774. \end{minipage}
  775. \begin{minipage}{0.25\textwidth}
  776. \begin{equation}
  777. \begin{tikzpicture}
  778. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  779. \node[draw, circle] (8) at (0, -1.2) {$8$};
  780. \draw[->] (minus) to (8);
  781. \end{tikzpicture}
  782. \label{eq:arith-neg8}
  783. \end{equation}
  784. \end{minipage}
  785. \end{center}
  786. The next two grammar rules are for addition and subtraction expressions:
  787. \begin{align}
  788. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  789. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  790. \end{align}
  791. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  792. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  793. \eqref{eq:arith-read}, and we have already categorized
  794. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  795. to show that
  796. \[
  797. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  798. \]
  799. is an $\Exp$ in the \LangInt{} language.
  800. If you have an AST for which these rules do not apply, then the
  801. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  802. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  803. because there is no rule for the \key{*} operator. Whenever we
  804. define a language with a grammar, the language includes only those
  805. programs that are justified by the grammar rules.
  806. {\if\edition\pythonEd\pythonColor
  807. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  808. There is a statement for printing the value of an expression
  809. \[
  810. \Stmt{} ::= \PRINT{\Exp}
  811. \]
  812. and a statement that evaluates an expression but ignores the result.
  813. \[
  814. \Stmt{} ::= \EXPR{\Exp}
  815. \]
  816. \fi}
  817. {\if\edition\racketEd
  818. The last grammar rule for \LangInt{} states that there is a
  819. \code{Program} node to mark the top of the whole program:
  820. \[
  821. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  822. \]
  823. The \code{Program} structure is defined as follows:
  824. \begin{lstlisting}
  825. (struct Program (info body))
  826. \end{lstlisting}
  827. where \code{body} is an expression. In further chapters, the \code{info}
  828. part is used to store auxiliary information, but for now it is
  829. just the empty list.
  830. \fi}
  831. {\if\edition\pythonEd\pythonColor
  832. The last grammar rule for \LangInt{} states that there is a
  833. \code{Module} node to mark the top of the whole program:
  834. \[
  835. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  836. \]
  837. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  838. this case, a list of statements.
  839. %
  840. The \code{Module} class is defined as follows
  841. \begin{lstlisting}
  842. class Module:
  843. def __init__(self, body):
  844. self.body = body
  845. \end{lstlisting}
  846. where \code{body} is a list of statements.
  847. \fi}
  848. It is common to have many grammar rules with the same left-hand side
  849. but different right-hand sides, such as the rules for $\Exp$ in the
  850. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  851. combine several right-hand sides into a single rule.
  852. The concrete syntax for \LangInt{} is shown in
  853. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  854. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  855. %
  856. \racket{The \code{read-program} function provided in
  857. \code{utilities.rkt} of the support code reads a program from a file
  858. (the sequence of characters in the concrete syntax of Racket) and
  859. parses it into an abstract syntax tree. Refer to the description of
  860. \code{read-program} in appendix~\ref{appendix:utilities} for more
  861. details.}
  862. %
  863. \python{The \code{parse} function in Python's \code{ast} module
  864. converts the concrete syntax (represented as a string) into an
  865. abstract syntax tree.}
  866. \newcommand{\LintGrammarRacket}{
  867. \begin{array}{rcl}
  868. \Type &::=& \key{Integer} \\
  869. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  870. \MID \CSUB{\Exp}{\Exp}
  871. \end{array}
  872. }
  873. \newcommand{\LintASTRacket}{
  874. \begin{array}{rcl}
  875. \Type &::=& \key{Integer} \\
  876. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  877. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  878. \end{array}
  879. }
  880. \newcommand{\LintGrammarPython}{
  881. \begin{array}{rcl}
  882. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  883. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  884. \end{array}
  885. }
  886. \newcommand{\LintASTPython}{
  887. \begin{array}{rcl}
  888. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  889. \itm{unaryop} &::= & \code{USub()} \\
  890. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  891. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp} \\
  892. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  893. \end{array}
  894. }
  895. \begin{figure}[tp]
  896. \begin{tcolorbox}[colback=white]
  897. {\if\edition\racketEd
  898. \[
  899. \begin{array}{l}
  900. \LintGrammarRacket \\
  901. \begin{array}{rcl}
  902. \LangInt{} &::=& \Exp
  903. \end{array}
  904. \end{array}
  905. \]
  906. \fi}
  907. {\if\edition\pythonEd\pythonColor
  908. \[
  909. \begin{array}{l}
  910. \LintGrammarPython \\
  911. \begin{array}{rcl}
  912. \LangInt{} &::=& \Stmt^{*}
  913. \end{array}
  914. \end{array}
  915. \]
  916. \fi}
  917. \end{tcolorbox}
  918. \caption{The concrete syntax of \LangInt{}.}
  919. \label{fig:r0-concrete-syntax}
  920. \end{figure}
  921. \begin{figure}[tp]
  922. \begin{tcolorbox}[colback=white]
  923. {\if\edition\racketEd
  924. \[
  925. \begin{array}{l}
  926. \LintASTRacket{} \\
  927. \begin{array}{rcl}
  928. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  929. \end{array}
  930. \end{array}
  931. \]
  932. \fi}
  933. {\if\edition\pythonEd\pythonColor
  934. \[
  935. \begin{array}{l}
  936. \LintASTPython\\
  937. \begin{array}{rcl}
  938. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  939. \end{array}
  940. \end{array}
  941. \]
  942. \fi}
  943. \end{tcolorbox}
  944. \python{
  945. \index{subject}{Constant@\texttt{Constant}}
  946. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  947. \index{subject}{USub@\texttt{USub}}
  948. \index{subject}{inputint@\texttt{input\_int}}
  949. \index{subject}{Call@\texttt{Call}}
  950. \index{subject}{Name@\texttt{Name}}
  951. \index{subject}{BinOp@\texttt{BinOp}}
  952. \index{subject}{Add@\texttt{Add}}
  953. \index{subject}{Sub@\texttt{Sub}}
  954. \index{subject}{print@\texttt{print}}
  955. \index{subject}{Expr@\texttt{Expr}}
  956. \index{subject}{Module@\texttt{Module}}
  957. }
  958. \caption{The abstract syntax of \LangInt{}.}
  959. \label{fig:r0-syntax}
  960. \end{figure}
  961. \section{Pattern Matching}
  962. \label{sec:pattern-matching}
  963. As mentioned in section~\ref{sec:ast}, compilers often need to access
  964. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  965. provides the \texttt{match} feature to access the parts of a value.
  966. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  967. \begin{center}
  968. \begin{minipage}{0.5\textwidth}
  969. {\if\edition\racketEd
  970. \begin{lstlisting}
  971. (match ast1_1
  972. [(Prim op (list child1 child2))
  973. (print op)])
  974. \end{lstlisting}
  975. \fi}
  976. {\if\edition\pythonEd\pythonColor
  977. \begin{lstlisting}
  978. match ast1_1:
  979. case BinOp(child1, op, child2):
  980. print(op)
  981. \end{lstlisting}
  982. \fi}
  983. \end{minipage}
  984. \end{center}
  985. {\if\edition\racketEd
  986. %
  987. In this example, the \texttt{match} form checks whether the AST
  988. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  989. three pattern variables \texttt{op}, \texttt{child1}, and
  990. \texttt{child2}. In general, a match clause consists of a
  991. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  992. recursively defined to be a pattern variable, a structure name
  993. followed by a pattern for each of the structure's arguments, or an
  994. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  995. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  996. and chapter 9 of The Racket
  997. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  998. for complete descriptions of \code{match}.)
  999. %
  1000. The body of a match clause may contain arbitrary Racket code. The
  1001. pattern variables can be used in the scope of the body, such as
  1002. \code{op} in \code{(print op)}.
  1003. %
  1004. \fi}
  1005. %
  1006. %
  1007. {\if\edition\pythonEd\pythonColor
  1008. %
  1009. In the above example, the \texttt{match} form checks whether the AST
  1010. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1011. three pattern variables \texttt{child1}, \texttt{op}, and
  1012. \texttt{child2}, and then prints out the operator. In general, each
  1013. \code{case} consists of a \emph{pattern} and a
  1014. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  1015. to be either a pattern variable, a class name followed by a pattern
  1016. for each of its constructor's arguments, or other
  1017. literals\index{subject}{literals} such as strings, lists, etc.
  1018. %
  1019. The body of each \code{case} may contain arbitrary Python code. The
  1020. pattern variables can be used in the body, such as \code{op} in
  1021. \code{print(op)}.
  1022. %
  1023. \fi}
  1024. A \code{match} form may contain several clauses, as in the following
  1025. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1026. the AST. The \code{match} proceeds through the clauses in order,
  1027. checking whether the pattern can match the input AST. The body of the
  1028. first clause that matches is executed. The output of \code{leaf} for
  1029. several ASTs is shown on the right side of the following:
  1030. \begin{center}
  1031. \begin{minipage}{0.6\textwidth}
  1032. {\if\edition\racketEd
  1033. \begin{lstlisting}
  1034. (define (leaf arith)
  1035. (match arith
  1036. [(Int n) #t]
  1037. [(Prim 'read '()) #t]
  1038. [(Prim '- (list e1)) #f]
  1039. [(Prim '+ (list e1 e2)) #f]
  1040. [(Prim '- (list e1 e2)) #f]))
  1041. (leaf (Prim 'read '()))
  1042. (leaf (Prim '- (list (Int 8))))
  1043. (leaf (Int 8))
  1044. \end{lstlisting}
  1045. \fi}
  1046. {\if\edition\pythonEd\pythonColor
  1047. \begin{lstlisting}
  1048. def leaf(arith):
  1049. match arith:
  1050. case Constant(n):
  1051. return True
  1052. case Call(Name('input_int'), []):
  1053. return True
  1054. case UnaryOp(USub(), e1):
  1055. return False
  1056. case BinOp(e1, Add(), e2):
  1057. return False
  1058. case BinOp(e1, Sub(), e2):
  1059. return False
  1060. print(leaf(Call(Name('input_int'), [])))
  1061. print(leaf(UnaryOp(USub(), eight)))
  1062. print(leaf(Constant(8)))
  1063. \end{lstlisting}
  1064. \fi}
  1065. \end{minipage}
  1066. \vrule
  1067. \begin{minipage}{0.25\textwidth}
  1068. {\if\edition\racketEd
  1069. \begin{lstlisting}
  1070. #t
  1071. #f
  1072. #t
  1073. \end{lstlisting}
  1074. \fi}
  1075. {\if\edition\pythonEd\pythonColor
  1076. \begin{lstlisting}
  1077. True
  1078. False
  1079. True
  1080. \end{lstlisting}
  1081. \fi}
  1082. \end{minipage}
  1083. \index{subject}{True@\TRUE{}}
  1084. \index{subject}{False@\FALSE{}}
  1085. \end{center}
  1086. When constructing a \code{match} expression, we refer to the grammar
  1087. definition to identify which nonterminal we are expecting to match
  1088. against, and then we make sure that (1) we have one
  1089. \racket{clause}\python{case} for each alternative of that nonterminal
  1090. and (2) the pattern in each \racket{clause}\python{case}
  1091. corresponds to the corresponding right-hand side of a grammar
  1092. rule. For the \code{match} in the \code{leaf} function, we refer to
  1093. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1094. nonterminal has four alternatives, so the \code{match} has four
  1095. \racket{clauses}\python{cases}. The pattern in each
  1096. \racket{clause}\python{case} corresponds to the right-hand side of a
  1097. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1098. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1099. translating from grammars to patterns, replace nonterminals such as
  1100. $\Exp$ with pattern variables of your choice (for example, \code{e1} and
  1101. \code{e2}).
  1102. \section{Recursive Functions}
  1103. \label{sec:recursion}
  1104. \index{subject}{recursive function}
  1105. Programs are inherently recursive. For example, an expression is often
  1106. made of smaller expressions. Thus, the natural way to process an
  1107. entire program is to use a recursive function. As a first example of
  1108. such a recursive function, we define the function \code{is\_exp} as
  1109. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1110. value and determine whether or not it is an expression in \LangInt{}.
  1111. %
  1112. We say that a function is defined by \emph{structural recursion} if
  1113. it is defined using a sequence of match \racket{clauses}\python{cases}
  1114. that correspond to a grammar and the body of each
  1115. \racket{clause}\python{case} makes a recursive call on each child
  1116. node.\footnote{This principle of structuring code according to the
  1117. data definition is advocated in the book \emph{How to Design
  1118. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1119. second function, named \code{stmt}, that recognizes whether a value
  1120. is a \LangInt{} statement.} \python{Finally, }
  1121. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1122. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1123. In general, we can write one recursive function to handle each
  1124. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1125. two examples at the bottom of the figure, the first is in
  1126. \LangInt{} and the second is not.
  1127. \begin{figure}[tp]
  1128. \begin{tcolorbox}[colback=white]
  1129. {\if\edition\racketEd
  1130. \begin{lstlisting}
  1131. (define (is_exp ast)
  1132. (match ast
  1133. [(Int n) #t]
  1134. [(Prim 'read '()) #t]
  1135. [(Prim '- (list e)) (is_exp e)]
  1136. [(Prim '+ (list e1 e2))
  1137. (and (is_exp e1) (is_exp e2))]
  1138. [(Prim '- (list e1 e2))
  1139. (and (is_exp e1) (is_exp e2))]
  1140. [else #f]))
  1141. (define (is_Lint ast)
  1142. (match ast
  1143. [(Program '() e) (is_exp e)]
  1144. [else #f]))
  1145. (is_Lint (Program '() ast1_1)
  1146. (is_Lint (Program '()
  1147. (Prim '* (list (Prim 'read '())
  1148. (Prim '+ (list (Int 8)))))))
  1149. \end{lstlisting}
  1150. \fi}
  1151. {\if\edition\pythonEd\pythonColor
  1152. \begin{lstlisting}
  1153. def is_exp(e):
  1154. match e:
  1155. case Constant(n):
  1156. return True
  1157. case Call(Name('input_int'), []):
  1158. return True
  1159. case UnaryOp(USub(), e1):
  1160. return is_exp(e1)
  1161. case BinOp(e1, Add(), e2):
  1162. return is_exp(e1) and is_exp(e2)
  1163. case BinOp(e1, Sub(), e2):
  1164. return is_exp(e1) and is_exp(e2)
  1165. case _:
  1166. return False
  1167. def stmt(s):
  1168. match s:
  1169. case Expr(Call(Name('print'), [e])):
  1170. return is_exp(e)
  1171. case Expr(e):
  1172. return is_exp(e)
  1173. case _:
  1174. return False
  1175. def is_Lint(p):
  1176. match p:
  1177. case Module(body):
  1178. return all([stmt(s) for s in body])
  1179. case _:
  1180. return False
  1181. print(is_Lint(Module([Expr(ast1_1)])))
  1182. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1183. UnaryOp(Add(), Constant(8))))])))
  1184. \end{lstlisting}
  1185. \fi}
  1186. \end{tcolorbox}
  1187. \caption{Example of recursive functions for \LangInt{}. These functions
  1188. recognize whether an AST is in \LangInt{}.}
  1189. \label{fig:exp-predicate}
  1190. \end{figure}
  1191. %% You may be tempted to merge the two functions into one, like this:
  1192. %% \begin{center}
  1193. %% \begin{minipage}{0.5\textwidth}
  1194. %% \begin{lstlisting}
  1195. %% (define (Lint ast)
  1196. %% (match ast
  1197. %% [(Int n) #t]
  1198. %% [(Prim 'read '()) #t]
  1199. %% [(Prim '- (list e)) (Lint e)]
  1200. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1201. %% [(Program '() e) (Lint e)]
  1202. %% [else #f]))
  1203. %% \end{lstlisting}
  1204. %% \end{minipage}
  1205. %% \end{center}
  1206. %% %
  1207. %% Sometimes such a trick will save a few lines of code, especially when
  1208. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1209. %% \emph{not} recommended because it can get you into trouble.
  1210. %% %
  1211. %% For example, the above function is subtly wrong:
  1212. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1213. %% returns true when it should return false.
  1214. \section{Interpreters}
  1215. \label{sec:interp_Lint}
  1216. \index{subject}{interpreter}
  1217. The behavior of a program is defined by the specification of the
  1218. programming language.
  1219. %
  1220. \racket{For example, the Scheme language is defined in the report by
  1221. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1222. reference manual~\citep{plt-tr}.}
  1223. %
  1224. \python{For example, the Python language is defined in the Python
  1225. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1226. %
  1227. In this book we use interpreters to specify each language that we
  1228. consider. An interpreter that is designated as the definition of a
  1229. language is called a \emph{definitional
  1230. interpreter}~\citep{reynolds72:_def_interp}.
  1231. \index{subject}{definitional interpreter} We warm up by creating a
  1232. definitional interpreter for the \LangInt{} language. This interpreter
  1233. serves as a second example of structural recursion. The definition of the
  1234. \code{interp\_Lint} function is shown in
  1235. figure~\ref{fig:interp_Lint}.
  1236. %
  1237. \racket{The body of the function is a match on the input program
  1238. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1239. which in turn has one match clause per grammar rule for \LangInt{}
  1240. expressions.}
  1241. %
  1242. \python{The body of the function matches on the \code{Module} AST node
  1243. and then invokes \code{interp\_stmt} on each statement in the
  1244. module. The \code{interp\_stmt} function includes a case for each
  1245. grammar rule of the \Stmt{} nonterminal and it calls
  1246. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1247. function includes a case for each grammar rule of the \Exp{}
  1248. nonterminal.}
  1249. \begin{figure}[tp]
  1250. \begin{tcolorbox}[colback=white]
  1251. {\if\edition\racketEd
  1252. \begin{lstlisting}
  1253. (define (interp_exp e)
  1254. (match e
  1255. [(Int n) n]
  1256. [(Prim 'read '())
  1257. (define r (read))
  1258. (cond [(fixnum? r) r]
  1259. [else (error 'interp_exp "read expected an integer" r)])]
  1260. [(Prim '- (list e))
  1261. (define v (interp_exp e))
  1262. (fx- 0 v)]
  1263. [(Prim '+ (list e1 e2))
  1264. (define v1 (interp_exp e1))
  1265. (define v2 (interp_exp e2))
  1266. (fx+ v1 v2)]
  1267. [(Prim '- (list e1 e2))
  1268. (define v1 (interp_exp e1))
  1269. (define v2 (interp_exp e2))
  1270. (fx- v1 v2)]))
  1271. (define (interp_Lint p)
  1272. (match p
  1273. [(Program '() e) (interp_exp e)]))
  1274. \end{lstlisting}
  1275. \fi}
  1276. {\if\edition\pythonEd\pythonColor
  1277. \begin{lstlisting}
  1278. def interp_exp(e):
  1279. match e:
  1280. case BinOp(left, Add(), right):
  1281. l = interp_exp(left); r = interp_exp(right)
  1282. return l + r
  1283. case BinOp(left, Sub(), right):
  1284. l = interp_exp(left); r = interp_exp(right)
  1285. return l - r
  1286. case UnaryOp(USub(), v):
  1287. return - interp_exp(v)
  1288. case Constant(value):
  1289. return value
  1290. case Call(Name('input_int'), []):
  1291. return int(input())
  1292. def interp_stmt(s):
  1293. match s:
  1294. case Expr(Call(Name('print'), [arg])):
  1295. print(interp_exp(arg))
  1296. case Expr(value):
  1297. interp_exp(value)
  1298. def interp_Lint(p):
  1299. match p:
  1300. case Module(body):
  1301. for s in body:
  1302. interp_stmt(s)
  1303. \end{lstlisting}
  1304. \fi}
  1305. \end{tcolorbox}
  1306. \caption{Interpreter for the \LangInt{} language.}
  1307. \label{fig:interp_Lint}
  1308. \end{figure}
  1309. Let us consider the result of interpreting a few \LangInt{} programs. The
  1310. following program adds two integers:
  1311. {\if\edition\racketEd
  1312. \begin{lstlisting}
  1313. (+ 10 32)
  1314. \end{lstlisting}
  1315. \fi}
  1316. {\if\edition\pythonEd\pythonColor
  1317. \begin{lstlisting}
  1318. print(10 + 32)
  1319. \end{lstlisting}
  1320. \fi}
  1321. %
  1322. \noindent The result is \key{42}, the answer to life, the universe,
  1323. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1324. the Galaxy} by Douglas Adams.}
  1325. %
  1326. We wrote this program in concrete syntax, whereas the parsed
  1327. abstract syntax is
  1328. {\if\edition\racketEd
  1329. \begin{lstlisting}
  1330. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1331. \end{lstlisting}
  1332. \fi}
  1333. {\if\edition\pythonEd\pythonColor
  1334. \begin{lstlisting}
  1335. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1336. \end{lstlisting}
  1337. \fi}
  1338. The following program demonstrates that expressions may be nested within
  1339. each other, in this case nesting several additions and negations.
  1340. {\if\edition\racketEd
  1341. \begin{lstlisting}
  1342. (+ 10 (- (+ 12 20)))
  1343. \end{lstlisting}
  1344. \fi}
  1345. {\if\edition\pythonEd\pythonColor
  1346. \begin{lstlisting}
  1347. print(10 + -(12 + 20))
  1348. \end{lstlisting}
  1349. \fi}
  1350. %
  1351. \noindent What is the result of this program?
  1352. {\if\edition\racketEd
  1353. As mentioned previously, the \LangInt{} language does not support
  1354. arbitrarily large integers but only $63$-bit integers, so we
  1355. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1356. in Racket.
  1357. Suppose that
  1358. \[
  1359. n = 999999999999999999
  1360. \]
  1361. which indeed fits in $63$ bits. What happens when we run the
  1362. following program in our interpreter?
  1363. \begin{lstlisting}
  1364. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1365. \end{lstlisting}
  1366. It produces the following error:
  1367. \begin{lstlisting}
  1368. fx+: result is not a fixnum
  1369. \end{lstlisting}
  1370. We establish the convention that if running the definitional
  1371. interpreter on a program produces an error, then the meaning of that
  1372. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1373. error is a \code{trapped-error}. A compiler for the language is under
  1374. no obligation regarding programs with unspecified behavior; it does
  1375. not have to produce an executable, and if it does, that executable can
  1376. do anything. On the other hand, if the error is a
  1377. \code{trapped-error}, then the compiler must produce an executable and
  1378. it is required to report that an error occurred. To signal an error,
  1379. exit with a return code of \code{255}. The interpreters in chapters
  1380. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1381. \code{trapped-error}.
  1382. \fi}
  1383. % TODO: how to deal with too-large integers in the Python interpreter?
  1384. %% This convention applies to the languages defined in this
  1385. %% book, as a way to simplify the student's task of implementing them,
  1386. %% but this convention is not applicable to all programming languages.
  1387. %%
  1388. The last feature of the \LangInt{} language, the \READOP{} operation,
  1389. prompts the user of the program for an integer. Recall that program
  1390. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1391. \code{8}. So, if we run {\if\edition\racketEd
  1392. \begin{lstlisting}
  1393. (interp_Lint (Program '() ast1_1))
  1394. \end{lstlisting}
  1395. \fi}
  1396. {\if\edition\pythonEd\pythonColor
  1397. \begin{lstlisting}
  1398. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1399. \end{lstlisting}
  1400. \fi}
  1401. \noindent and if the input is \code{50}, the result is \code{42}.
  1402. We include the \READOP{} operation in \LangInt{} so that a clever
  1403. student cannot implement a compiler for \LangInt{} that simply runs
  1404. the interpreter during compilation to obtain the output and then
  1405. generates the trivial code to produce the output.\footnote{Yes, a
  1406. clever student did this in the first instance of this course!}
  1407. The job of a compiler is to translate a program in one language into a
  1408. program in another language so that the output program behaves the
  1409. same way as the input program. This idea is depicted in the
  1410. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1411. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1412. Given a compiler that translates from language $\mathcal{L}_1$ to
  1413. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1414. compiler must translate it into some program $P_2$ such that
  1415. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1416. same input $i$ yields the same output $o$.
  1417. \begin{equation} \label{eq:compile-correct}
  1418. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1419. \node (p1) at (0, 0) {$P_1$};
  1420. \node (p2) at (3, 0) {$P_2$};
  1421. \node (o) at (3, -2.5) {$o$};
  1422. \path[->] (p1) edge [above] node {compile} (p2);
  1423. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1424. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1425. \end{tikzpicture}
  1426. \end{equation}
  1427. \python{We establish the convention that if running the definitional
  1428. interpreter on a program produces an error, then the meaning of that
  1429. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1430. unless the exception raised is a \code{TrappedError}. A compiler for
  1431. the language is under no obligation regarding programs with
  1432. unspecified behavior; it does not have to produce an executable, and
  1433. if it does, that executable can do anything. On the other hand, if
  1434. the error is a \code{TrappedError}, then the compiler must produce
  1435. an executable and it is required to report that an error
  1436. occurred. To signal an error, exit with a return code of \code{255}.
  1437. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1438. section \ref{sec:arrays} use \code{TrappedError}.}
  1439. In the next section we see our first example of a compiler.
  1440. \section{Example Compiler: A Partial Evaluator}
  1441. \label{sec:partial-evaluation}
  1442. In this section we consider a compiler that translates \LangInt{}
  1443. programs into \LangInt{} programs that may be more efficient. The
  1444. compiler eagerly computes the parts of the program that do not depend
  1445. on any inputs, a process known as \emph{partial
  1446. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1447. For example, given the following program
  1448. {\if\edition\racketEd
  1449. \begin{lstlisting}
  1450. (+ (read) (- (+ 5 3)))
  1451. \end{lstlisting}
  1452. \fi}
  1453. {\if\edition\pythonEd\pythonColor
  1454. \begin{lstlisting}
  1455. print(input_int() + -(5 + 3) )
  1456. \end{lstlisting}
  1457. \fi}
  1458. \noindent our compiler translates it into the program
  1459. {\if\edition\racketEd
  1460. \begin{lstlisting}
  1461. (+ (read) -8)
  1462. \end{lstlisting}
  1463. \fi}
  1464. {\if\edition\pythonEd\pythonColor
  1465. \begin{lstlisting}
  1466. print(input_int() + -8)
  1467. \end{lstlisting}
  1468. \fi}
  1469. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1470. evaluator for the \LangInt{} language. The output of the partial evaluator
  1471. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1472. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1473. whereas the code for partially evaluating the negation and addition
  1474. operations is factored into three auxiliary functions:
  1475. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1476. functions is the output of partially evaluating the children.
  1477. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1478. arguments are integers and if they are, perform the appropriate
  1479. arithmetic. Otherwise, they create an AST node for the arithmetic
  1480. operation.
  1481. \begin{figure}[tp]
  1482. \begin{tcolorbox}[colback=white]
  1483. {\if\edition\racketEd
  1484. \begin{lstlisting}
  1485. (define (pe_neg r)
  1486. (match r
  1487. [(Int n) (Int (fx- 0 n))]
  1488. [else (Prim '- (list r))]))
  1489. (define (pe_add r1 r2)
  1490. (match* (r1 r2)
  1491. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1492. [(_ _) (Prim '+ (list r1 r2))]))
  1493. (define (pe_sub r1 r2)
  1494. (match* (r1 r2)
  1495. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1496. [(_ _) (Prim '- (list r1 r2))]))
  1497. (define (pe_exp e)
  1498. (match e
  1499. [(Int n) (Int n)]
  1500. [(Prim 'read '()) (Prim 'read '())]
  1501. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1502. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1503. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1504. (define (pe_Lint p)
  1505. (match p
  1506. [(Program '() e) (Program '() (pe_exp e))]))
  1507. \end{lstlisting}
  1508. \fi}
  1509. {\if\edition\pythonEd\pythonColor
  1510. \begin{lstlisting}
  1511. def pe_neg(r):
  1512. match r:
  1513. case Constant(n):
  1514. return Constant(-n)
  1515. case _:
  1516. return UnaryOp(USub(), r)
  1517. def pe_add(r1, r2):
  1518. match (r1, r2):
  1519. case (Constant(n1), Constant(n2)):
  1520. return Constant(n1 + n2)
  1521. case _:
  1522. return BinOp(r1, Add(), r2)
  1523. def pe_sub(r1, r2):
  1524. match (r1, r2):
  1525. case (Constant(n1), Constant(n2)):
  1526. return Constant(n1 - n2)
  1527. case _:
  1528. return BinOp(r1, Sub(), r2)
  1529. def pe_exp(e):
  1530. match e:
  1531. case BinOp(left, Add(), right):
  1532. return pe_add(pe_exp(left), pe_exp(right))
  1533. case BinOp(left, Sub(), right):
  1534. return pe_sub(pe_exp(left), pe_exp(right))
  1535. case UnaryOp(USub(), v):
  1536. return pe_neg(pe_exp(v))
  1537. case Constant(value):
  1538. return e
  1539. case Call(Name('input_int'), []):
  1540. return e
  1541. def pe_stmt(s):
  1542. match s:
  1543. case Expr(Call(Name('print'), [arg])):
  1544. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1545. case Expr(value):
  1546. return Expr(pe_exp(value))
  1547. def pe_P_int(p):
  1548. match p:
  1549. case Module(body):
  1550. new_body = [pe_stmt(s) for s in body]
  1551. return Module(new_body)
  1552. \end{lstlisting}
  1553. \fi}
  1554. \end{tcolorbox}
  1555. \caption{A partial evaluator for \LangInt{}.}
  1556. \label{fig:pe-arith}
  1557. \end{figure}
  1558. To gain some confidence that the partial evaluator is correct, we can
  1559. test whether it produces programs that produce the same result as the
  1560. input programs. That is, we can test whether it satisfies the diagram
  1561. of \eqref{eq:compile-correct}.
  1562. %
  1563. {\if\edition\racketEd
  1564. The following code runs the partial evaluator on several examples and
  1565. tests the output program. The \texttt{parse-program} and
  1566. \texttt{assert} functions are defined in
  1567. appendix~\ref{appendix:utilities}.\\
  1568. \begin{minipage}{1.0\textwidth}
  1569. \begin{lstlisting}
  1570. (define (test_pe p)
  1571. (assert "testing pe_Lint"
  1572. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1573. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1574. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1575. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1576. \end{lstlisting}
  1577. \end{minipage}
  1578. \fi}
  1579. % TODO: python version of testing the PE
  1580. \begin{exercise}\normalfont\normalsize
  1581. Create three programs in the \LangInt{} language and test whether
  1582. partially evaluating them with \code{pe\_Lint} and then
  1583. interpreting them with \code{interp\_Lint} gives the same result
  1584. as directly interpreting them with \code{interp\_Lint}.
  1585. \end{exercise}
  1586. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1587. \chapter{Integers and Variables}
  1588. \label{ch:Lvar}
  1589. \setcounter{footnote}{0}
  1590. This chapter covers compiling a subset of
  1591. \racket{Racket}\python{Python} to x86-64 assembly
  1592. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1593. integer arithmetic and local variables. We often refer to x86-64
  1594. simply as x86. The chapter first describes the \LangVar{} language
  1595. (section~\ref{sec:s0}) and then introduces x86 assembly
  1596. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1597. discuss only the instructions needed for compiling \LangVar{}. We
  1598. introduce more x86 instructions in subsequent chapters. After
  1599. introducing \LangVar{} and x86, we reflect on their differences and
  1600. create a plan to break down the translation from \LangVar{} to x86
  1601. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1602. the chapter gives detailed hints regarding each step. We aim to give
  1603. enough hints that the well-prepared reader, together with a few
  1604. friends, can implement a compiler from \LangVar{} to x86 in a short
  1605. time. To suggest the scale of this first compiler, we note that the
  1606. instructor solution for the \LangVar{} compiler is approximately
  1607. \racket{500}\python{300} lines of code.
  1608. \section{The \LangVar{} Language}
  1609. \label{sec:s0}
  1610. \index{subject}{variable}
  1611. The \LangVar{} language extends the \LangInt{} language with
  1612. variables. The concrete syntax of the \LangVar{} language is defined
  1613. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1614. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1615. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1616. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1617. \key{-} is a unary operator, and \key{+} is a binary operator.
  1618. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1619. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1620. the top of the program.
  1621. %% The $\itm{info}$
  1622. %% field of the \key{Program} structure contains an \emph{association
  1623. %% list} (a list of key-value pairs) that is used to communicate
  1624. %% auxiliary data from one compiler pass the next.
  1625. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1626. exhibit several compilation techniques.
  1627. \newcommand{\LvarGrammarRacket}{
  1628. \begin{array}{rcl}
  1629. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1630. \end{array}
  1631. }
  1632. \newcommand{\LvarASTRacket}{
  1633. \begin{array}{rcl}
  1634. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1635. \end{array}
  1636. }
  1637. \newcommand{\LvarGrammarPython}{
  1638. \begin{array}{rcl}
  1639. \Exp &::=& \Var{} \\
  1640. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1641. \end{array}
  1642. }
  1643. \newcommand{\LvarASTPython}{
  1644. \begin{array}{rcl}
  1645. \Exp{} &::=& \VAR{\Var{}} \\
  1646. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1647. \end{array}
  1648. }
  1649. \begin{figure}[tp]
  1650. \centering
  1651. \begin{tcolorbox}[colback=white]
  1652. {\if\edition\racketEd
  1653. \[
  1654. \begin{array}{l}
  1655. \gray{\LintGrammarRacket{}} \\ \hline
  1656. \LvarGrammarRacket{} \\
  1657. \begin{array}{rcl}
  1658. \LangVarM{} &::=& \Exp
  1659. \end{array}
  1660. \end{array}
  1661. \]
  1662. \fi}
  1663. {\if\edition\pythonEd\pythonColor
  1664. \[
  1665. \begin{array}{l}
  1666. \gray{\LintGrammarPython} \\ \hline
  1667. \LvarGrammarPython \\
  1668. \begin{array}{rcl}
  1669. \LangVarM{} &::=& \Stmt^{*}
  1670. \end{array}
  1671. \end{array}
  1672. \]
  1673. \fi}
  1674. \end{tcolorbox}
  1675. \caption{The concrete syntax of \LangVar{}.}
  1676. \label{fig:Lvar-concrete-syntax}
  1677. \end{figure}
  1678. \begin{figure}[tp]
  1679. \centering
  1680. \begin{tcolorbox}[colback=white]
  1681. {\if\edition\racketEd
  1682. \[
  1683. \begin{array}{l}
  1684. \gray{\LintASTRacket{}} \\ \hline
  1685. \LvarASTRacket \\
  1686. \begin{array}{rcl}
  1687. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1688. \end{array}
  1689. \end{array}
  1690. \]
  1691. \fi}
  1692. {\if\edition\pythonEd\pythonColor
  1693. \[
  1694. \begin{array}{l}
  1695. \gray{\LintASTPython}\\ \hline
  1696. \LvarASTPython \\
  1697. \begin{array}{rcl}
  1698. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1699. \end{array}
  1700. \end{array}
  1701. \]
  1702. \fi}
  1703. \end{tcolorbox}
  1704. \caption{The abstract syntax of \LangVar{}.}
  1705. \label{fig:Lvar-syntax}
  1706. \end{figure}
  1707. {\if\edition\racketEd
  1708. Let us dive further into the syntax and semantics of the \LangVar{}
  1709. language. The \key{let} feature defines a variable for use within its
  1710. body and initializes the variable with the value of an expression.
  1711. The abstract syntax for \key{let} is shown in
  1712. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1713. \begin{lstlisting}
  1714. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1715. \end{lstlisting}
  1716. For example, the following program initializes \code{x} to $32$ and then
  1717. evaluates the body \code{(+ 10 x)}, producing $42$.
  1718. \begin{lstlisting}
  1719. (let ([x (+ 12 20)]) (+ 10 x))
  1720. \end{lstlisting}
  1721. \fi}
  1722. %
  1723. {\if\edition\pythonEd\pythonColor
  1724. %
  1725. The \LangVar{} language includes assignment statements, which define a
  1726. variable for use in later statements and initializes the variable with
  1727. the value of an expression. The abstract syntax for assignment is
  1728. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1729. assignment is \index{subject}{Assign@\texttt{Assign}}
  1730. \begin{lstlisting}
  1731. |$\itm{var}$| = |$\itm{exp}$|
  1732. \end{lstlisting}
  1733. For example, the following program initializes the variable \code{x}
  1734. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1735. \begin{lstlisting}
  1736. x = 12 + 20
  1737. print(10 + x)
  1738. \end{lstlisting}
  1739. \fi}
  1740. {\if\edition\racketEd
  1741. %
  1742. When there are multiple \key{let}s for the same variable, the closest
  1743. enclosing \key{let} is used. That is, variable definitions overshadow
  1744. prior definitions. Consider the following program with two \key{let}s
  1745. that define two variables named \code{x}. Can you figure out the
  1746. result?
  1747. \begin{lstlisting}
  1748. (let ([x 32]) (+ (let ([x 10]) x) x))
  1749. \end{lstlisting}
  1750. For the purposes of depicting which variable occurrences correspond to
  1751. which definitions, the following shows the \code{x}'s annotated with
  1752. subscripts to distinguish them. Double-check that your answer for the
  1753. previous program is the same as your answer for this annotated version
  1754. of the program.
  1755. \begin{lstlisting}
  1756. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1757. \end{lstlisting}
  1758. The initializing expression is always evaluated before the body of the
  1759. \key{let}, so in the following, the \key{read} for \code{x} is
  1760. performed before the \key{read} for \code{y}. Given the input
  1761. $52$ then $10$, the following produces $42$ (not $-42$).
  1762. \begin{lstlisting}
  1763. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1764. \end{lstlisting}
  1765. \fi}
  1766. \subsection{Extensible Interpreters via Method Overriding}
  1767. \label{sec:extensible-interp}
  1768. \index{subject}{method overriding}
  1769. To prepare for discussing the interpreter of \LangVar{}, we explain
  1770. why we implement it in an object-oriented style. Throughout this book
  1771. we define many interpreters, one for each language that we
  1772. study. Because each language builds on the prior one, there is a lot
  1773. of commonality between these interpreters. We want to write down the
  1774. common parts just once instead of many times. A naive interpreter for
  1775. \LangVar{} would handle the \racket{cases for variables and
  1776. \code{let}} \python{case for variables} but dispatch to an
  1777. interpreter for \LangInt{} in the rest of the cases. The following
  1778. code sketches this idea. (We explain the \code{env} parameter in
  1779. section~\ref{sec:interp-Lvar}.)
  1780. \begin{center}
  1781. {\if\edition\racketEd
  1782. \begin{minipage}{0.45\textwidth}
  1783. \begin{lstlisting}
  1784. (define ((interp_Lint env) e)
  1785. (match e
  1786. [(Prim '- (list e1))
  1787. (fx- 0 ((interp_Lint env) e1))]
  1788. ...))
  1789. \end{lstlisting}
  1790. \end{minipage}
  1791. \begin{minipage}{0.45\textwidth}
  1792. \begin{lstlisting}
  1793. (define ((interp_Lvar env) e)
  1794. (match e
  1795. [(Var x)
  1796. (dict-ref env x)]
  1797. [(Let x e body)
  1798. (define v ((interp_Lvar env) e))
  1799. (define env^ (dict-set env x v))
  1800. ((interp_Lvar env^) body)]
  1801. [else ((interp_Lint env) e)]))
  1802. \end{lstlisting}
  1803. \end{minipage}
  1804. \fi}
  1805. {\if\edition\pythonEd\pythonColor
  1806. \begin{minipage}{0.45\textwidth}
  1807. \begin{lstlisting}
  1808. def interp_Lint(e, env):
  1809. match e:
  1810. case UnaryOp(USub(), e1):
  1811. return - interp_Lint(e1, env)
  1812. ...
  1813. \end{lstlisting}
  1814. \end{minipage}
  1815. \begin{minipage}{0.45\textwidth}
  1816. \begin{lstlisting}
  1817. def interp_Lvar(e, env):
  1818. match e:
  1819. case Name(id):
  1820. return env[id]
  1821. case _:
  1822. return interp_Lint(e, env)
  1823. \end{lstlisting}
  1824. \end{minipage}
  1825. \fi}
  1826. \end{center}
  1827. The problem with this naive approach is that it does not handle
  1828. situations in which an \LangVar{} feature, such as a variable, is
  1829. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1830. in the following program.
  1831. {\if\edition\racketEd
  1832. \begin{lstlisting}
  1833. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1834. \end{lstlisting}
  1835. \fi}
  1836. {\if\edition\pythonEd\pythonColor
  1837. \begin{minipage}{0.96\textwidth}
  1838. \begin{lstlisting}
  1839. y = 10
  1840. print(-y)
  1841. \end{lstlisting}
  1842. \end{minipage}
  1843. \fi}
  1844. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1845. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1846. then it recursively calls \code{interp\_Lint} again on its argument.
  1847. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1848. an error!
  1849. To make our interpreters extensible we need something called
  1850. \emph{open recursion}\index{subject}{open recursion}, in which the
  1851. tying of the recursive knot is delayed until the functions are
  1852. composed. Object-oriented languages provide open recursion via method
  1853. overriding. The following code uses
  1854. method overriding to interpret \LangInt{} and \LangVar{} using
  1855. %
  1856. \racket{the
  1857. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1858. \index{subject}{class} feature of Racket.}
  1859. %
  1860. \python{a Python \code{class} definition.}
  1861. %
  1862. We define one class for each language and define a method for
  1863. interpreting expressions inside each class. The class for \LangVar{}
  1864. inherits from the class for \LangInt{}, and the method
  1865. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1866. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1867. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1868. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1869. \code{interp\_exp} in \LangInt{}.
  1870. \begin{center}
  1871. \hspace{-20pt}
  1872. {\if\edition\racketEd
  1873. \begin{minipage}{0.45\textwidth}
  1874. \begin{lstlisting}
  1875. (define interp-Lint-class
  1876. (class object%
  1877. (define/public ((interp_exp env) e)
  1878. (match e
  1879. [(Prim '- (list e))
  1880. (fx- 0 ((interp_exp env) e))]
  1881. ...))
  1882. ...))
  1883. \end{lstlisting}
  1884. \end{minipage}
  1885. \begin{minipage}{0.45\textwidth}
  1886. \begin{lstlisting}
  1887. (define interp-Lvar-class
  1888. (class interp-Lint-class
  1889. (define/override ((interp_exp env) e)
  1890. (match e
  1891. [(Var x)
  1892. (dict-ref env x)]
  1893. [(Let x e body)
  1894. (define v ((interp_exp env) e))
  1895. (define env^ (dict-set env x v))
  1896. ((interp_exp env^) body)]
  1897. [else
  1898. (super (interp_exp env) e)]))
  1899. ...
  1900. ))
  1901. \end{lstlisting}
  1902. \end{minipage}
  1903. \fi}
  1904. {\if\edition\pythonEd\pythonColor
  1905. \begin{minipage}{0.45\textwidth}
  1906. \begin{lstlisting}
  1907. class InterpLint:
  1908. def interp_exp(e):
  1909. match e:
  1910. case UnaryOp(USub(), e1):
  1911. return -self.interp_exp(e1)
  1912. ...
  1913. ...
  1914. \end{lstlisting}
  1915. \end{minipage}
  1916. \begin{minipage}{0.45\textwidth}
  1917. \begin{lstlisting}
  1918. def InterpLvar(InterpLint):
  1919. def interp_exp(e):
  1920. match e:
  1921. case Name(id):
  1922. return env[id]
  1923. case _:
  1924. return super().interp_exp(e)
  1925. ...
  1926. \end{lstlisting}
  1927. \end{minipage}
  1928. \fi}
  1929. \end{center}
  1930. Getting back to the troublesome example, repeated here:
  1931. {\if\edition\racketEd
  1932. \begin{lstlisting}
  1933. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1934. \end{lstlisting}
  1935. \fi}
  1936. {\if\edition\pythonEd\pythonColor
  1937. \begin{lstlisting}
  1938. y = 10
  1939. print(-y)
  1940. \end{lstlisting}
  1941. \fi}
  1942. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1943. \racket{on this expression,}
  1944. \python{on the \code{-y} expression,}%
  1945. %
  1946. which we call \code{e0}, by creating an object of the \LangVar{} class
  1947. and calling the \code{interp\_exp} method
  1948. {\if\edition\racketEd
  1949. \begin{lstlisting}
  1950. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1951. \end{lstlisting}
  1952. \fi}
  1953. {\if\edition\pythonEd\pythonColor
  1954. \begin{lstlisting}
  1955. InterpLvar().interp_exp(e0)
  1956. \end{lstlisting}
  1957. \fi}
  1958. \noindent To process the \code{-} operator, the default case of
  1959. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1960. method in \LangInt{}. But then for the recursive method call, it
  1961. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1962. \code{Var} node is handled correctly. Thus, method overriding gives us
  1963. the open recursion that we need to implement our interpreters in an
  1964. extensible way.
  1965. \subsection{Definitional Interpreter for \LangVar{}}
  1966. \label{sec:interp-Lvar}
  1967. Having justified the use of classes and methods to implement
  1968. interpreters, we revisit the definitional interpreter for \LangInt{}
  1969. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1970. create an interpreter for \LangVar{}, shown in
  1971. figure~\ref{fig:interp-Lvar}.
  1972. %
  1973. \python{We change the \code{interp\_stmt} method in the interpreter
  1974. for \LangInt{} in anticipation of adding \code{Goto} in
  1975. Chapter~\ref{ch:Lif}. The \code{interp\_stmt} method takes an extra
  1976. parameter named \code{cont} for \emph{continuation}, which is the
  1977. technical name for what comes after a particular point in a
  1978. program. The \code{cont} parameter is the list of statements that
  1979. need to be interpreted after the current statement.}
  1980. %
  1981. The interpreter for \LangVar{} adds two new cases for
  1982. variables and \racket{\key{let}}\python{assignment}. For
  1983. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1984. value bound to a variable to all the uses of the variable. To
  1985. accomplish this, we maintain a mapping from variables to values called
  1986. an \emph{environment}\index{subject}{environment}.
  1987. %
  1988. We use
  1989. %
  1990. \racket{an association list (alist) }%
  1991. %
  1992. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1993. %
  1994. to represent the environment.
  1995. %
  1996. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1997. and the \code{racket/dict} package.}
  1998. %
  1999. The \code{interp\_exp} function takes the current environment,
  2000. \code{env}, as an extra parameter. When the interpreter encounters a
  2001. variable, it looks up the corresponding value in the dictionary. If
  2002. the variable is not in the dictionary (because the variable was not
  2003. defined) then the dictionary lookup will fail and the interpreter will
  2004. halt with an error. Recall that the compiler is not obligated to
  2005. compile such programs (Section~\ref{sec:interp_Lint}).
  2006. %
  2007. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2008. initializing expression, extends the environment with the result
  2009. value bound to the variable, using \code{dict-set}, then evaluates
  2010. the body of the \key{Let}.}
  2011. %
  2012. \python{When the interpreter encounters an assignment, it evaluates
  2013. the initializing expression and then associates the resulting value
  2014. with the variable in the environment.}
  2015. \begin{figure}[tp]
  2016. \begin{tcolorbox}[colback=white]
  2017. {\if\edition\racketEd
  2018. \begin{lstlisting}
  2019. (define interp-Lint-class
  2020. (class object%
  2021. (super-new)
  2022. (define/public ((interp_exp env) e)
  2023. (match e
  2024. [(Int n) n]
  2025. [(Prim 'read '())
  2026. (define r (read))
  2027. (cond [(fixnum? r) r]
  2028. [else (error 'interp_exp "expected an integer" r)])]
  2029. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2030. [(Prim '+ (list e1 e2))
  2031. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2032. [(Prim '- (list e1 e2))
  2033. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2034. (define/public (interp_program p)
  2035. (match p
  2036. [(Program '() e) ((interp_exp '()) e)]))
  2037. ))
  2038. \end{lstlisting}
  2039. \fi}
  2040. {\if\edition\pythonEd\pythonColor
  2041. \begin{lstlisting}
  2042. class InterpLint:
  2043. def interp_exp(self, e, env):
  2044. match e:
  2045. case BinOp(left, Add(), right):
  2046. return self.interp_exp(left, env) + self.interp_exp(right, env)
  2047. case BinOp(left, Sub(), right):
  2048. return self.interp_exp(left, env) - self.interp_exp(right, env)
  2049. case UnaryOp(USub(), v):
  2050. return - self.interp_exp(v, env)
  2051. case Constant(value):
  2052. return value
  2053. case Call(Name('input_int'), []):
  2054. return int(input())
  2055. def interp_stmt(self, s, env, cont):
  2056. match s:
  2057. case Expr(Call(Name('print'), [arg])):
  2058. val = self.interp_exp(arg, env)
  2059. print(val, end='')
  2060. return self.interp_stmts(cont, env)
  2061. case Expr(value):
  2062. self.interp_exp(value, env)
  2063. return self.interp_stmts(cont, env)
  2064. case _:
  2065. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2066. def interp_stmts(self, ss, env):
  2067. if len(ss) == 0:
  2068. return None
  2069. else:
  2070. return self.interp_stmt(ss[0], env, ss[1:])
  2071. def interp(self, p):
  2072. match p:
  2073. case Module(body):
  2074. self.interp_stmts(body, {})
  2075. def interp_Lint(p):
  2076. return InterpLint().interp(p)
  2077. \end{lstlisting}
  2078. \fi}
  2079. \end{tcolorbox}
  2080. \caption{Interpreter for \LangInt{} as a class.}
  2081. \label{fig:interp-Lint-class}
  2082. \end{figure}
  2083. \begin{figure}[tp]
  2084. \begin{tcolorbox}[colback=white]
  2085. {\if\edition\racketEd
  2086. \begin{lstlisting}
  2087. (define interp-Lvar-class
  2088. (class interp-Lint-class
  2089. (super-new)
  2090. (define/override ((interp_exp env) e)
  2091. (match e
  2092. [(Var x) (dict-ref env x)]
  2093. [(Let x e body)
  2094. (define new-env (dict-set env x ((interp_exp env) e)))
  2095. ((interp_exp new-env) body)]
  2096. [else ((super interp_exp env) e)]))
  2097. ))
  2098. (define (interp_Lvar p)
  2099. (send (new interp-Lvar-class) interp_program p))
  2100. \end{lstlisting}
  2101. \fi}
  2102. {\if\edition\pythonEd\pythonColor
  2103. \begin{lstlisting}
  2104. class InterpLvar(InterpLint):
  2105. def interp_exp(self, e, env):
  2106. match e:
  2107. case Name(id):
  2108. return env[id]
  2109. case _:
  2110. return super().interp_exp(e, env)
  2111. def interp_stmt(self, s, env, cont):
  2112. match s:
  2113. case Assign([lhs], value):
  2114. env[lhs.id] = self.interp_exp(value, env)
  2115. return self.interp_stmts(cont, env)
  2116. case _:
  2117. return super().interp_stmt(s, env, cont)
  2118. def interp_Lvar(p):
  2119. return InterpLvar().interp(p)
  2120. \end{lstlisting}
  2121. \fi}
  2122. \end{tcolorbox}
  2123. \caption{Interpreter for the \LangVar{} language.}
  2124. \label{fig:interp-Lvar}
  2125. \end{figure}
  2126. {\if\edition\racketEd
  2127. \begin{figure}[tp]
  2128. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2129. \small
  2130. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2131. An \emph{association list} (called an alist) is a list of key-value pairs.
  2132. For example, we can map people to their ages with an alist
  2133. \index{subject}{alist}\index{subject}{association list}
  2134. \begin{lstlisting}[basicstyle=\ttfamily]
  2135. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2136. \end{lstlisting}
  2137. The \emph{dictionary} interface is for mapping keys to values.
  2138. Every alist implements this interface. \index{subject}{dictionary}
  2139. The package
  2140. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2141. provides many functions for working with dictionaries, such as
  2142. \begin{description}
  2143. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2144. returns the value associated with the given $\itm{key}$.
  2145. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2146. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2147. and otherwise is the same as $\itm{dict}$.
  2148. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2149. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2150. of keys and values in $\itm{dict}$. For example, the following
  2151. creates a new alist in which the ages are incremented:
  2152. \end{description}
  2153. \vspace{-10pt}
  2154. \begin{lstlisting}[basicstyle=\ttfamily]
  2155. (for/list ([(k v) (in-dict ages)])
  2156. (cons k (add1 v)))
  2157. \end{lstlisting}
  2158. \end{tcolorbox}
  2159. %\end{wrapfigure}
  2160. \caption{Association lists implement the dictionary interface.}
  2161. \label{fig:alist}
  2162. \end{figure}
  2163. \fi}
  2164. The goal for this chapter is to implement a compiler that translates
  2165. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2166. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2167. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2168. That is, they output the same integer $n$. We depict this correctness
  2169. criteria in the following diagram:
  2170. \[
  2171. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2172. \node (p1) at (0, 0) {$P_1$};
  2173. \node (p2) at (4, 0) {$P_2$};
  2174. \node (o) at (4, -2) {$n$};
  2175. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2176. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2177. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2178. \end{tikzpicture}
  2179. \]
  2180. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2181. compiling \LangVar{}.
  2182. \section{The \LangXInt{} Assembly Language}
  2183. \label{sec:x86}
  2184. \index{subject}{x86}
  2185. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2186. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2187. assembler.
  2188. %
  2189. A program begins with a \code{main} label followed by a sequence of
  2190. instructions. The \key{globl} directive makes the \key{main} procedure
  2191. externally visible so that the operating system can call it.
  2192. %
  2193. An x86 program is stored in the computer's memory. For our purposes,
  2194. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2195. values. The computer has a \emph{program counter}
  2196. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2197. \code{rip} register that points to the address of the next instruction
  2198. to be executed. For most instructions, the program counter is
  2199. incremented after the instruction is executed so that it points to the
  2200. next instruction in memory. Most x86 instructions take two operands,
  2201. each of which is an integer constant (called an \emph{immediate
  2202. value}\index{subject}{immediate value}), a
  2203. \emph{register}\index{subject}{register}, or a memory location.
  2204. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2205. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2206. && \key{r8} \MID \key{r9} \MID \key{r10}
  2207. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2208. \MID \key{r14} \MID \key{r15}}
  2209. \newcommand{\GrammarXInt}{
  2210. \begin{array}{rcl}
  2211. \Reg &::=& \allregisters{} \\
  2212. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2213. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2214. \key{subq} \; \Arg\key{,} \Arg \MID
  2215. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2216. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2217. \key{callq} \; \mathit{label} \MID
  2218. \key{retq} \MID
  2219. \key{jmp}\,\itm{label} \MID \\
  2220. && \itm{label}\key{:}\; \Instr
  2221. \end{array}
  2222. }
  2223. \begin{figure}[tp]
  2224. \begin{tcolorbox}[colback=white]
  2225. {\if\edition\racketEd
  2226. \[
  2227. \begin{array}{l}
  2228. \GrammarXInt \\
  2229. \begin{array}{lcl}
  2230. \LangXIntM{} &::= & \key{.globl main}\\
  2231. & & \key{main:} \; \Instr\ldots
  2232. \end{array}
  2233. \end{array}
  2234. \]
  2235. \fi}
  2236. {\if\edition\pythonEd\pythonColor
  2237. \[
  2238. \begin{array}{lcl}
  2239. \Reg &::=& \allregisters{} \\
  2240. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2241. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2242. \key{subq} \; \Arg\key{,} \Arg \MID
  2243. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2244. && \key{callq} \; \mathit{label} \MID
  2245. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2246. \LangXIntM{} &::= & \key{.globl main}\\
  2247. & & \key{main:} \; \Instr^{*}
  2248. \end{array}
  2249. \]
  2250. \fi}
  2251. \end{tcolorbox}
  2252. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2253. \label{fig:x86-int-concrete}
  2254. \end{figure}
  2255. A register is a special kind of variable that holds a 64-bit
  2256. value. There are 16 general-purpose registers in the computer; their
  2257. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2258. written with a percent sign, \key{\%}, followed by the register name,
  2259. for example \key{\%rax}.
  2260. An immediate value is written using the notation \key{\$}$n$ where $n$
  2261. is an integer.
  2262. %
  2263. %
  2264. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2265. which obtains the address stored in register $r$ and then adds $n$
  2266. bytes to the address. The resulting address is used to load or to store
  2267. to memory depending on whether it occurs as a source or destination
  2268. argument of an instruction.
  2269. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2270. the source $s$ and destination $d$, applies the arithmetic operation,
  2271. and then writes the result to the destination $d$. \index{subject}{instruction}
  2272. %
  2273. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2274. stores the result in $d$.
  2275. %
  2276. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2277. specified by the label, and $\key{retq}$ returns from a procedure to
  2278. its caller.
  2279. %
  2280. We discuss procedure calls in more detail further in this chapter and
  2281. in chapter~\ref{ch:Lfun}.
  2282. %
  2283. The last letter \key{q} indicates that these instructions operate on
  2284. quadwords, which are 64-bit values.
  2285. %
  2286. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2287. counter to the address of the instruction immediately after the
  2288. specified label.}
  2289. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2290. all the x86 instructions used in this book.
  2291. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2292. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2293. \lstinline{movq $10, %rax}
  2294. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2295. adds $32$ to the $10$ in \key{rax} and
  2296. puts the result, $42$, into \key{rax}.
  2297. %
  2298. The last instruction \key{retq} finishes the \key{main} function by
  2299. returning the integer in \key{rax} to the operating system. The
  2300. operating system interprets this integer as the program's exit
  2301. code. By convention, an exit code of 0 indicates that a program has
  2302. completed successfully, and all other exit codes indicate various
  2303. errors.
  2304. %
  2305. \racket{However, in this book we return the result of the program
  2306. as the exit code.}
  2307. \begin{figure}[tbp]
  2308. \begin{minipage}{0.45\textwidth}
  2309. \begin{tcolorbox}[colback=white]
  2310. \begin{lstlisting}
  2311. .globl main
  2312. main:
  2313. movq $10, %rax
  2314. addq $32, %rax
  2315. retq
  2316. \end{lstlisting}
  2317. \end{tcolorbox}
  2318. \end{minipage}
  2319. \caption{An x86 program that computes
  2320. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2321. \label{fig:p0-x86}
  2322. \end{figure}
  2323. We exhibit the use of memory for storing intermediate results in the
  2324. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2325. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2326. uses a region of memory called the \emph{procedure call stack}
  2327. (\emph{stack} for
  2328. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2329. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2330. for each procedure call. The memory layout for an individual frame is
  2331. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2332. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2333. address of the item at the top of the stack. In general, we use the
  2334. term \emph{pointer}\index{subject}{pointer} for something that
  2335. contains an address. The stack grows downward in memory, so we
  2336. increase the size of the stack by subtracting from the stack pointer.
  2337. In the context of a procedure call, the \emph{return
  2338. address}\index{subject}{return address} is the location of the
  2339. instruction that immediately follows the call instruction on the
  2340. caller side. The function call instruction, \code{callq}, pushes the
  2341. return address onto the stack prior to jumping to the procedure. The
  2342. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2343. pointer} and is used to access variables that are stored in the
  2344. frame of the current procedure call. The base pointer of the caller
  2345. is stored immediately after the return address.
  2346. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2347. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2348. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2349. $-16\key{(\%rbp)}$, and so on.
  2350. \begin{figure}[tbp]
  2351. \begin{minipage}{0.66\textwidth}
  2352. \begin{tcolorbox}[colback=white]
  2353. {\if\edition\racketEd
  2354. \begin{lstlisting}
  2355. start:
  2356. movq $10, -8(%rbp)
  2357. negq -8(%rbp)
  2358. movq -8(%rbp), %rax
  2359. addq $52, %rax
  2360. jmp conclusion
  2361. .globl main
  2362. main:
  2363. pushq %rbp
  2364. movq %rsp, %rbp
  2365. subq $16, %rsp
  2366. jmp start
  2367. conclusion:
  2368. addq $16, %rsp
  2369. popq %rbp
  2370. retq
  2371. \end{lstlisting}
  2372. \fi}
  2373. {\if\edition\pythonEd\pythonColor
  2374. \begin{lstlisting}
  2375. .globl main
  2376. main:
  2377. pushq %rbp
  2378. movq %rsp, %rbp
  2379. subq $16, %rsp
  2380. movq $10, -8(%rbp)
  2381. negq -8(%rbp)
  2382. movq -8(%rbp), %rax
  2383. addq $52, %rax
  2384. addq $16, %rsp
  2385. popq %rbp
  2386. retq
  2387. \end{lstlisting}
  2388. \fi}
  2389. \end{tcolorbox}
  2390. \end{minipage}
  2391. \caption{An x86 program that computes
  2392. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2393. \label{fig:p1-x86}
  2394. \end{figure}
  2395. \begin{figure}[tbp]
  2396. \begin{minipage}{0.66\textwidth}
  2397. \begin{tcolorbox}[colback=white]
  2398. \centering
  2399. \begin{tabular}{|r|l|} \hline
  2400. Position & Contents \\ \hline
  2401. $8$(\key{\%rbp}) & return address \\
  2402. $0$(\key{\%rbp}) & old \key{rbp} \\
  2403. $-8$(\key{\%rbp}) & variable $1$ \\
  2404. $-16$(\key{\%rbp}) & variable $2$ \\
  2405. \ldots & \ldots \\
  2406. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2407. \end{tabular}
  2408. \end{tcolorbox}
  2409. \end{minipage}
  2410. \caption{Memory layout of a frame.}
  2411. \label{fig:frame}
  2412. \end{figure}
  2413. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2414. is transferred from the operating system to the \code{main} function.
  2415. The operating system issues a \code{callq main} instruction that
  2416. pushes its return address on the stack and then jumps to
  2417. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2418. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2419. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2420. out of alignment (because the \code{callq} pushed the return address).
  2421. The first three instructions are the typical
  2422. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2423. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2424. pointer \code{rsp} and then saves the base pointer of the caller at
  2425. address \code{rsp} on the stack. The next instruction \code{movq
  2426. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2427. which is pointing to the location of the old base pointer. The
  2428. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2429. make enough room for storing variables. This program needs one
  2430. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2431. 16-byte-aligned, and then we are ready to make calls to other functions.
  2432. \racket{The last instruction of the prelude is \code{jmp start}, which
  2433. transfers control to the instructions that were generated from the
  2434. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2435. \racket{The first instruction under the \code{start} label is}
  2436. %
  2437. \python{The first instruction after the prelude is}
  2438. %
  2439. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2440. %
  2441. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2442. $1$ to $-10$.
  2443. %
  2444. The next instruction moves the $-10$ from variable $1$ into the
  2445. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2446. the value in \code{rax}, updating its contents to $42$.
  2447. \racket{The three instructions under the label \code{conclusion} are the
  2448. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2449. %
  2450. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2451. \code{main} function consists of the last three instructions.}
  2452. %
  2453. The first two restore the \code{rsp} and \code{rbp} registers to their
  2454. states at the beginning of the procedure. In particular,
  2455. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2456. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2457. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2458. \key{retq}, jumps back to the procedure that called this one and adds
  2459. $8$ to the stack pointer.
  2460. Our compiler needs a convenient representation for manipulating x86
  2461. programs, so we define an abstract syntax for x86, shown in
  2462. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2463. \LangXInt{}.
  2464. %
  2465. {\if\edition\pythonEd\pythonColor%
  2466. The main difference between this and the concrete syntax of \LangXInt{}
  2467. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2468. names, and register names are explicitly represented by strings.
  2469. \fi} %
  2470. {\if\edition\racketEd
  2471. The main difference between this and the concrete syntax of \LangXInt{}
  2472. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2473. front of every instruction. Instead instructions are grouped into
  2474. \emph{basic blocks}\index{subject}{basic block} with a
  2475. label associated with every basic block; this is why the \key{X86Program}
  2476. struct includes an alist mapping labels to basic blocks. The reason for this
  2477. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2478. introduce conditional branching. The \code{Block} structure includes
  2479. an $\itm{info}$ field that is not needed in this chapter but becomes
  2480. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2481. $\itm{info}$ field should contain an empty list.
  2482. \fi}
  2483. %
  2484. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2485. node includes an integer for representing the arity of the function,
  2486. that is, the number of arguments, which is helpful to know during
  2487. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2488. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2489. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2490. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2491. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2492. \MID \skey{r14} \MID \skey{r15}}
  2493. \newcommand{\ASTXIntRacket}{
  2494. \begin{array}{lcl}
  2495. \Reg &::=& \allregisters{} \\
  2496. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2497. \MID \DEREF{\Reg}{\Int} \\
  2498. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2499. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2500. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2501. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2502. &\MID& \PUSHQ{\Arg}
  2503. \MID \POPQ{\Arg} \\
  2504. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2505. \MID \RETQ{}
  2506. \MID \JMP{\itm{label}} \\
  2507. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2508. \end{array}
  2509. }
  2510. \begin{figure}[tp]
  2511. \begin{tcolorbox}[colback=white]
  2512. \small
  2513. {\if\edition\racketEd
  2514. \[\arraycolsep=3pt
  2515. \begin{array}{l}
  2516. \ASTXIntRacket \\
  2517. \begin{array}{lcl}
  2518. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2519. \end{array}
  2520. \end{array}
  2521. \]
  2522. \fi}
  2523. {\if\edition\pythonEd\pythonColor
  2524. \[
  2525. \begin{array}{lcl}
  2526. \Reg &::=& \allastregisters{} \\
  2527. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2528. \MID \DEREF{\Reg}{\Int} \\
  2529. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2530. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2531. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2532. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2533. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2534. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2535. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2536. \end{array}
  2537. \]
  2538. \fi}
  2539. \end{tcolorbox}
  2540. \caption{The abstract syntax of \LangXInt{} assembly.}
  2541. \label{fig:x86-int-ast}
  2542. \end{figure}
  2543. \section{Planning the Trip to x86}
  2544. \label{sec:plan-s0-x86}
  2545. To compile one language to another, it helps to focus on the
  2546. differences between the two languages because the compiler will need
  2547. to bridge those differences. What are the differences between \LangVar{}
  2548. and x86 assembly? Here are some of the most important ones:
  2549. \begin{enumerate}
  2550. \item x86 arithmetic instructions typically have two arguments and
  2551. update the second argument in place. In contrast, \LangVar{}
  2552. arithmetic operations take two arguments and produce a new value.
  2553. An x86 instruction may have at most one memory-accessing argument.
  2554. Furthermore, some x86 instructions place special restrictions on
  2555. their arguments.
  2556. \item An argument of an \LangVar{} operator can be a deeply nested
  2557. expression, whereas x86 instructions restrict their arguments to be
  2558. integer constants, registers, and memory locations.
  2559. {\if\edition\racketEd
  2560. \item The order of execution in x86 is explicit in the syntax, which
  2561. is a sequence of instructions and jumps to labeled positions,
  2562. whereas in \LangVar{} the order of evaluation is a left-to-right
  2563. depth-first traversal of the abstract syntax tree. \fi}
  2564. \item A program in \LangVar{} can have any number of variables,
  2565. whereas x86 has 16 registers and the procedure call stack.
  2566. {\if\edition\racketEd
  2567. \item Variables in \LangVar{} can shadow other variables with the
  2568. same name. In x86, registers have unique names, and memory locations
  2569. have unique addresses.
  2570. \fi}
  2571. \end{enumerate}
  2572. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2573. down the problem into several steps, which deal with these differences
  2574. one at a time. Each of these steps is called a \emph{pass} of the
  2575. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2576. %
  2577. This term indicates that each step passes over, or traverses, the AST
  2578. of the program.
  2579. %
  2580. Furthermore, we follow the nanopass approach, which means that we
  2581. strive for each pass to accomplish one clear objective rather than two
  2582. or three at the same time.
  2583. %
  2584. We begin by sketching how we might implement each pass and give each
  2585. pass a name. We then figure out an ordering of the passes and the
  2586. input/output language for each pass. The very first pass has
  2587. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2588. its output language. In between these two passes, we can choose
  2589. whichever language is most convenient for expressing the output of
  2590. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2591. \emph{intermediate language} of our own design. Finally, to
  2592. implement each pass we write one recursive function per nonterminal in
  2593. the grammar of the input language of the pass.
  2594. \index{subject}{intermediate language}
  2595. Our compiler for \LangVar{} consists of the following passes:
  2596. %
  2597. \begin{description}
  2598. {\if\edition\racketEd
  2599. \item[\key{uniquify}] deals with the shadowing of variables by
  2600. renaming every variable to a unique name.
  2601. \fi}
  2602. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2603. of a primitive operation or function call is a variable or integer,
  2604. that is, an \emph{atomic} expression. We refer to nonatomic
  2605. expressions as \emph{complex}. This pass introduces temporary
  2606. variables to hold the results of complex
  2607. subexpressions.\index{subject}{atomic
  2608. expression}\index{subject}{complex expression}%
  2609. {\if\edition\racketEd
  2610. \item[\key{explicate\_control}] makes the execution order of the
  2611. program explicit. It converts the abstract syntax tree
  2612. representation into a graph in which each node is a labeled sequence
  2613. of statements and the edges are \code{goto} statements.
  2614. \fi}
  2615. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2616. handles the difference between
  2617. \LangVar{} operations and x86 instructions. This pass converts each
  2618. \LangVar{} operation to a short sequence of instructions that
  2619. accomplishes the same task.
  2620. \item[\key{assign\_homes}] replaces variables with registers or stack
  2621. locations.
  2622. \end{description}
  2623. %
  2624. {\if\edition\racketEd
  2625. %
  2626. Our treatment of \code{remove\_complex\_operands} and
  2627. \code{explicate\_control} as separate passes is an example of the
  2628. nanopass approach.\footnote{For analogous decompositions of the
  2629. translation into continuation passing style, see the work of
  2630. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2631. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2632. %
  2633. \fi}
  2634. The next question is, in what order should we apply these passes? This
  2635. question can be challenging because it is difficult to know ahead of
  2636. time which orderings will be better (that is, will be easier to
  2637. implement, produce more efficient code, and so on), and therefore
  2638. ordering often involves trial and error. Nevertheless, we can plan
  2639. ahead and make educated choices regarding the ordering.
  2640. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2641. \key{uniquify}? The \key{uniquify} pass should come first because
  2642. \key{explicate\_control} changes all the \key{let}-bound variables to
  2643. become local variables whose scope is the entire program, which would
  2644. confuse variables with the same name.}
  2645. %
  2646. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2647. because the later removes the \key{let} form, but it is convenient to
  2648. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2649. %
  2650. \racket{The ordering of \key{uniquify} with respect to
  2651. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2652. \key{uniquify} to come first.}
  2653. The \key{select\_instructions} and \key{assign\_homes} passes are
  2654. intertwined.
  2655. %
  2656. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2657. passing arguments to functions and that it is preferable to assign
  2658. parameters to their corresponding registers. This suggests that it
  2659. would be better to start with the \key{select\_instructions} pass,
  2660. which generates the instructions for argument passing, before
  2661. performing register allocation.
  2662. %
  2663. On the other hand, by selecting instructions first we may run into a
  2664. dead end in \key{assign\_homes}. Recall that only one argument of an
  2665. x86 instruction may be a memory access, but \key{assign\_homes} might
  2666. be forced to assign both arguments to memory locations.
  2667. %
  2668. A sophisticated approach is to repeat the two passes until a solution
  2669. is found. However, to reduce implementation complexity we recommend
  2670. placing \key{select\_instructions} first, followed by the
  2671. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2672. that uses a reserved register to fix outstanding problems.
  2673. \begin{figure}[tbp]
  2674. \begin{tcolorbox}[colback=white]
  2675. {\if\edition\racketEd
  2676. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2677. \node (Lvar) at (0,2) {\large \LangVar{}};
  2678. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2679. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2680. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2681. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2682. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2683. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2684. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2685. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2686. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2687. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2688. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2689. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2690. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2691. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2692. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2693. \end{tikzpicture}
  2694. \fi}
  2695. {\if\edition\pythonEd\pythonColor
  2696. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2697. \node (Lvar) at (0,2) {\large \LangVar{}};
  2698. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2699. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2700. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2701. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2702. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2703. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2704. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2705. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2706. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2707. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2708. \end{tikzpicture}
  2709. \fi}
  2710. \end{tcolorbox}
  2711. \caption{Diagram of the passes for compiling \LangVar{}. }
  2712. \label{fig:Lvar-passes}
  2713. \end{figure}
  2714. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2715. passes and identifies the input and output language of each pass.
  2716. %
  2717. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2718. language, which extends \LangXInt{} with an unbounded number of
  2719. program-scope variables and removes the restrictions regarding
  2720. instruction arguments.
  2721. %
  2722. The last pass, \key{prelude\_and\_conclusion}, places the program
  2723. instructions inside a \code{main} function with instructions for the
  2724. prelude and conclusion.
  2725. %
  2726. \racket{In the next section we discuss the \LangCVar{} intermediate
  2727. language that serves as the output of \code{explicate\_control}.}
  2728. %
  2729. The remainder of this chapter provides guidance on the implementation
  2730. of each of the compiler passes represented in
  2731. figure~\ref{fig:Lvar-passes}.
  2732. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2733. %% are programs that are still in the \LangVar{} language, though the
  2734. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2735. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2736. %% %
  2737. %% The output of \code{explicate\_control} is in an intermediate language
  2738. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2739. %% syntax, which we introduce in the next section. The
  2740. %% \key{select-instruction} pass translates from \LangCVar{} to
  2741. %% \LangXVar{}. The \key{assign-homes} and
  2742. %% \key{patch-instructions}
  2743. %% passes input and output variants of x86 assembly.
  2744. \newcommand{\CvarGrammarRacket}{
  2745. \begin{array}{lcl}
  2746. \Atm &::=& \Int \MID \Var \\
  2747. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2748. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2749. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2750. \end{array}
  2751. }
  2752. \newcommand{\CvarASTRacket}{
  2753. \begin{array}{lcl}
  2754. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2755. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2756. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2757. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2758. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2759. \end{array}
  2760. }
  2761. {\if\edition\racketEd
  2762. \subsection{The \LangCVar{} Intermediate Language}
  2763. The output of \code{explicate\_control} is similar to the C
  2764. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2765. categories for expressions and statements, so we name it \LangCVar{}.
  2766. This style of intermediate language is also known as
  2767. \emph{three-address code}, to emphasize that the typical form of a
  2768. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2769. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2770. The concrete syntax for \LangCVar{} is shown in
  2771. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2772. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2773. %
  2774. The \LangCVar{} language supports the same operators as \LangVar{} but
  2775. the arguments of operators are restricted to atomic
  2776. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2777. assignment statements that can be executed in sequence using the
  2778. \key{Seq} form. A sequence of statements always ends with
  2779. \key{Return}, a guarantee that is baked into the grammar rules for
  2780. \itm{tail}. The naming of this nonterminal comes from the term
  2781. \emph{tail position}\index{subject}{tail position}, which refers to an
  2782. expression that is the last one to execute within a function or
  2783. program.
  2784. A \LangCVar{} program consists of an alist mapping labels to
  2785. tails. This is more general than necessary for the present chapter, as
  2786. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2787. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2788. there is just one label, \key{start}, and the whole program is
  2789. its tail.
  2790. %
  2791. The $\itm{info}$ field of the \key{CProgram} form, after the
  2792. \code{explicate\_control} pass, contains an alist that associates the
  2793. symbol \key{locals} with a list of all the variables used in the
  2794. program. At the start of the program, these variables are
  2795. uninitialized; they become initialized on their first assignment.
  2796. \begin{figure}[tbp]
  2797. \begin{tcolorbox}[colback=white]
  2798. \[
  2799. \begin{array}{l}
  2800. \CvarGrammarRacket \\
  2801. \begin{array}{lcl}
  2802. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2803. \end{array}
  2804. \end{array}
  2805. \]
  2806. \end{tcolorbox}
  2807. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2808. \label{fig:c0-concrete-syntax}
  2809. \end{figure}
  2810. \begin{figure}[tbp]
  2811. \begin{tcolorbox}[colback=white]
  2812. \[
  2813. \begin{array}{l}
  2814. \CvarASTRacket \\
  2815. \begin{array}{lcl}
  2816. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2817. \end{array}
  2818. \end{array}
  2819. \]
  2820. \end{tcolorbox}
  2821. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2822. \label{fig:c0-syntax}
  2823. \end{figure}
  2824. The definitional interpreter for \LangCVar{} is in the support code,
  2825. in the file \code{interp-Cvar.rkt}.
  2826. \fi}
  2827. {\if\edition\racketEd
  2828. \section{Uniquify Variables}
  2829. \label{sec:uniquify-Lvar}
  2830. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2831. with a unique name. Both the input and output of the \code{uniquify}
  2832. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2833. should translate the program on the left into the program on the
  2834. right.
  2835. \begin{transformation}
  2836. \begin{lstlisting}
  2837. (let ([x 32])
  2838. (+ (let ([x 10]) x) x))
  2839. \end{lstlisting}
  2840. \compilesto
  2841. \begin{lstlisting}
  2842. (let ([x.1 32])
  2843. (+ (let ([x.2 10]) x.2) x.1))
  2844. \end{lstlisting}
  2845. \end{transformation}
  2846. The following is another example translation, this time of a program
  2847. with a \key{let} nested inside the initializing expression of another
  2848. \key{let}.
  2849. \begin{transformation}
  2850. \begin{lstlisting}
  2851. (let ([x (let ([x 4])
  2852. (+ x 1))])
  2853. (+ x 2))
  2854. \end{lstlisting}
  2855. \compilesto
  2856. \begin{lstlisting}
  2857. (let ([x.2 (let ([x.1 4])
  2858. (+ x.1 1))])
  2859. (+ x.2 2))
  2860. \end{lstlisting}
  2861. \end{transformation}
  2862. We recommend implementing \code{uniquify} by creating a structurally
  2863. recursive function named \code{uniquify\_exp} that does little other
  2864. than copy an expression. However, when encountering a \key{let}, it
  2865. should generate a unique name for the variable and associate the old
  2866. name with the new name in an alist.\footnote{The Racket function
  2867. \code{gensym} is handy for generating unique variable names.} The
  2868. \code{uniquify\_exp} function needs to access this alist when it gets
  2869. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2870. for the alist.
  2871. The skeleton of the \code{uniquify\_exp} function is shown in
  2872. figure~\ref{fig:uniquify-Lvar}.
  2873. %% The function is curried so that it is
  2874. %% convenient to partially apply it to an alist and then apply it to
  2875. %% different expressions, as in the last case for primitive operations in
  2876. %% figure~\ref{fig:uniquify-Lvar}.
  2877. The
  2878. %
  2879. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2880. %
  2881. form of Racket is useful for transforming the element of a list to
  2882. produce a new list.\index{subject}{for/list}
  2883. \begin{figure}[tbp]
  2884. \begin{tcolorbox}[colback=white]
  2885. \begin{lstlisting}
  2886. (define (uniquify_exp env)
  2887. (lambda (e)
  2888. (match e
  2889. [(Var x) ___]
  2890. [(Int n) (Int n)]
  2891. [(Let x e body) ___]
  2892. [(Prim op es)
  2893. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2894. (define (uniquify p)
  2895. (match p
  2896. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2897. \end{lstlisting}
  2898. \end{tcolorbox}
  2899. \caption{Skeleton for the \key{uniquify} pass.}
  2900. \label{fig:uniquify-Lvar}
  2901. \end{figure}
  2902. \begin{exercise}
  2903. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2904. Complete the \code{uniquify} pass by filling in the blanks in
  2905. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2906. variables and for the \key{let} form in the file \code{compiler.rkt}
  2907. in the support code.
  2908. \end{exercise}
  2909. \begin{exercise}
  2910. \normalfont\normalsize
  2911. \label{ex:Lvar}
  2912. Create five \LangVar{} programs that exercise the most interesting
  2913. parts of the \key{uniquify} pass; that is, the programs should include
  2914. \key{let} forms, variables, and variables that shadow each other.
  2915. The five programs should be placed in the subdirectory named
  2916. \key{tests}, and the file names should start with \code{var\_test\_}
  2917. followed by a unique integer and end with the file extension
  2918. \key{.rkt}.
  2919. %
  2920. The \key{run-tests.rkt} script in the support code checks whether the
  2921. output programs produce the same result as the input programs. The
  2922. script uses the \key{interp-tests} function
  2923. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2924. your \key{uniquify} pass on the example programs. The \code{passes}
  2925. parameter of \key{interp-tests} is a list that should have one entry
  2926. for each pass in your compiler. For now, define \code{passes} to
  2927. contain just one entry for \code{uniquify} as follows:
  2928. \begin{lstlisting}
  2929. (define passes
  2930. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2931. \end{lstlisting}
  2932. Run the \key{run-tests.rkt} script in the support code to check
  2933. whether the output programs produce the same result as the input
  2934. programs.
  2935. \end{exercise}
  2936. \fi}
  2937. \section{Remove Complex Operands}
  2938. \label{sec:remove-complex-opera-Lvar}
  2939. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2940. into a restricted form in which the arguments of operations are atomic
  2941. expressions. Put another way, this pass removes complex
  2942. operands\index{subject}{complex operand}, such as the expression
  2943. \racket{\code{(- 10)}}\python{\code{-10}}
  2944. in the following program. This is accomplished by introducing a new
  2945. temporary variable, assigning the complex operand to the new
  2946. variable, and then using the new variable in place of the complex
  2947. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2948. right.
  2949. {\if\edition\racketEd
  2950. \begin{transformation}
  2951. % var_test_19.rkt
  2952. \begin{lstlisting}
  2953. (let ([x (+ 42 (- 10))])
  2954. (+ x 10))
  2955. \end{lstlisting}
  2956. \compilesto
  2957. \begin{lstlisting}
  2958. (let ([x (let ([tmp.1 (- 10)])
  2959. (+ 42 tmp.1))])
  2960. (+ x 10))
  2961. \end{lstlisting}
  2962. \end{transformation}
  2963. \fi}
  2964. {\if\edition\pythonEd\pythonColor
  2965. \begin{transformation}
  2966. \begin{lstlisting}
  2967. x = 42 + -10
  2968. print(x + 10)
  2969. \end{lstlisting}
  2970. \compilesto
  2971. \begin{lstlisting}
  2972. tmp_0 = -10
  2973. x = 42 + tmp_0
  2974. tmp_1 = x + 10
  2975. print(tmp_1)
  2976. \end{lstlisting}
  2977. \end{transformation}
  2978. \fi}
  2979. \newcommand{\LvarMonadASTRacket}{
  2980. \begin{array}{rcl}
  2981. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2982. \Exp &::=& \Atm \MID \READ{} \\
  2983. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2984. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2985. \end{array}
  2986. }
  2987. \newcommand{\LvarMonadASTPython}{
  2988. \begin{array}{rcl}
  2989. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2990. \Exp{} &::=& \Atm \MID \READ{} \\
  2991. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2992. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2993. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2994. \end{array}
  2995. }
  2996. \begin{figure}[tp]
  2997. \centering
  2998. \begin{tcolorbox}[colback=white]
  2999. {\if\edition\racketEd
  3000. \[
  3001. \begin{array}{l}
  3002. \LvarMonadASTRacket \\
  3003. \begin{array}{rcl}
  3004. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3005. \end{array}
  3006. \end{array}
  3007. \]
  3008. \fi}
  3009. {\if\edition\pythonEd\pythonColor
  3010. \[
  3011. \begin{array}{l}
  3012. \LvarMonadASTPython \\
  3013. \begin{array}{rcl}
  3014. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3015. \end{array}
  3016. \end{array}
  3017. \]
  3018. \fi}
  3019. \end{tcolorbox}
  3020. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3021. atomic expressions.}
  3022. \label{fig:Lvar-anf-syntax}
  3023. \end{figure}
  3024. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3025. of this pass, the language \LangVarANF{}. The only difference is that
  3026. operator arguments are restricted to be atomic expressions that are
  3027. defined by the \Atm{} nonterminal. In particular, integer constants
  3028. and variables are atomic.
  3029. The atomic expressions are pure (they do not cause or depend on side
  3030. effects) whereas complex expressions may have side effects, such as
  3031. \READ{}. A language with this separation between pure expressions
  3032. versus expressions with side effects is said to be in monadic normal
  3033. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3034. in the name \LangVarANF{}. An important invariant of the
  3035. \code{remove\_complex\_operands} pass is that the relative ordering
  3036. among complex expressions is not changed, but the relative ordering
  3037. between atomic expressions and complex expressions can change and
  3038. often does. The reason that these changes are behavior preserving is
  3039. that the atomic expressions are pure.
  3040. Another well-known form for intermediate languages is the
  3041. \emph{administrative normal form}
  3042. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3043. \index{subject}{administrative normal form} \index{subject}{ANF}
  3044. %
  3045. The \LangVarANF{} language is not quite in ANF because it allows the
  3046. right-hand side of a \code{let} to be a complex expression, such as
  3047. another \code{let}. The flattening of nested \code{let} expressions is
  3048. instead one of the responsibilities of the \code{explicate\_control}
  3049. pass.
  3050. {\if\edition\racketEd
  3051. We recommend implementing this pass with two mutually recursive
  3052. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3053. \code{rco\_atom} to subexpressions that need to become atomic and to
  3054. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3055. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3056. returns an expression. The \code{rco\_atom} function returns two
  3057. things: an atomic expression and an alist mapping temporary variables to
  3058. complex subexpressions. You can return multiple things from a function
  3059. using Racket's \key{values} form, and you can receive multiple things
  3060. from a function call using the \key{define-values} form.
  3061. \fi}
  3062. %
  3063. {\if\edition\pythonEd\pythonColor
  3064. %
  3065. We recommend implementing this pass with an auxiliary method named
  3066. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3067. Boolean that specifies whether the expression needs to become atomic
  3068. or not. The \code{rco\_exp} method should return a pair consisting of
  3069. the new expression and a list of pairs, associating new temporary
  3070. variables with their initializing expressions.
  3071. %
  3072. \fi}
  3073. {\if\edition\racketEd
  3074. %
  3075. Returning to the example program with the expression \code{(+ 42 (-
  3076. 10))}, the subexpression \code{(- 10)} should be processed using the
  3077. \code{rco\_atom} function because it is an argument of the \code{+}
  3078. operator and therefore needs to become atomic. The output of
  3079. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3080. \begin{transformation}
  3081. \begin{lstlisting}
  3082. (- 10)
  3083. \end{lstlisting}
  3084. \compilesto
  3085. \begin{lstlisting}
  3086. tmp.1
  3087. ((tmp.1 . (- 10)))
  3088. \end{lstlisting}
  3089. \end{transformation}
  3090. \fi}
  3091. %
  3092. {\if\edition\pythonEd\pythonColor
  3093. %
  3094. Returning to the example program with the expression \code{42 + -10},
  3095. the subexpression \code{-10} should be processed using the
  3096. \code{rco\_exp} function with \code{True} as the second argument
  3097. because \code{-10} is an argument of the \code{+} operator and
  3098. therefore needs to become atomic. The output of \code{rco\_exp}
  3099. applied to \code{-10} is as follows.
  3100. \begin{transformation}
  3101. \begin{lstlisting}
  3102. -10
  3103. \end{lstlisting}
  3104. \compilesto
  3105. \begin{lstlisting}
  3106. tmp_1
  3107. [(tmp_1, -10)]
  3108. \end{lstlisting}
  3109. \end{transformation}
  3110. %
  3111. \fi}
  3112. Take special care of programs, such as the following, that
  3113. %
  3114. \racket{bind a variable to an atomic expression.}
  3115. %
  3116. \python{assign an atomic expression to a variable.}
  3117. %
  3118. You should leave such \racket{variable bindings}\python{assignments}
  3119. unchanged, as shown in the program on the right:\\
  3120. %
  3121. {\if\edition\racketEd
  3122. \begin{transformation}
  3123. % var_test_20.rkt
  3124. \begin{lstlisting}
  3125. (let ([a 42])
  3126. (let ([b a])
  3127. b))
  3128. \end{lstlisting}
  3129. \compilesto
  3130. \begin{lstlisting}
  3131. (let ([a 42])
  3132. (let ([b a])
  3133. b))
  3134. \end{lstlisting}
  3135. \end{transformation}
  3136. \fi}
  3137. {\if\edition\pythonEd\pythonColor
  3138. \begin{transformation}
  3139. \begin{lstlisting}
  3140. a = 42
  3141. b = a
  3142. print(b)
  3143. \end{lstlisting}
  3144. \compilesto
  3145. \begin{lstlisting}
  3146. a = 42
  3147. b = a
  3148. print(b)
  3149. \end{lstlisting}
  3150. \end{transformation}
  3151. \fi}
  3152. %
  3153. \noindent A careless implementation might produce the following output with
  3154. unnecessary temporary variables.
  3155. \begin{center}
  3156. \begin{minipage}{0.4\textwidth}
  3157. {\if\edition\racketEd
  3158. \begin{lstlisting}
  3159. (let ([tmp.1 42])
  3160. (let ([a tmp.1])
  3161. (let ([tmp.2 a])
  3162. (let ([b tmp.2])
  3163. b))))
  3164. \end{lstlisting}
  3165. \fi}
  3166. {\if\edition\pythonEd\pythonColor
  3167. \begin{lstlisting}
  3168. tmp_1 = 42
  3169. a = tmp_1
  3170. tmp_2 = a
  3171. b = tmp_2
  3172. print(b)
  3173. \end{lstlisting}
  3174. \fi}
  3175. \end{minipage}
  3176. \end{center}
  3177. \begin{exercise}
  3178. \normalfont\normalsize
  3179. {\if\edition\racketEd
  3180. Implement the \code{remove\_complex\_operands} function in
  3181. \code{compiler.rkt}.
  3182. %
  3183. Create three new \LangVar{} programs that exercise the interesting
  3184. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3185. regarding file names described in exercise~\ref{ex:Lvar}.
  3186. %
  3187. In the \code{run-tests.rkt} script, add the following entry to the
  3188. list of \code{passes}, and then run the script to test your compiler.
  3189. \begin{lstlisting}
  3190. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3191. \end{lstlisting}
  3192. In debugging your compiler, it is often useful to see the intermediate
  3193. programs that are output from each pass. To print the intermediate
  3194. programs, place \lstinline{(debug-level 1)} before the call to
  3195. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3196. %
  3197. {\if\edition\pythonEd\pythonColor
  3198. Implement the \code{remove\_complex\_operands} pass in
  3199. \code{compiler.py}, creating auxiliary functions for each
  3200. nonterminal in the grammar, i.e., \code{rco\_exp}
  3201. and \code{rco\_stmt}. We recommend you use the function
  3202. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3203. \fi}
  3204. \end{exercise}
  3205. {\if\edition\pythonEd\pythonColor
  3206. \begin{exercise}
  3207. \normalfont\normalsize
  3208. \label{ex:Lvar}
  3209. Create five \LangVar{} programs that exercise the most interesting
  3210. parts of the \code{remove\_complex\_operands} pass. The five programs
  3211. should be placed in the subdirectory named \key{tests}, and the file
  3212. names should start with \code{var\_test\_} followed by a unique
  3213. integer and end with the file extension \key{.py}.
  3214. %% The \key{run-tests.rkt} script in the support code checks whether the
  3215. %% output programs produce the same result as the input programs. The
  3216. %% script uses the \key{interp-tests} function
  3217. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3218. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3219. %% parameter of \key{interp-tests} is a list that should have one entry
  3220. %% for each pass in your compiler. For now, define \code{passes} to
  3221. %% contain just one entry for \code{uniquify} as shown below.
  3222. %% \begin{lstlisting}
  3223. %% (define passes
  3224. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3225. %% \end{lstlisting}
  3226. Run the \key{run-tests.py} script in the support code to check
  3227. whether the output programs produce the same result as the input
  3228. programs.
  3229. \end{exercise}
  3230. \fi}
  3231. {\if\edition\racketEd
  3232. \section{Explicate Control}
  3233. \label{sec:explicate-control-Lvar}
  3234. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3235. programs that make the order of execution explicit in their
  3236. syntax. For now this amounts to flattening \key{let} constructs into a
  3237. sequence of assignment statements. For example, consider the following
  3238. \LangVar{} program:\\
  3239. % var_test_11.rkt
  3240. \begin{minipage}{0.96\textwidth}
  3241. \begin{lstlisting}
  3242. (let ([y (let ([x 20])
  3243. (+ x (let ([x 22]) x)))])
  3244. y)
  3245. \end{lstlisting}
  3246. \end{minipage}\\
  3247. %
  3248. The output of the previous pass is shown next, on the left, and the
  3249. output of \code{explicate\_control} is on the right. Recall that the
  3250. right-hand side of a \key{let} executes before its body, so that the order
  3251. of evaluation for this program is to assign \code{20} to \code{x.1},
  3252. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3253. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3254. this ordering explicit.
  3255. \begin{transformation}
  3256. \begin{lstlisting}
  3257. (let ([y (let ([x.1 20])
  3258. (let ([x.2 22])
  3259. (+ x.1 x.2)))])
  3260. y)
  3261. \end{lstlisting}
  3262. \compilesto
  3263. \begin{lstlisting}[language=C]
  3264. start:
  3265. x.1 = 20;
  3266. x.2 = 22;
  3267. y = (+ x.1 x.2);
  3268. return y;
  3269. \end{lstlisting}
  3270. \end{transformation}
  3271. \begin{figure}[tbp]
  3272. \begin{tcolorbox}[colback=white]
  3273. \begin{lstlisting}
  3274. (define (explicate_tail e)
  3275. (match e
  3276. [(Var x) ___]
  3277. [(Int n) (Return (Int n))]
  3278. [(Let x rhs body) ___]
  3279. [(Prim op es) ___]
  3280. [else (error "explicate_tail unhandled case" e)]))
  3281. (define (explicate_assign e x cont)
  3282. (match e
  3283. [(Var x) ___]
  3284. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3285. [(Let y rhs body) ___]
  3286. [(Prim op es) ___]
  3287. [else (error "explicate_assign unhandled case" e)]))
  3288. (define (explicate_control p)
  3289. (match p
  3290. [(Program info body) ___]))
  3291. \end{lstlisting}
  3292. \end{tcolorbox}
  3293. \caption{Skeleton for the \code{explicate\_control} pass.}
  3294. \label{fig:explicate-control-Lvar}
  3295. \end{figure}
  3296. The organization of this pass depends on the notion of tail position
  3297. to which we have alluded. Here is the definition.
  3298. \begin{definition}\normalfont
  3299. The following rules define when an expression is in \emph{tail
  3300. position}\index{subject}{tail position} for the language \LangVar{}.
  3301. \begin{enumerate}
  3302. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3303. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3304. \end{enumerate}
  3305. \end{definition}
  3306. We recommend implementing \code{explicate\_control} using two
  3307. recursive functions, \code{explicate\_tail} and
  3308. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3309. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3310. function should be applied to expressions in tail position, whereas the
  3311. \code{explicate\_assign} should be applied to expressions that occur on
  3312. the right-hand side of a \key{let}.
  3313. %
  3314. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3315. input and produces a \Tail{} in \LangCVar{} (see
  3316. figure~\ref{fig:c0-syntax}).
  3317. %
  3318. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3319. the variable to which it is to be assigned, and a \Tail{} in
  3320. \LangCVar{} for the code that comes after the assignment. The
  3321. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3322. The \code{explicate\_assign} function is in accumulator-passing style:
  3323. the \code{cont} parameter is used for accumulating the output. This
  3324. accumulator-passing style plays an important role in the way that we
  3325. generate high-quality code for conditional expressions in
  3326. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3327. continuation because it contains the generated code that should come
  3328. after the current assignment. This code organization is also related
  3329. to continuation-passing style, except that \code{cont} is not what
  3330. happens next during compilation but is what happens next in the
  3331. generated code.
  3332. \begin{exercise}\normalfont\normalsize
  3333. %
  3334. Implement the \code{explicate\_control} function in
  3335. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3336. exercise the code in \code{explicate\_control}.
  3337. %
  3338. In the \code{run-tests.rkt} script, add the following entry to the
  3339. list of \code{passes} and then run the script to test your compiler.
  3340. \begin{lstlisting}
  3341. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3342. \end{lstlisting}
  3343. \end{exercise}
  3344. \fi}
  3345. \section{Select Instructions}
  3346. \label{sec:select-Lvar}
  3347. \index{subject}{select instructions}
  3348. In the \code{select\_instructions} pass we begin the work of
  3349. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3350. language of this pass is a variant of x86 that still uses variables,
  3351. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3352. nonterminal of the \LangXInt{} abstract syntax
  3353. (figure~\ref{fig:x86-int-ast}).
  3354. \racket{We recommend implementing the
  3355. \code{select\_instructions} with three auxiliary functions, one for
  3356. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3357. $\Tail$.}
  3358. \python{We recommend implementing an auxiliary function
  3359. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3360. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3361. same and integer constants change to immediates; that is, $\INT{n}$
  3362. changes to $\IMM{n}$.}
  3363. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3364. arithmetic operations. For example, consider the following addition
  3365. operation, on the left side. There is an \key{addq} instruction in
  3366. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3367. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3368. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3369. $\Atm_2$, respectively.
  3370. \begin{transformation}
  3371. {\if\edition\racketEd
  3372. \begin{lstlisting}
  3373. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3374. \end{lstlisting}
  3375. \fi}
  3376. {\if\edition\pythonEd\pythonColor
  3377. \begin{lstlisting}
  3378. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3379. \end{lstlisting}
  3380. \fi}
  3381. \compilesto
  3382. \begin{lstlisting}
  3383. movq |$\Arg_1$|, |$\itm{var}$|
  3384. addq |$\Arg_2$|, |$\itm{var}$|
  3385. \end{lstlisting}
  3386. \end{transformation}
  3387. There are also cases that require special care to avoid generating
  3388. needlessly complicated code. For example, if one of the arguments of
  3389. the addition is the same variable as the left-hand side of the
  3390. assignment, as shown next, then there is no need for the extra move
  3391. instruction. The assignment statement can be translated into a single
  3392. \key{addq} instruction, as follows.
  3393. \begin{transformation}
  3394. {\if\edition\racketEd
  3395. \begin{lstlisting}
  3396. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3397. \end{lstlisting}
  3398. \fi}
  3399. {\if\edition\pythonEd\pythonColor
  3400. \begin{lstlisting}
  3401. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3402. \end{lstlisting}
  3403. \fi}
  3404. \compilesto
  3405. \begin{lstlisting}
  3406. addq |$\Arg_1$|, |$\itm{var}$|
  3407. \end{lstlisting}
  3408. \end{transformation}
  3409. The \READOP{} operation does not have a direct counterpart in x86
  3410. assembly, so we provide this functionality with the function
  3411. \code{read\_int} in the file \code{runtime.c}, written in
  3412. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3413. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3414. system}, or simply the \emph{runtime} for short. When compiling your
  3415. generated x86 assembly code, you need to compile \code{runtime.c} to
  3416. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3417. \code{-c}) and link it into the executable. For our purposes of code
  3418. generation, all you need to do is translate an assignment of
  3419. \READOP{} into a call to the \code{read\_int} function followed by a
  3420. move from \code{rax} to the left-hand side variable. (Recall that the
  3421. return value of a function goes into \code{rax}.)
  3422. \begin{transformation}
  3423. {\if\edition\racketEd
  3424. \begin{lstlisting}
  3425. |$\itm{var}$| = (read);
  3426. \end{lstlisting}
  3427. \fi}
  3428. {\if\edition\pythonEd\pythonColor
  3429. \begin{lstlisting}
  3430. |$\itm{var}$| = input_int();
  3431. \end{lstlisting}
  3432. \fi}
  3433. \compilesto
  3434. \begin{lstlisting}
  3435. callq read_int
  3436. movq %rax, |$\itm{var}$|
  3437. \end{lstlisting}
  3438. \end{transformation}
  3439. {\if\edition\pythonEd\pythonColor
  3440. %
  3441. Similarly, we translate the \code{print} operation, shown below, into
  3442. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3443. In x86, the first six arguments to functions are passed in registers,
  3444. with the first argument passed in register \code{rdi}. So we move the
  3445. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3446. \code{callq} instruction.
  3447. \begin{transformation}
  3448. \begin{lstlisting}
  3449. print(|$\Atm$|)
  3450. \end{lstlisting}
  3451. \compilesto
  3452. \begin{lstlisting}
  3453. movq |$\Arg$|, %rdi
  3454. callq print_int
  3455. \end{lstlisting}
  3456. \end{transformation}
  3457. %
  3458. \fi}
  3459. {\if\edition\racketEd
  3460. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3461. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3462. assignment to the \key{rax} register followed by a jump to the
  3463. conclusion of the program (so the conclusion needs to be labeled).
  3464. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3465. recursively and then append the resulting instructions.
  3466. \fi}
  3467. {\if\edition\pythonEd\pythonColor
  3468. We recommend that you use the function \code{utils.label\_name()} to
  3469. transform strings into labels, for example, in
  3470. the target of the \code{callq} instruction. This practice makes your
  3471. compiler portable across Linus and Mac OS X, which requires an underscore
  3472. prefixed to all labels.
  3473. \fi}
  3474. \begin{exercise}
  3475. \normalfont\normalsize
  3476. {\if\edition\racketEd
  3477. Implement the \code{select\_instructions} pass in
  3478. \code{compiler.rkt}. Create three new example programs that are
  3479. designed to exercise all the interesting cases in this pass.
  3480. %
  3481. In the \code{run-tests.rkt} script, add the following entry to the
  3482. list of \code{passes} and then run the script to test your compiler.
  3483. \begin{lstlisting}
  3484. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3485. \end{lstlisting}
  3486. \fi}
  3487. {\if\edition\pythonEd\pythonColor
  3488. Implement the \key{select\_instructions} pass in
  3489. \code{compiler.py}. Create three new example programs that are
  3490. designed to exercise all the interesting cases in this pass.
  3491. Run the \code{run-tests.py} script to to check
  3492. whether the output programs produce the same result as the input
  3493. programs.
  3494. \fi}
  3495. \end{exercise}
  3496. \section{Assign Homes}
  3497. \label{sec:assign-Lvar}
  3498. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3499. \LangXVar{} programs that no longer use program variables. Thus, the
  3500. \code{assign\_homes} pass is responsible for placing all the program
  3501. variables in registers or on the stack. For runtime efficiency, it is
  3502. better to place variables in registers, but because there are only
  3503. sixteen registers, some programs must necessarily resort to placing
  3504. some variables on the stack. In this chapter we focus on the mechanics
  3505. of placing variables on the stack. We study an algorithm for placing
  3506. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3507. Consider again the following \LangVar{} program from
  3508. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3509. % var_test_20.rkt
  3510. \begin{minipage}{0.96\textwidth}
  3511. {\if\edition\racketEd
  3512. \begin{lstlisting}
  3513. (let ([a 42])
  3514. (let ([b a])
  3515. b))
  3516. \end{lstlisting}
  3517. \fi}
  3518. {\if\edition\pythonEd\pythonColor
  3519. \begin{lstlisting}
  3520. a = 42
  3521. b = a
  3522. print(b)
  3523. \end{lstlisting}
  3524. \fi}
  3525. \end{minipage}\\
  3526. %
  3527. The output of \code{select\_instructions} is shown next, on the left,
  3528. and the output of \code{assign\_homes} is on the right. In this
  3529. example, we assign variable \code{a} to stack location
  3530. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3531. \begin{transformation}
  3532. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3533. movq $42, a
  3534. movq a, b
  3535. movq b, %rax
  3536. \end{lstlisting}
  3537. \compilesto
  3538. %stack-space: 16
  3539. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3540. movq $42, -8(%rbp)
  3541. movq -8(%rbp), -16(%rbp)
  3542. movq -16(%rbp), %rax
  3543. \end{lstlisting}
  3544. \end{transformation}
  3545. \racket{
  3546. The \code{assign\_homes} pass should replace all variables
  3547. with stack locations.
  3548. The list of variables can be obtained from
  3549. the \code{locals-types} entry in the $\itm{info}$ of the
  3550. \code{X86Program} node. The \code{locals-types} entry is an alist
  3551. mapping all the variables in the program to their types
  3552. (for now, just \code{Integer}).
  3553. As an aside, the \code{locals-types} entry is
  3554. computed by \code{type-check-Cvar} in the support code, which
  3555. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3556. which you should propagate to the \code{X86Program} node.}
  3557. %
  3558. \python{The \code{assign\_homes} pass should replace all uses of
  3559. variables with stack locations.}
  3560. %
  3561. In the process of assigning variables to stack locations, it is
  3562. convenient for you to compute and store the size of the frame (in
  3563. bytes) in
  3564. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3565. %
  3566. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3567. %
  3568. which is needed later to generate the conclusion of the \code{main}
  3569. procedure. The x86-64 standard requires the frame size to be a
  3570. multiple of 16 bytes.\index{subject}{frame}
  3571. % TODO: store the number of variables instead? -Jeremy
  3572. \begin{exercise}\normalfont\normalsize
  3573. Implement the \code{assign\_homes} pass in
  3574. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3575. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3576. grammar. We recommend that the auxiliary functions take an extra
  3577. parameter that maps variable names to homes (stack locations for now).
  3578. %
  3579. {\if\edition\racketEd
  3580. In the \code{run-tests.rkt} script, add the following entry to the
  3581. list of \code{passes} and then run the script to test your compiler.
  3582. \begin{lstlisting}
  3583. (list "assign homes" assign-homes interp_x86-0)
  3584. \end{lstlisting}
  3585. \fi}
  3586. {\if\edition\pythonEd\pythonColor
  3587. Run the \code{run-tests.py} script to to check
  3588. whether the output programs produce the same result as the input
  3589. programs.
  3590. \fi}
  3591. \end{exercise}
  3592. \section{Patch Instructions}
  3593. \label{sec:patch-s0}
  3594. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3595. \LangXInt{} by making sure that each instruction adheres to the
  3596. restriction that at most one argument of an instruction may be a
  3597. memory reference.
  3598. We return to the following example.\\
  3599. \begin{minipage}{0.5\textwidth}
  3600. % var_test_20.rkt
  3601. {\if\edition\racketEd
  3602. \begin{lstlisting}
  3603. (let ([a 42])
  3604. (let ([b a])
  3605. b))
  3606. \end{lstlisting}
  3607. \fi}
  3608. {\if\edition\pythonEd\pythonColor
  3609. \begin{lstlisting}
  3610. a = 42
  3611. b = a
  3612. print(b)
  3613. \end{lstlisting}
  3614. \fi}
  3615. \end{minipage}\\
  3616. The \code{assign\_homes} pass produces the following translation. \\
  3617. \begin{minipage}{0.5\textwidth}
  3618. {\if\edition\racketEd
  3619. \begin{lstlisting}
  3620. movq $42, -8(%rbp)
  3621. movq -8(%rbp), -16(%rbp)
  3622. movq -16(%rbp), %rax
  3623. \end{lstlisting}
  3624. \fi}
  3625. {\if\edition\pythonEd\pythonColor
  3626. \begin{lstlisting}
  3627. movq 42, -8(%rbp)
  3628. movq -8(%rbp), -16(%rbp)
  3629. movq -16(%rbp), %rdi
  3630. callq print_int
  3631. \end{lstlisting}
  3632. \fi}
  3633. \end{minipage}\\
  3634. The second \key{movq} instruction is problematic because both
  3635. arguments are stack locations. We suggest fixing this problem by
  3636. moving from the source location to the register \key{rax} and then
  3637. from \key{rax} to the destination location, as follows.
  3638. \begin{lstlisting}
  3639. movq -8(%rbp), %rax
  3640. movq %rax, -16(%rbp)
  3641. \end{lstlisting}
  3642. There is a similar corner case that also needs to be dealt with. If
  3643. one argument is an immediate integer larger than $2^{16}$ and the
  3644. other is a memory reference, then the instruction is invalid. One can
  3645. fix this, for example, by first moving the immediate integer into
  3646. \key{rax} and then using \key{rax} in place of the integer.
  3647. \begin{exercise}
  3648. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3649. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3650. Create three new example programs that are
  3651. designed to exercise all the interesting cases in this pass.
  3652. %
  3653. {\if\edition\racketEd
  3654. In the \code{run-tests.rkt} script, add the following entry to the
  3655. list of \code{passes} and then run the script to test your compiler.
  3656. \begin{lstlisting}
  3657. (list "patch instructions" patch_instructions interp_x86-0)
  3658. \end{lstlisting}
  3659. \fi}
  3660. {\if\edition\pythonEd\pythonColor
  3661. Run the \code{run-tests.py} script to to check
  3662. whether the output programs produce the same result as the input
  3663. programs.
  3664. \fi}
  3665. \end{exercise}
  3666. \section{Generate Prelude and Conclusion}
  3667. \label{sec:print-x86}
  3668. \index{subject}{prelude}\index{subject}{conclusion}
  3669. The last step of the compiler from \LangVar{} to x86 is to generate
  3670. the \code{main} function with a prelude and conclusion wrapped around
  3671. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3672. discussed in section~\ref{sec:x86}.
  3673. When running on Mac OS X, your compiler should prefix an underscore to
  3674. all labels (for example, changing \key{main} to \key{\_main}).
  3675. %
  3676. \racket{The Racket call \code{(system-type 'os)} is useful for
  3677. determining which operating system the compiler is running on. It
  3678. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3679. %
  3680. \python{The Python \code{platform} library includes a \code{system()}
  3681. function that returns \code{'Linux'}, \code{'Windows'}, or
  3682. \code{'Darwin'} (for Mac).}
  3683. \begin{exercise}\normalfont\normalsize
  3684. %
  3685. Implement the \key{prelude\_and\_conclusion} pass in
  3686. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3687. %
  3688. {\if\edition\racketEd
  3689. In the \code{run-tests.rkt} script, add the following entry to the
  3690. list of \code{passes} and then run the script to test your compiler.
  3691. \begin{lstlisting}
  3692. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3693. \end{lstlisting}
  3694. %
  3695. Uncomment the call to the \key{compiler-tests} function
  3696. (appendix~\ref{appendix:utilities}), which tests your complete
  3697. compiler by executing the generated x86 code. It translates the x86
  3698. AST that you produce into a string by invoking the \code{print-x86}
  3699. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3700. the provided \key{runtime.c} file to \key{runtime.o} using
  3701. \key{gcc}. Run the script to test your compiler.
  3702. %
  3703. \fi}
  3704. {\if\edition\pythonEd\pythonColor
  3705. %
  3706. Run the \code{run-tests.py} script to to check whether the output
  3707. programs produce the same result as the input programs. That script
  3708. translates the x86 AST that you produce into a string by invoking the
  3709. \code{repr} method that is implemented by the x86 AST classes in
  3710. \code{x86\_ast.py}.
  3711. %
  3712. \fi}
  3713. \end{exercise}
  3714. \section{Challenge: Partial Evaluator for \LangVar{}}
  3715. \label{sec:pe-Lvar}
  3716. \index{subject}{partialevaluation@partial evaluation}
  3717. This section describes two optional challenge exercises that involve
  3718. adapting and improving the partial evaluator for \LangInt{} that was
  3719. introduced in section~\ref{sec:partial-evaluation}.
  3720. \begin{exercise}\label{ex:pe-Lvar}
  3721. \normalfont\normalsize
  3722. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3723. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3724. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3725. %
  3726. \racket{\key{let} binding}\python{assignment}
  3727. %
  3728. to the \LangInt{} language, so you will need to add cases for them in
  3729. the \code{pe\_exp}
  3730. %
  3731. \racket{function.}
  3732. %
  3733. \python{and \code{pe\_stmt} functions.}
  3734. %
  3735. Once complete, add the partial evaluation pass to the front of your
  3736. compiler, and make sure that your compiler still passes all the
  3737. tests.
  3738. \end{exercise}
  3739. \begin{exercise}
  3740. \normalfont\normalsize
  3741. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3742. \code{pe\_add} auxiliary functions with functions that know more about
  3743. arithmetic. For example, your partial evaluator should translate
  3744. {\if\edition\racketEd
  3745. \[
  3746. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3747. \code{(+ 2 (read))}
  3748. \]
  3749. \fi}
  3750. {\if\edition\pythonEd\pythonColor
  3751. \[
  3752. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3753. \code{2 + input\_int()}
  3754. \]
  3755. \fi}
  3756. %
  3757. To accomplish this, the \code{pe\_exp} function should produce output
  3758. in the form of the $\itm{residual}$ nonterminal of the following
  3759. grammar. The idea is that when processing an addition expression, we
  3760. can always produce one of the following: (1) an integer constant, (2)
  3761. an addition expression with an integer constant on the left-hand side
  3762. but not the right-hand side, or (3) an addition expression in which
  3763. neither subexpression is a constant.
  3764. %
  3765. {\if\edition\racketEd
  3766. \[
  3767. \begin{array}{lcl}
  3768. \itm{inert} &::=& \Var
  3769. \MID \LP\key{read}\RP
  3770. \MID \LP\key{-} ~\Var\RP
  3771. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3772. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3773. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3774. \itm{residual} &::=& \Int
  3775. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3776. \MID \itm{inert}
  3777. \end{array}
  3778. \]
  3779. \fi}
  3780. {\if\edition\pythonEd\pythonColor
  3781. \[
  3782. \begin{array}{lcl}
  3783. \itm{inert} &::=& \Var
  3784. \MID \key{input\_int}\LP\RP
  3785. \MID \key{-} \Var
  3786. \MID \key{-} \key{input\_int}\LP\RP
  3787. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3788. \itm{residual} &::=& \Int
  3789. \MID \Int ~ \key{+} ~ \itm{inert}
  3790. \MID \itm{inert}
  3791. \end{array}
  3792. \]
  3793. \fi}
  3794. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3795. inputs are $\itm{residual}$ expressions and they should return
  3796. $\itm{residual}$ expressions. Once the improvements are complete,
  3797. make sure that your compiler still passes all the tests. After
  3798. all, fast code is useless if it produces incorrect results!
  3799. \end{exercise}
  3800. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3801. {\if\edition\pythonEd\pythonColor
  3802. \chapter{Parsing}
  3803. \label{ch:parsing}
  3804. \setcounter{footnote}{0}
  3805. \index{subject}{parsing}
  3806. In this chapter we learn how to use the Lark parser
  3807. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3808. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3809. You will then be asked to use Lark to create a parser for \LangVar{}.
  3810. We also describe the parsing algorithms used inside Lark, studying the
  3811. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3812. A parser framework such as Lark takes in a specification of the
  3813. concrete syntax and an input program and produces a parse tree. Even
  3814. though a parser framework does most of the work for us, using one
  3815. properly requires some knowledge. In particular, we must learn about
  3816. its specification languages and we must learn how to deal with
  3817. ambiguity in our language specifications. Also, some algorithms, such
  3818. as LALR(1) place restrictions on the grammars they can handle, in
  3819. which case it helps to know the algorithm when trying to decipher the
  3820. error messages.
  3821. The process of parsing is traditionally subdivided into two phases:
  3822. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3823. analysis} (also called parsing). The lexical analysis phase
  3824. translates the sequence of characters into a sequence of
  3825. \emph{tokens}, that is, words consisting of several characters. The
  3826. parsing phase organizes the tokens into a \emph{parse tree} that
  3827. captures how the tokens were matched by rules in the grammar of the
  3828. language. The reason for the subdivision into two phases is to enable
  3829. the use of a faster but less powerful algorithm for lexical analysis
  3830. and the use of a slower but more powerful algorithm for parsing.
  3831. %
  3832. %% Likewise, parser generators typical come in pairs, with separate
  3833. %% generators for the lexical analyzer (or lexer for short) and for the
  3834. %% parser. A particularly influential pair of generators were
  3835. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3836. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3837. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3838. %% Compiler Compiler.
  3839. %
  3840. The Lark parser framework that we use in this chapter includes both
  3841. lexical analyzers and parsers. The next section discusses lexical
  3842. analysis and the remainder of the chapter discusses parsing.
  3843. \section{Lexical Analysis and Regular Expressions}
  3844. \label{sec:lex}
  3845. The lexical analyzers produced by Lark turn a sequence of characters
  3846. (a string) into a sequence of token objects. For example, a Lark
  3847. generated lexer for \LangInt{} converts the string
  3848. \begin{lstlisting}
  3849. 'print(1 + 3)'
  3850. \end{lstlisting}
  3851. \noindent into the following sequence of token objects
  3852. \begin{center}
  3853. \begin{minipage}{0.95\textwidth}
  3854. \begin{lstlisting}
  3855. Token('PRINT', 'print')
  3856. Token('LPAR', '(')
  3857. Token('INT', '1')
  3858. Token('PLUS', '+')
  3859. Token('INT', '3')
  3860. Token('RPAR', ')')
  3861. Token('NEWLINE', '\n')
  3862. \end{lstlisting}
  3863. \end{minipage}
  3864. \end{center}
  3865. Each token includes a field for its \code{type}, such as \code{'INT'},
  3866. and a field for its \code{value}, such as \code{'1'}.
  3867. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3868. specification language for Lark's lexer is one regular expression for
  3869. each type of token. The term \emph{regular} comes from the term
  3870. \emph{regular languages}, which are the languages that can be
  3871. recognized by a finite state machine. A \emph{regular expression} is a
  3872. pattern formed of the following core elements:\index{subject}{regular
  3873. expression}\footnote{Regular expressions traditionally include the
  3874. empty regular expression that matches any zero-length part of a
  3875. string, but Lark does not support the empty regular expression.}
  3876. \begin{itemize}
  3877. \item A single character $c$ is a regular expression and it only
  3878. matches itself. For example, the regular expression \code{a} only
  3879. matches with the string \code{'a'}.
  3880. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3881. R_2$ form a regular expression that matches any string that matches
  3882. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3883. matches the string \code{'a'} and the string \code{'c'}.
  3884. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3885. expression that matches any string that can be formed by
  3886. concatenating two strings, where the first string matches $R_1$ and
  3887. the second string matches $R_2$. For example, the regular expression
  3888. \code{(a|c)b} matches the strings \code{'ab'} and \code{'cb'}.
  3889. (Parentheses can be used to control the grouping of operators within
  3890. a regular expression.)
  3891. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3892. Kleene closure) is a regular expression that matches any string that
  3893. can be formed by concatenating zero or more strings that each match
  3894. the regular expression $R$. For example, the regular expression
  3895. \code{"((a|c)b)*"} matches the strings \code{'abcbab'} but not
  3896. \code{'abc'}.
  3897. \end{itemize}
  3898. For our convenience, Lark also accepts the following extended set of
  3899. regular expressions that are automatically translated into the core
  3900. regular expressions.
  3901. \begin{itemize}
  3902. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3903. c_n]$ is a regular expression that matches any one of the
  3904. characters. So $[c_1 c_2 \ldots c_n]$ is equivalent to
  3905. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3906. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3907. a regular expression that matches any character between $c_1$ and
  3908. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3909. letter in the alphabet.
  3910. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3911. is a regular expression that matches any string that can
  3912. be formed by concatenating one or more strings that each match $R$.
  3913. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3914. matches \code{'b'} and \code{'bzca'}.
  3915. \item A regular expression followed by a question mark $R\ttm{?}$
  3916. is a regular expression that matches any string that either
  3917. matches $R$ or that is the empty string.
  3918. For example, \code{a?b} matches both \code{'ab'} and \code{'b'}.
  3919. \item A string, such as \code{"hello"}, which matches itself,
  3920. that is, \code{'hello'}.
  3921. \end{itemize}
  3922. In a Lark grammar file, specify a name for each type of token followed
  3923. by a colon and then a regular expression surrounded by \code{/}
  3924. characters. For example, the \code{DIGIT}, \code{INT}, and
  3925. \code{NEWLINE} types of tokens are specified in the following way.
  3926. \begin{center}
  3927. \begin{minipage}{0.95\textwidth}
  3928. \begin{lstlisting}
  3929. DIGIT: /[0-9]/
  3930. INT: "-"? DIGIT+
  3931. NEWLINE: (/\r/? /\n/)+
  3932. \end{lstlisting}
  3933. \end{minipage}
  3934. \end{center}
  3935. \noindent In Lark, the regular expression operators can be used both
  3936. inside a regular expression, that is, between the \code{/} characters,
  3937. and they can be used to combine regular expressions, outside the
  3938. \code{/} characters.
  3939. \section{Grammars and Parse Trees}
  3940. \label{sec:CFG}
  3941. In section~\ref{sec:grammar} we learned how to use grammar rules to
  3942. specify the abstract syntax of a language. We now take a closer look
  3943. at using grammar rules to specify the concrete syntax. Recall that
  3944. each rule has a left-hand side and a right-hand side where the
  3945. left-hand side is a nonterminal and the right-hand side is a pattern
  3946. that defines what can be parsed as that nonterminal.
  3947. For concrete syntax, each right-hand side expresses a pattern for a
  3948. string, instead of a pattern for an abstract syntax tree. In
  3949. particular, each right-hand side is a sequence of
  3950. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  3951. terminal or nonterminal. A \emph{terminal}\index{subject}{terminal} is
  3952. a string. The nonterminals play the same role as in the abstract
  3953. syntax, defining categories of syntax. The nonterminals of a grammar
  3954. include the tokens defined in the lexer and all the nonterminals
  3955. defined by the grammar rules.
  3956. As an example, let us take a closer look at the concrete syntax of the
  3957. \LangInt{} language, repeated here.
  3958. \[
  3959. \begin{array}{l}
  3960. \LintGrammarPython \\
  3961. \begin{array}{rcl}
  3962. \LangInt{} &::=& \Stmt^{*}
  3963. \end{array}
  3964. \end{array}
  3965. \]
  3966. The Lark syntax for grammar rules differs slightly from the variant of
  3967. BNF that we use in this book. In particular, the notation $::=$ is
  3968. replaced by a single colon and the use of typewriter font for string
  3969. literals is replaced by quotation marks. The following grammar serves
  3970. as a first draft of a Lark grammar for \LangInt{}.
  3971. \begin{center}
  3972. \begin{minipage}{0.95\textwidth}
  3973. \begin{lstlisting}[escapechar=$]
  3974. exp: INT
  3975. | "input_int" "(" ")"
  3976. | "-" exp
  3977. | exp "+" exp
  3978. | exp "-" exp
  3979. | "(" exp ")"
  3980. stmt_list:
  3981. | stmt NEWLINE stmt_list
  3982. lang_int: stmt_list
  3983. \end{lstlisting}
  3984. \end{minipage}
  3985. \end{center}
  3986. Let us begin by discussing the rule \code{exp: INT} which says that if
  3987. the lexer matches a string to \code{INT}, then the parser also
  3988. categorizes the string as an \code{exp}. Recall that in
  3989. Section~\ref{sec:grammar} we defined the corresponding \Int{}
  3990. nonterminal with an English sentence. Here we specify \code{INT} more
  3991. formally using a type of token \code{INT} and its regular expression
  3992. \code{"-"? DIGIT+}.
  3993. The rule \code{exp: exp "+" exp} says that any string that matches
  3994. \code{exp}, followed by the \code{+} character, followed by another
  3995. string that matches \code{exp}, is itself an \code{exp}. For example,
  3996. the string \code{'1+3'} is an \code{exp} because \code{'1'} and
  3997. \code{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  3998. the rule for addition applies to categorize \code{'1+3'} as an
  3999. \code{exp}. We can visualize the application of grammar rules to parse
  4000. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4001. internal node in the tree is an application of a grammar rule and is
  4002. labeled with its left-hand side nonterminal. Each leaf node is a
  4003. substring of the input program. The parse tree for \code{'1+3'} is
  4004. shown in figure~\ref{fig:simple-parse-tree}.
  4005. \begin{figure}[tbp]
  4006. \begin{tcolorbox}[colback=white]
  4007. \centering
  4008. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4009. \end{tcolorbox}
  4010. \caption{The parse tree for \code{'1+3'}.}
  4011. \label{fig:simple-parse-tree}
  4012. \end{figure}
  4013. The result of parsing \code{'1+3'} with this Lark grammar is the
  4014. following parse tree as represented by \code{Tree} and \code{Token}
  4015. objects.
  4016. \begin{lstlisting}
  4017. Tree('lang_int',
  4018. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4019. Tree('exp', [Token('INT', '3')])])]),
  4020. Token('NEWLINE', '\n')])
  4021. \end{lstlisting}
  4022. The nodes that come from the lexer are \code{Token} objects whereas
  4023. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4024. object has a \code{data} field containing the name of the nonterminal
  4025. for the grammar rule that was applied. Each \code{Tree} object also
  4026. has a \code{children} field that is a list containing trees and/or
  4027. tokens. Note that Lark does not produce nodes for string literals in
  4028. the grammar. For example, the \code{Tree} node for the addition
  4029. expression has only two children for the two integers but is missing
  4030. its middle child for the \code{"+"} terminal. This would be
  4031. problematic except that Lark provides a mechanism for customizing the
  4032. \code{data} field of each \code{Tree} node based on which rule was
  4033. applied. Next to each alternative in a grammar rule, write \code{->}
  4034. followed by a string that you would like to appear in the \code{data}
  4035. field. The following is a second draft of a Lark grammar for
  4036. \LangInt{}, this time with more specific labels on the \code{Tree}
  4037. nodes.
  4038. \begin{center}
  4039. \begin{minipage}{0.95\textwidth}
  4040. \begin{lstlisting}[escapechar=$]
  4041. exp: INT -> int
  4042. | "input_int" "(" ")" -> input_int
  4043. | "-" exp -> usub
  4044. | exp "+" exp -> add
  4045. | exp "-" exp -> sub
  4046. | "(" exp ")" -> paren
  4047. stmt: "print" "(" exp ")" -> print
  4048. | exp -> expr
  4049. stmt_list: -> empty_stmt
  4050. | stmt NEWLINE stmt_list -> add_stmt
  4051. lang_int: stmt_list -> module
  4052. \end{lstlisting}
  4053. \end{minipage}
  4054. \end{center}
  4055. Here is the resulting parse tree.
  4056. \begin{lstlisting}
  4057. Tree('module',
  4058. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4059. Tree('int', [Token('INT', '3')])])]),
  4060. Token('NEWLINE', '\n')])
  4061. \end{lstlisting}
  4062. \section{Ambiguous Grammars}
  4063. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4064. can be parsed in more than one way. For example, consider the string
  4065. \code{'1-2+3'}. This string can parsed in two different ways using
  4066. our draft grammar, resulting in the two parse trees shown in
  4067. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4068. interpreting the second parse tree would yield \code{-4} even through
  4069. the correct answer is \code{2}.
  4070. \begin{figure}[tbp]
  4071. \begin{tcolorbox}[colback=white]
  4072. \centering
  4073. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4074. \end{tcolorbox}
  4075. \caption{The two parse trees for \code{'1-2+3'}.}
  4076. \label{fig:ambig-parse-tree}
  4077. \end{figure}
  4078. To deal with this problem we can change the grammar by categorizing
  4079. the syntax in a more fine grained fashion. In this case we want to
  4080. disallow the application of the rule \code{exp: exp "-" exp} when the
  4081. child on the right is an addition. To do this we can replace the
  4082. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4083. the expressions except for addition, as in the following.
  4084. \begin{center}
  4085. \begin{minipage}{0.95\textwidth}
  4086. \begin{lstlisting}[escapechar=$]
  4087. exp: exp "-" exp_no_add -> sub
  4088. | exp "+" exp -> add
  4089. | exp_no_add
  4090. exp_no_add: INT -> int
  4091. | "input_int" "(" ")" -> input_int
  4092. | "-" exp -> usub
  4093. | exp "-" exp_no_add -> sub
  4094. | "(" exp ")" -> paren
  4095. \end{lstlisting}
  4096. \end{minipage}
  4097. \end{center}
  4098. However, there remains some ambiguity in the grammar. For example, the
  4099. string \code{'1-2-3'} can still be parsed in two different ways, as
  4100. \code{'(1-2)-3'} (correct) or \code{'1-(2-3)'} (incorrect). That is
  4101. to say, subtraction is left associative. Likewise, addition in Python
  4102. is left associative. We also need to consider the interaction of unary
  4103. subtraction with both addition and subtraction. How should we parse
  4104. \code{'-1+2'}? Unary subtraction has higher
  4105. \emph{precendence}\index{subject}{precedence} than addition and
  4106. subtraction, so \code{'-1+2'} should parse the same as \code{'(-1)+2'}
  4107. and not \code{'-(1+2)'}. The grammar in
  4108. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4109. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4110. all the other expressions, and uses \code{exp\_hi} for the second
  4111. child in the rules for addition and subtraction. Furthermore, unary
  4112. subtraction uses \code{exp\_hi} for its child.
  4113. For languages with more operators and more precedence levels, one must
  4114. refine the \code{exp} nonterminal into several nonterminals, one for
  4115. each precedence level.
  4116. \begin{figure}[tbp]
  4117. \begin{tcolorbox}[colback=white]
  4118. \centering
  4119. \begin{lstlisting}[escapechar=$]
  4120. exp: exp "+" exp_hi -> add
  4121. | exp "-" exp_hi -> sub
  4122. | exp_hi
  4123. exp_hi: INT -> int
  4124. | "input_int" "(" ")" -> input_int
  4125. | "-" exp_hi -> usub
  4126. | "(" exp ")" -> paren
  4127. stmt: "print" "(" exp ")" -> print
  4128. | exp -> expr
  4129. stmt_list: -> empty_stmt
  4130. | stmt NEWLINE stmt_list -> add_stmt
  4131. lang_int: stmt_list -> module
  4132. \end{lstlisting}
  4133. \end{tcolorbox}
  4134. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4135. \label{fig:Lint-lark-grammar}
  4136. \end{figure}
  4137. \section{From Parse Trees to Abstract Syntax Trees}
  4138. As we have seen, the output of a Lark parser is a parse tree, that is,
  4139. a tree consisting of \code{Tree} and \code{Token} nodes. So the next
  4140. step is to convert the parse tree to an abstract syntax tree. This can
  4141. be accomplished with a recursive function that inspects the
  4142. \code{data} field of each node and then constructs the corresponding
  4143. AST node, using recursion to handle its children. The following is an
  4144. excerpt of the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4145. \begin{center}
  4146. \begin{minipage}{0.95\textwidth}
  4147. \begin{lstlisting}
  4148. def parse_tree_to_ast(e):
  4149. if e.data == 'int':
  4150. return Constant(int(e.children[0].value))
  4151. elif e.data == 'input_int':
  4152. return Call(Name('input_int'), [])
  4153. elif e.data == 'add':
  4154. e1, e2 = e.children
  4155. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4156. ...
  4157. else:
  4158. raise Exception('unhandled parse tree', e)
  4159. \end{lstlisting}
  4160. \end{minipage}
  4161. \end{center}
  4162. \begin{exercise}
  4163. \normalfont\normalsize
  4164. %
  4165. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4166. default parsing algorithm (Earley) with the \code{ambiguity} option
  4167. set to \code{'explicit'} so that if your grammar is ambiguous, the
  4168. output will include multiple parse trees which will indicate to you
  4169. that there is a problem with your grammar. Your parser should ignore
  4170. white space so we recommend using Lark's \code{\%ignore} directive
  4171. as follows.
  4172. \begin{lstlisting}
  4173. WS: /[ \t\f\r\n]/+
  4174. %ignore WS
  4175. \end{lstlisting}
  4176. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4177. Lark parser instead of using the \code{parse} function from
  4178. the \code{ast} module. Test your compiler on all of the \LangVar{}
  4179. programs that you have created and create four additional programs
  4180. that test for ambiguities in your grammar.
  4181. \end{exercise}
  4182. \section{The Earley Algorithm}
  4183. \label{sec:earley}
  4184. In this section we discuss the parsing algorithm of
  4185. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4186. algorithm is powerful in that it can handle any context-free grammar,
  4187. which makes it easy to use. However, it is not the most efficient
  4188. parsing algorithm: it is $O(n^3)$ for ambiguous grammars and $O(n^2)$
  4189. for unambiguous grammars, where $n$ is the number of tokens in the
  4190. input string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr}
  4191. we learn about the LALR(1) algorithm, which is more efficient but
  4192. cannot handle all context-free grammars.
  4193. The Earley algorithm can be viewed as an interpreter; it treats the
  4194. grammar as the program being interpreted and it treats the concrete
  4195. syntax of the program-to-be-parsed as its input. The Earley algorithm
  4196. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4197. keep track of its progress and to memoize its results. The chart is an
  4198. array with one slot for each position in the input string, where
  4199. position $0$ is before the first character and position $n$ is
  4200. immediately after the last character. So the array has length $n+1$
  4201. for an input string of length $n$. Each slot in the chart contains a
  4202. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4203. with a period indicating how much of its right-hand side has already
  4204. been parsed. For example, the dotted rule
  4205. \begin{lstlisting}
  4206. exp: exp "+" . exp_hi
  4207. \end{lstlisting}
  4208. represents a partial parse that has matched an \code{exp} followed by
  4209. \code{+}, but has not yet parsed an \code{exp} to the right of
  4210. \code{+}.
  4211. %
  4212. The Earley algorithm starts with an initialization phase, and then
  4213. repeats three actions---prediction, scanning, and completion---for as
  4214. long as opportunities arise. We demonstrate the Earley algorithm on a
  4215. running example, parsing the following program:
  4216. \begin{lstlisting}
  4217. print(1 + 3)
  4218. \end{lstlisting}
  4219. The algorithm's initialization phase creates dotted rules for all the
  4220. grammar rules whose left-hand side is the start symbol and places them
  4221. in slot $0$ of the chart. We also record the starting position of the
  4222. dotted rule in parentheses on the right. For example, given the
  4223. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4224. \begin{lstlisting}
  4225. lang_int: . stmt_list (0)
  4226. \end{lstlisting}
  4227. in slot $0$ of the chart. The algorithm then proceeds with
  4228. \emph{prediction} actions in which it adds more dotted rules to the
  4229. chart based on which nonterminals come immediately after a period. In
  4230. the above, the nonterminal \code{stmt\_list} appears after a period,
  4231. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4232. period at the beginning of their right-hand sides, as follows:
  4233. \begin{lstlisting}
  4234. stmt_list: . (0)
  4235. stmt_list: . stmt NEWLINE stmt_list (0)
  4236. \end{lstlisting}
  4237. We continue to perform prediction actions as more opportunities
  4238. arise. For example, the \code{stmt} nonterminal now appears after a
  4239. period, so we add all the rules for \code{stmt}.
  4240. \begin{lstlisting}
  4241. stmt: . "print" "(" exp ")" (0)
  4242. stmt: . exp (0)
  4243. \end{lstlisting}
  4244. This reveals yet more opportunities for prediction, so we add the grammar
  4245. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4246. \begin{lstlisting}[escapechar=$]
  4247. exp: . exp "+" exp_hi (0)
  4248. exp: . exp "-" exp_hi (0)
  4249. exp: . exp_hi (0)
  4250. exp_hi: . INT (0)
  4251. exp_hi: . "input_int" "(" ")" (0)
  4252. exp_hi: . "-" exp_hi (0)
  4253. exp_hi: . "(" exp ")" (0)
  4254. \end{lstlisting}
  4255. We have exhausted the opportunities for prediction, so the algorithm
  4256. proceeds to \emph{scanning}, in which we inspect the next input token
  4257. and look for a dotted rule at the current position that has a matching
  4258. terminal immediately following the period. In our running example, the
  4259. first input token is \code{"print"} so we identify the rule in slot
  4260. $0$ of the chart where \code{"print"} follows the period:
  4261. \begin{lstlisting}
  4262. stmt: . "print" "(" exp ")" (0)
  4263. \end{lstlisting}
  4264. We advance the period past \code{"print"} and add the resulting rule
  4265. to slot $1$ of the chart:
  4266. \begin{lstlisting}
  4267. stmt: "print" . "(" exp ")" (0)
  4268. \end{lstlisting}
  4269. If the new dotted rule had a nonterminal after the period, we would
  4270. need to carry out a prediction action, adding more dotted rules into
  4271. slot $1$. That is not the case, so we continue scanning. The next
  4272. input token is \code{"("}, so we add the following to slot $2$ of the
  4273. chart.
  4274. \begin{lstlisting}
  4275. stmt: "print" "(" . exp ")" (0)
  4276. \end{lstlisting}
  4277. Now we have a nonterminal after the period, so we carry out several
  4278. prediction actions, adding dotted rules for \code{exp} and
  4279. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4280. starting position $2$.
  4281. \begin{lstlisting}[escapechar=$]
  4282. exp: . exp "+" exp_hi (2)
  4283. exp: . exp "-" exp_hi (2)
  4284. exp: . exp_hi (2)
  4285. exp_hi: . INT (2)
  4286. exp_hi: . "input_int" "(" ")" (2)
  4287. exp_hi: . "-" exp_hi (2)
  4288. exp_hi: . "(" exp ")" (2)
  4289. \end{lstlisting}
  4290. With this prediction complete, we return to scanning, noting that the
  4291. next input token is \code{"1"} which the lexer parses as an
  4292. \code{INT}. There is a matching rule in slot $2$:
  4293. \begin{lstlisting}
  4294. exp_hi: . INT (2)
  4295. \end{lstlisting}
  4296. so we advance the period and put the following rule is slot $3$.
  4297. \begin{lstlisting}
  4298. exp_hi: INT . (2)
  4299. \end{lstlisting}
  4300. This brings us to \emph{completion} actions. When the period reaches
  4301. the end of a dotted rule, we recognize that the substring
  4302. has matched the nonterminal on the left-hand side of the rule, in this case
  4303. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4304. rules in slot $2$ (the starting position for the finished rule) if
  4305. the period is immediately followed by \code{exp\_hi}. So we identify
  4306. \begin{lstlisting}
  4307. exp: . exp_hi (2)
  4308. \end{lstlisting}
  4309. and add the following dotted rule to slot $3$
  4310. \begin{lstlisting}
  4311. exp: exp_hi . (2)
  4312. \end{lstlisting}
  4313. This triggers another completion step for the nonterminal \code{exp},
  4314. adding two more dotted rules to slot $3$.
  4315. \begin{lstlisting}[escapechar=$]
  4316. exp: exp . "+" exp_hi (2)
  4317. exp: exp . "-" exp_hi (2)
  4318. \end{lstlisting}
  4319. Returning to scanning, the next input token is \code{"+"}, so
  4320. we add the following to slot $4$.
  4321. \begin{lstlisting}[escapechar=$]
  4322. exp: exp "+" . exp_hi (2)
  4323. \end{lstlisting}
  4324. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4325. the following dotted rules to slot $4$ of the chart.
  4326. \begin{lstlisting}[escapechar=$]
  4327. exp_hi: . INT (4)
  4328. exp_hi: . "input_int" "(" ")" (4)
  4329. exp_hi: . "-" exp_hi (4)
  4330. exp_hi: . "(" exp ")" (4)
  4331. \end{lstlisting}
  4332. The next input token is \code{"3"} which the lexer categorized as an
  4333. \code{INT}, so we advance the period past \code{INT} for the rules in
  4334. slot $4$, of which there is just one, and put the following in slot $5$.
  4335. \begin{lstlisting}[escapechar=$]
  4336. exp_hi: INT . (4)
  4337. \end{lstlisting}
  4338. The period at the end of the rule triggers a completion action for the
  4339. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4340. So we advance the period and put the following in slot $5$.
  4341. \begin{lstlisting}[escapechar=$]
  4342. exp: exp "+" exp_hi . (2)
  4343. \end{lstlisting}
  4344. This triggers another completion action for the rules in slot $2$ that
  4345. have a period before \code{exp}.
  4346. \begin{lstlisting}[escapechar=$]
  4347. stmt: "print" "(" exp . ")" (0)
  4348. exp: exp . "+" exp_hi (2)
  4349. exp: exp . "-" exp_hi (2)
  4350. \end{lstlisting}
  4351. We scan the next input token \code{")"}, placing the following dotted
  4352. rule in slot $6$.
  4353. \begin{lstlisting}[escapechar=$]
  4354. stmt: "print" "(" exp ")" . (0)
  4355. \end{lstlisting}
  4356. This triggers the completion of \code{stmt} in slot $0$
  4357. \begin{lstlisting}
  4358. stmt_list: stmt . NEWLINE stmt_list (0)
  4359. \end{lstlisting}
  4360. The last input token is a \code{NEWLINE}, so we advance the period
  4361. and place the new dotted rule in slot $7$.
  4362. \begin{lstlisting}
  4363. stmt_list: stmt NEWLINE . stmt_list (0)
  4364. \end{lstlisting}
  4365. We are close to the end of parsing the input!
  4366. The period is before the \code{stmt\_list} nonterminal, so we
  4367. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4368. \begin{lstlisting}
  4369. stmt_list: . (7)
  4370. stmt_list: . stmt NEWLINE stmt_list (7)
  4371. stmt: . "print" "(" exp ")" (7)
  4372. stmt: . exp (7)
  4373. \end{lstlisting}
  4374. There is immediately an opportunity for completion of \code{stmt\_list},
  4375. so we add the following to slot $7$.
  4376. \begin{lstlisting}
  4377. stmt_list: stmt NEWLINE stmt_list . (0)
  4378. \end{lstlisting}
  4379. This triggers another completion action for \code{stmt\_list} in slot $0$
  4380. \begin{lstlisting}
  4381. lang_int: stmt_list . (0)
  4382. \end{lstlisting}
  4383. which in turn completes \code{lang\_int}, the start symbol of the
  4384. grammar, so the parsing of the input is complete.
  4385. For reference, we now give a general description of the Earley
  4386. algorithm.
  4387. \begin{enumerate}
  4388. \item The algorithm begins by initializing slot $0$ of the chart with the
  4389. grammar rule for the start symbol, placing a period at the beginning
  4390. of the right-hand side, and recording its starting position as $0$.
  4391. \item The algorithm repeatedly applies the following three kinds of
  4392. actions for as long as there are opportunities to do so.
  4393. \begin{itemize}
  4394. \item Prediction: if there is a rule in slot $k$ whose period comes
  4395. before a nonterminal, add the rules for that nonterminal into slot
  4396. $k$, placing a period at the beginning of their right-hand sides
  4397. and recording their starting position as $k$.
  4398. \item Scanning: If the token at position $k$ of the input string
  4399. matches the symbol after the period in a dotted rule in slot $k$
  4400. of the chart, advance the period in the dotted rule, adding
  4401. the result to slot $k+1$.
  4402. \item Completion: If a dotted rule in slot $k$ has a period at the
  4403. end, inspect the rules in the slot corresponding to the starting
  4404. position of the completed rule. If any of those rules have a
  4405. nonterminal following their period that matches the left-hand side
  4406. of the completed rule, then advance their period, placing the new
  4407. dotted rule in slot $k$.
  4408. \end{itemize}
  4409. While repeating these three actions, take care to never add
  4410. duplicate dotted rules to the chart.
  4411. \end{enumerate}
  4412. We have described how the Earley algorithm recognizes that an input
  4413. string matches a grammar, but we have not described how it builds a
  4414. parse tree. The basic idea is simple, but building parse trees in an
  4415. efficient way is more complex, requiring a data structure called a
  4416. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4417. to attach a partial parse tree to every dotted rule in the chart.
  4418. Initially, the tree node associated with a dotted rule has no
  4419. children. As the period moves to the right, the nodes from the
  4420. subparses are added as children to the tree node.
  4421. As mentioned at the beginning of this section, the Earley algorithm is
  4422. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4423. files that contain thousands of tokens in a reasonable amount of time,
  4424. but not millions.
  4425. %
  4426. In the next section we discuss the LALR(1) parsing algorithm, which is
  4427. efficient enough to use with even the largest of input files.
  4428. \section{The LALR(1) Algorithm}
  4429. \label{sec:lalr}
  4430. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4431. two phase approach in which it first compiles the grammar into a state
  4432. machine and then runs the state machine to parse an input string. The
  4433. second phase has time complexity $O(n)$ where $n$ is the number of
  4434. tokens in the input, so LALR(1) is the best one could hope for with
  4435. respect to efficiency.
  4436. %
  4437. A particularly influential implementation of LALR(1) is the
  4438. \texttt{yacc} parser generator by \citet{Johnson:1979qy}, which stands
  4439. for Yet Another Compiler Compiler.
  4440. %
  4441. The LALR(1) state machine uses a stack to record its progress in
  4442. parsing the input string. Each element of the stack is a pair: a
  4443. state number and a grammar symbol (a terminal or nonterminal). The
  4444. symbol characterizes the input that has been parsed so-far and the
  4445. state number is used to remember how to proceed once the next
  4446. symbol-worth of input has been parsed. Each state in the machine
  4447. represents where the parser stands in the parsing process with respect
  4448. to certain grammar rules. In particular, each state is associated with
  4449. a set of dotted rules.
  4450. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4451. (also called parse table) for the following simple but ambiguous
  4452. grammar:
  4453. \begin{lstlisting}[escapechar=$]
  4454. exp: INT
  4455. | exp "+" exp
  4456. stmt: "print" exp
  4457. start: stmt
  4458. \end{lstlisting}
  4459. Consider state 1 in Figure~\ref{fig:shift-reduce}. The parser has just
  4460. read in a \lstinline{"print"} token, so the top of the stack is
  4461. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4462. the input according to grammar rule 1, which is signified by showing
  4463. rule 1 with a period after the \code{"print"} token and before the
  4464. \code{exp} nonterminal. There are several rules that could apply next,
  4465. both rule 2 and 3, so state 1 also shows those rules with a period at
  4466. the beginning of their right-hand sides. The edges between states
  4467. indicate which transitions the machine should make depending on the
  4468. next input token. So, for example, if the next input token is
  4469. \code{INT} then the parser will push \code{INT} and the target state 4
  4470. on the stack and transition to state 4. Suppose we are now at the end
  4471. of the input. In state 4 it says we should reduce by rule 3, so we pop
  4472. from the stack the same number of items as the number of symbols in
  4473. the right-hand side of the rule, in this case just one. We then
  4474. momentarily jump to the state at the top of the stack (state 1) and
  4475. then follow the goto edge that corresponds to the left-hand side of
  4476. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4477. state 3. (A slightly longer example parse is shown in
  4478. Figure~\ref{fig:shift-reduce}.)
  4479. \begin{figure}[htbp]
  4480. \centering
  4481. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4482. \caption{An LALR(1) parse table and a trace of an example run.}
  4483. \label{fig:shift-reduce}
  4484. \end{figure}
  4485. In general, the algorithm works as follows. Set the current state to
  4486. state $0$. Then repeat the following, looking at the next input token.
  4487. \begin{itemize}
  4488. \item If there there is a shift edge for the input token in the
  4489. current state, push the edge's target state and the input token on
  4490. the stack and proceed to the edge's target state.
  4491. \item If there is a reduce action for the input token in the current
  4492. state, pop $k$ elements from the stack, where $k$ is the number of
  4493. symbols in the right-hand side of the rule being reduced. Jump to
  4494. the state at the top of the stack and then follow the goto edge for
  4495. the nonterminal that matches the left-hand side of the rule that we
  4496. reducing by. Push the edge's target state and the nonterminal on the
  4497. stack.
  4498. \end{itemize}
  4499. Notice that in state 6 of Figure~\ref{fig:shift-reduce} there is both
  4500. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4501. algorithm does not know which action to take in this case. When a
  4502. state has both a shift and a reduce action for the same token, we say
  4503. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4504. will arise, for example, when trying to parse the input
  4505. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2}
  4506. the parser will be in state 6, and it will not know whether to
  4507. reduce to form an \code{exp} of \lstinline{1 + 2}, or whether it
  4508. should proceed by shifting the next \lstinline{+} from the input.
  4509. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4510. arises when there are two reduce actions in a state for the same
  4511. token. To understand which grammars gives rise to shift/reduce and
  4512. reduce/reduce conflicts, it helps to know how the parse table is
  4513. generated from the grammar, which we discuss next.
  4514. The parse table is generated one state at a time. State 0 represents
  4515. the start of the parser. We add the grammar rule for the start symbol
  4516. to this state with a period at the beginning of the right-hand side,
  4517. similar to the initialization phase of the Earley parser. If the
  4518. period appears immediately before another nonterminal, we add all the
  4519. rules with that nonterminal on the left-hand side. Again, we place a
  4520. period at the beginning of the right-hand side of each the new
  4521. rules. This process, called \emph{state closure}, is continued
  4522. until there are no more rules to add (similar to the prediction
  4523. actions of an Earley parser). We then examine each dotted rule in the
  4524. current state $I$. Suppose a dotted rule has the form $A ::=
  4525. s_1.\,X s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4526. are sequences of symbols. We create a new state, call it $J$. If $X$
  4527. is a terminal, we create a shift edge from $I$ to $J$ (analogous to
  4528. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4529. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4530. state $J$. We start by adding all dotted rules from state $I$ that
  4531. have the form $B ::= s_1.\,Xs_2$ (where $B$ is any nonterminal and
  4532. $s_1$ and $s_2$ are arbitrary sequences of symbols), but with
  4533. the period moved past the $X$. (This is analogous to completion in
  4534. the Earley algorithm.) We then perform state closure on $J$. This
  4535. process repeats until there are no more states or edges to add.
  4536. We then mark states as accepting states if they have a dotted rule
  4537. that is the start rule with a period at the end. Also, to add
  4538. in the reduce actions, we look for any state containing a dotted rule
  4539. with a period at the end. Let $n$ be the rule number for this dotted
  4540. rule. We then put a reduce $n$ action into that state for every token
  4541. $Y$. For example, in Figure~\ref{fig:shift-reduce} state 4 has an
  4542. dotted rule with a period at the end. We therefore put a reduce by
  4543. rule 3 action into state 4 for every
  4544. token.
  4545. When inserting reduce actions, take care to spot any shift/reduce or
  4546. reduce/reduce conflicts. If there are any, abort the construction of
  4547. the parse table.
  4548. \begin{exercise}
  4549. \normalfont\normalsize
  4550. %
  4551. On a piece of paper, walk through the parse table generation process
  4552. for the grammar at the top of figure~\ref{fig:shift-reduce} and check
  4553. your results against parse table in figure~\ref{fig:shift-reduce}.
  4554. \end{exercise}
  4555. \begin{exercise}
  4556. \normalfont\normalsize
  4557. %
  4558. Change the parser in your compiler for \LangVar{} to set the
  4559. \code{parser} option of Lark to \code{'lalr'}. Test your compiler on
  4560. all the \LangVar{} programs that you have created. In doing so, Lark
  4561. may signal an error due to shift/reduce or reduce/reduce conflicts
  4562. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4563. remove those conflicts.
  4564. \end{exercise}
  4565. \section{Further Reading}
  4566. In this chapter we have just scratched the surface of the field of
  4567. parsing, with the study of a very general but less efficient algorithm
  4568. (Earley) and with a more limited but highly efficient algorithm
  4569. (LALR). There are many more algorithms, and classes of grammars, that
  4570. fall between these two ends of the spectrum. We recommend the reader
  4571. to \citet{Aho:2006wb} for a thorough treatment of parsing.
  4572. Regarding lexical analysis, we described the specification language,
  4573. the regular expressions, but not the algorithms for recognizing them.
  4574. In short, regular expressions can be translated to nondeterministic
  4575. finite automata, which in turn are translated to finite automata. We
  4576. refer the reader again to \citet{Aho:2006wb} for all the details on
  4577. lexical analysis.
  4578. \fi}
  4579. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4580. \chapter{Register Allocation}
  4581. \label{ch:register-allocation-Lvar}
  4582. \setcounter{footnote}{0}
  4583. \index{subject}{register allocation}
  4584. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4585. storing variables on the procedure call stack. The CPU may require tens
  4586. to hundreds of cycles to access a location on the stack, whereas
  4587. accessing a register takes only a single cycle. In this chapter we
  4588. improve the efficiency of our generated code by storing some variables
  4589. in registers. The goal of register allocation is to fit as many
  4590. variables into registers as possible. Some programs have more
  4591. variables than registers, so we cannot always map each variable to a
  4592. different register. Fortunately, it is common for different variables
  4593. to be in use during different periods of time during program
  4594. execution, and in those cases we can map multiple variables to the
  4595. same register.
  4596. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4597. example. The source program is on the left and the output of
  4598. instruction selection\index{subject}{instruction selection}
  4599. is on the right. The program is almost
  4600. completely in the x86 assembly language, but it still uses variables.
  4601. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4602. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4603. the other hand, is used only after this point, so \code{x} and
  4604. \code{z} could share the same register.
  4605. \begin{figure}
  4606. \begin{tcolorbox}[colback=white]
  4607. \begin{minipage}{0.45\textwidth}
  4608. Example \LangVar{} program:
  4609. % var_test_28.rkt
  4610. {\if\edition\racketEd
  4611. \begin{lstlisting}
  4612. (let ([v 1])
  4613. (let ([w 42])
  4614. (let ([x (+ v 7)])
  4615. (let ([y x])
  4616. (let ([z (+ x w)])
  4617. (+ z (- y)))))))
  4618. \end{lstlisting}
  4619. \fi}
  4620. {\if\edition\pythonEd\pythonColor
  4621. \begin{lstlisting}
  4622. v = 1
  4623. w = 42
  4624. x = v + 7
  4625. y = x
  4626. z = x + w
  4627. print(z + (- y))
  4628. \end{lstlisting}
  4629. \fi}
  4630. \end{minipage}
  4631. \begin{minipage}{0.45\textwidth}
  4632. After instruction selection:
  4633. {\if\edition\racketEd
  4634. \begin{lstlisting}
  4635. locals-types:
  4636. x : Integer, y : Integer,
  4637. z : Integer, t : Integer,
  4638. v : Integer, w : Integer
  4639. start:
  4640. movq $1, v
  4641. movq $42, w
  4642. movq v, x
  4643. addq $7, x
  4644. movq x, y
  4645. movq x, z
  4646. addq w, z
  4647. movq y, t
  4648. negq t
  4649. movq z, %rax
  4650. addq t, %rax
  4651. jmp conclusion
  4652. \end{lstlisting}
  4653. \fi}
  4654. {\if\edition\pythonEd\pythonColor
  4655. \begin{lstlisting}
  4656. movq $1, v
  4657. movq $42, w
  4658. movq v, x
  4659. addq $7, x
  4660. movq x, y
  4661. movq x, z
  4662. addq w, z
  4663. movq y, tmp_0
  4664. negq tmp_0
  4665. movq z, tmp_1
  4666. addq tmp_0, tmp_1
  4667. movq tmp_1, %rdi
  4668. callq print_int
  4669. \end{lstlisting}
  4670. \fi}
  4671. \end{minipage}
  4672. \end{tcolorbox}
  4673. \caption{A running example for register allocation.}
  4674. \label{fig:reg-eg}
  4675. \end{figure}
  4676. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4677. compute where a variable is in use. Once we have that information, we
  4678. compute which variables are in use at the same time, that is, which ones
  4679. \emph{interfere}\index{subject}{interfere} with each other, and
  4680. represent this relation as an undirected graph whose vertices are
  4681. variables and edges indicate when two variables interfere
  4682. (section~\ref{sec:build-interference}). We then model register
  4683. allocation as a graph coloring problem
  4684. (section~\ref{sec:graph-coloring}).
  4685. If we run out of registers despite these efforts, we place the
  4686. remaining variables on the stack, similarly to how we handled
  4687. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4688. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4689. location. The decision to spill a variable is handled as part of the
  4690. graph coloring process.
  4691. We make the simplifying assumption that each variable is assigned to
  4692. one location (a register or stack address). A more sophisticated
  4693. approach is to assign a variable to one or more locations in different
  4694. regions of the program. For example, if a variable is used many times
  4695. in short sequence and then used again only after many other
  4696. instructions, it could be more efficient to assign the variable to a
  4697. register during the initial sequence and then move it to the stack for
  4698. the rest of its lifetime. We refer the interested reader to
  4699. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4700. approach.
  4701. % discuss prioritizing variables based on how much they are used.
  4702. \section{Registers and Calling Conventions}
  4703. \label{sec:calling-conventions}
  4704. \index{subject}{calling conventions}
  4705. As we perform register allocation, we must be aware of the
  4706. \emph{calling conventions} \index{subject}{calling conventions} that
  4707. govern how function calls are performed in x86.
  4708. %
  4709. Even though \LangVar{} does not include programmer-defined functions,
  4710. our generated code includes a \code{main} function that is called by
  4711. the operating system and our generated code contains calls to the
  4712. \code{read\_int} function.
  4713. Function calls require coordination between two pieces of code that
  4714. may be written by different programmers or generated by different
  4715. compilers. Here we follow the System V calling conventions that are
  4716. used by the GNU C compiler on Linux and
  4717. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4718. %
  4719. The calling conventions include rules about how functions share the
  4720. use of registers. In particular, the caller is responsible for freeing
  4721. some registers prior to the function call for use by the callee.
  4722. These are called the \emph{caller-saved registers}
  4723. \index{subject}{caller-saved registers}
  4724. and they are
  4725. \begin{lstlisting}
  4726. rax rcx rdx rsi rdi r8 r9 r10 r11
  4727. \end{lstlisting}
  4728. On the other hand, the callee is responsible for preserving the values
  4729. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4730. which are
  4731. \begin{lstlisting}
  4732. rsp rbp rbx r12 r13 r14 r15
  4733. \end{lstlisting}
  4734. We can think about this caller/callee convention from two points of
  4735. view, the caller view and the callee view, as follows:
  4736. \begin{itemize}
  4737. \item The caller should assume that all the caller-saved registers get
  4738. overwritten with arbitrary values by the callee. On the other hand,
  4739. the caller can safely assume that all the callee-saved registers
  4740. retain their original values.
  4741. \item The callee can freely use any of the caller-saved registers.
  4742. However, if the callee wants to use a callee-saved register, the
  4743. callee must arrange to put the original value back in the register
  4744. prior to returning to the caller. This can be accomplished by saving
  4745. the value to the stack in the prelude of the function and restoring
  4746. the value in the conclusion of the function.
  4747. \end{itemize}
  4748. In x86, registers are also used for passing arguments to a function
  4749. and for the return value. In particular, the first six arguments of a
  4750. function are passed in the following six registers, in this order.
  4751. \begin{lstlisting}
  4752. rdi rsi rdx rcx r8 r9
  4753. \end{lstlisting}
  4754. We refer to these six registers are the argument-passing registers
  4755. \index{subject}{argument-passing registers}.
  4756. If there are more than six arguments, the convention is to use space
  4757. on the frame of the caller for the rest of the arguments. In
  4758. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4759. argument and the rest of the arguments, which simplifies the treatment
  4760. of efficient tail calls.
  4761. %
  4762. \racket{For now, the only function we care about is \code{read\_int},
  4763. which takes zero arguments.}
  4764. %
  4765. \python{For now, the only functions we care about are \code{read\_int}
  4766. and \code{print\_int}, which take zero and one argument, respectively.}
  4767. %
  4768. The register \code{rax} is used for the return value of a function.
  4769. The next question is how these calling conventions impact register
  4770. allocation. Consider the \LangVar{} program presented in
  4771. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4772. example from the caller point of view and then from the callee point
  4773. of view. We refer to a variable that is in use during a function call
  4774. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4775. The program makes two calls to \READOP{}. The variable \code{x} is
  4776. call-live because it is in use during the second call to \READOP{}; we
  4777. must ensure that the value in \code{x} does not get overwritten during
  4778. the call to \READOP{}. One obvious approach is to save all the values
  4779. that reside in caller-saved registers to the stack prior to each
  4780. function call and to restore them after each call. That way, if the
  4781. register allocator chooses to assign \code{x} to a caller-saved
  4782. register, its value will be preserved across the call to \READOP{}.
  4783. However, saving and restoring to the stack is relatively slow. If
  4784. \code{x} is not used many times, it may be better to assign \code{x}
  4785. to a stack location in the first place. Or better yet, if we can
  4786. arrange for \code{x} to be placed in a callee-saved register, then it
  4787. won't need to be saved and restored during function calls.
  4788. We recommend an approach that captures these issues in the
  4789. interference graph, without complicating the graph coloring algorithm.
  4790. During liveness analysis we know which variables are call-live because
  4791. we compute which variables are in use at every instruction
  4792. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4793. interference graph (section~\ref{sec:build-interference}), we can
  4794. place an edge in the interference graph between each call-live
  4795. variable and the caller-saved registers. This will prevent the graph
  4796. coloring algorithm from assigning call-live variables to caller-saved
  4797. registers.
  4798. On the other hand, for variables that are not call-live, we prefer
  4799. placing them in caller-saved registers to leave more room for
  4800. call-live variables in the callee-saved registers. This can also be
  4801. implemented without complicating the graph coloring algorithm. We
  4802. recommend that the graph coloring algorithm assign variables to
  4803. natural numbers, choosing the lowest number for which there is no
  4804. interference. After the coloring is complete, we map the numbers to
  4805. registers and stack locations: mapping the lowest numbers to
  4806. caller-saved registers, the next lowest to callee-saved registers, and
  4807. the largest numbers to stack locations. This ordering gives preference
  4808. to registers over stack locations and to caller-saved registers over
  4809. callee-saved registers.
  4810. Returning to the example in
  4811. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4812. generated x86 code on the right-hand side. Variable \code{x} is
  4813. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4814. in a safe place during the second call to \code{read\_int}. Next,
  4815. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4816. because \code{y} is not a call-live variable.
  4817. We have completed the analysis from the caller point of view, so now
  4818. we switch to the callee point of view, focusing on the prelude and
  4819. conclusion of the \code{main} function. As usual, the prelude begins
  4820. with saving the \code{rbp} register to the stack and setting the
  4821. \code{rbp} to the current stack pointer. We now know why it is
  4822. necessary to save the \code{rbp}: it is a callee-saved register. The
  4823. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4824. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4825. (\code{x}). The other callee-saved registers are not saved in the
  4826. prelude because they are not used. The prelude subtracts 8 bytes from
  4827. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4828. conclusion, we see that \code{rbx} is restored from the stack with a
  4829. \code{popq} instruction.
  4830. \index{subject}{prelude}\index{subject}{conclusion}
  4831. \begin{figure}[tp]
  4832. \begin{tcolorbox}[colback=white]
  4833. \begin{minipage}{0.45\textwidth}
  4834. Example \LangVar{} program:
  4835. %var_test_14.rkt
  4836. {\if\edition\racketEd
  4837. \begin{lstlisting}
  4838. (let ([x (read)])
  4839. (let ([y (read)])
  4840. (+ (+ x y) 42)))
  4841. \end{lstlisting}
  4842. \fi}
  4843. {\if\edition\pythonEd\pythonColor
  4844. \begin{lstlisting}
  4845. x = input_int()
  4846. y = input_int()
  4847. print((x + y) + 42)
  4848. \end{lstlisting}
  4849. \fi}
  4850. \end{minipage}
  4851. \begin{minipage}{0.45\textwidth}
  4852. Generated x86 assembly:
  4853. {\if\edition\racketEd
  4854. \begin{lstlisting}
  4855. start:
  4856. callq read_int
  4857. movq %rax, %rbx
  4858. callq read_int
  4859. movq %rax, %rcx
  4860. addq %rcx, %rbx
  4861. movq %rbx, %rax
  4862. addq $42, %rax
  4863. jmp _conclusion
  4864. .globl main
  4865. main:
  4866. pushq %rbp
  4867. movq %rsp, %rbp
  4868. pushq %rbx
  4869. subq $8, %rsp
  4870. jmp start
  4871. conclusion:
  4872. addq $8, %rsp
  4873. popq %rbx
  4874. popq %rbp
  4875. retq
  4876. \end{lstlisting}
  4877. \fi}
  4878. {\if\edition\pythonEd\pythonColor
  4879. \begin{lstlisting}
  4880. .globl main
  4881. main:
  4882. pushq %rbp
  4883. movq %rsp, %rbp
  4884. pushq %rbx
  4885. subq $8, %rsp
  4886. callq read_int
  4887. movq %rax, %rbx
  4888. callq read_int
  4889. movq %rax, %rcx
  4890. movq %rbx, %rdx
  4891. addq %rcx, %rdx
  4892. movq %rdx, %rcx
  4893. addq $42, %rcx
  4894. movq %rcx, %rdi
  4895. callq print_int
  4896. addq $8, %rsp
  4897. popq %rbx
  4898. popq %rbp
  4899. retq
  4900. \end{lstlisting}
  4901. \fi}
  4902. \end{minipage}
  4903. \end{tcolorbox}
  4904. \caption{An example with function calls.}
  4905. \label{fig:example-calling-conventions}
  4906. \end{figure}
  4907. %\clearpage
  4908. \section{Liveness Analysis}
  4909. \label{sec:liveness-analysis-Lvar}
  4910. \index{subject}{liveness analysis}
  4911. The \code{uncover\_live} \racket{pass}\python{function} performs
  4912. \emph{liveness analysis}; that is, it discovers which variables are
  4913. in use in different regions of a program.
  4914. %
  4915. A variable or register is \emph{live} at a program point if its
  4916. current value is used at some later point in the program. We refer to
  4917. variables, stack locations, and registers collectively as
  4918. \emph{locations}.
  4919. %
  4920. Consider the following code fragment in which there are two writes to
  4921. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4922. time?
  4923. \begin{center}
  4924. \begin{minipage}{0.96\textwidth}
  4925. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4926. movq $5, a
  4927. movq $30, b
  4928. movq a, c
  4929. movq $10, b
  4930. addq b, c
  4931. \end{lstlisting}
  4932. \end{minipage}
  4933. \end{center}
  4934. The answer is no, because \code{a} is live from line 1 to 3 and
  4935. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4936. line 2 is never used because it is overwritten (line 4) before the
  4937. next read (line 5).
  4938. The live locations for each instruction can be computed by traversing
  4939. the instruction sequence back to front (i.e., backward in execution
  4940. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4941. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4942. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4943. locations before instruction $I_k$. \racket{We recommend representing
  4944. these sets with the Racket \code{set} data structure described in
  4945. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4946. with the Python
  4947. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4948. data structure.}
  4949. {\if\edition\racketEd
  4950. \begin{figure}[tp]
  4951. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4952. \small
  4953. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4954. A \emph{set} is an unordered collection of elements without duplicates.
  4955. Here are some of the operations defined on sets.
  4956. \index{subject}{set}
  4957. \begin{description}
  4958. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4959. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4960. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4961. difference of the two sets.
  4962. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4963. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4964. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4965. \end{description}
  4966. \end{tcolorbox}
  4967. %\end{wrapfigure}
  4968. \caption{The \code{set} data structure.}
  4969. \label{fig:set}
  4970. \end{figure}
  4971. \fi}
  4972. The locations that are live after an instruction are its
  4973. \emph{live-after}\index{subject}{live-after} set, and the locations
  4974. that are live before an instruction are its
  4975. \emph{live-before}\index{subject}{live-before} set. The live-after
  4976. set of an instruction is always the same as the live-before set of the
  4977. next instruction.
  4978. \begin{equation} \label{eq:live-after-before-next}
  4979. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4980. \end{equation}
  4981. To start things off, there are no live locations after the last
  4982. instruction, so
  4983. \begin{equation}\label{eq:live-last-empty}
  4984. L_{\mathsf{after}}(n) = \emptyset
  4985. \end{equation}
  4986. We then apply the following rule repeatedly, traversing the
  4987. instruction sequence back to front.
  4988. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4989. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4990. \end{equation}
  4991. where $W(k)$ are the locations written to by instruction $I_k$, and
  4992. $R(k)$ are the locations read by instruction $I_k$.
  4993. {\if\edition\racketEd
  4994. %
  4995. There is a special case for \code{jmp} instructions. The locations
  4996. that are live before a \code{jmp} should be the locations in
  4997. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4998. maintaining an alist named \code{label->live} that maps each label to
  4999. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5000. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5001. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5002. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5003. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5004. %
  5005. \fi}
  5006. Let us walk through the previous example, applying these formulas
  5007. starting with the instruction on line 5 of the code fragment. We
  5008. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5009. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5010. $\emptyset$ because it is the last instruction
  5011. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5012. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5013. variables \code{b} and \code{c}
  5014. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5015. \[
  5016. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5017. \]
  5018. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5019. the live-before set from line 5 to be the live-after set for this
  5020. instruction (formula~\eqref{eq:live-after-before-next}).
  5021. \[
  5022. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5023. \]
  5024. This move instruction writes to \code{b} and does not read from any
  5025. variables, so we have the following live-before set
  5026. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5027. \[
  5028. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5029. \]
  5030. The live-before for instruction \code{movq a, c}
  5031. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5032. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5033. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5034. variable that is not live and does not read from a variable.
  5035. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5036. because it writes to variable \code{a}.
  5037. \begin{figure}[tbp]
  5038. \centering
  5039. \begin{tcolorbox}[colback=white]
  5040. \hspace{10pt}
  5041. \begin{minipage}{0.4\textwidth}
  5042. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5043. movq $5, a
  5044. movq $30, b
  5045. movq a, c
  5046. movq $10, b
  5047. addq b, c
  5048. \end{lstlisting}
  5049. \end{minipage}
  5050. \vrule\hspace{10pt}
  5051. \begin{minipage}{0.45\textwidth}
  5052. \begin{align*}
  5053. L_{\mathsf{before}}(1)= \emptyset,
  5054. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5055. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5056. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5057. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5058. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5059. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5060. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5061. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5062. L_{\mathsf{after}}(5)= \emptyset
  5063. \end{align*}
  5064. \end{minipage}
  5065. \end{tcolorbox}
  5066. \caption{Example output of liveness analysis on a short example.}
  5067. \label{fig:liveness-example-0}
  5068. \end{figure}
  5069. \begin{exercise}\normalfont\normalsize
  5070. Perform liveness analysis by hand on the running example in
  5071. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5072. sets for each instruction. Compare your answers to the solution
  5073. shown in figure~\ref{fig:live-eg}.
  5074. \end{exercise}
  5075. \begin{figure}[tp]
  5076. \hspace{20pt}
  5077. \begin{minipage}{0.55\textwidth}
  5078. \begin{tcolorbox}[colback=white]
  5079. {\if\edition\racketEd
  5080. \begin{lstlisting}
  5081. |$\{\ttm{rsp}\}$|
  5082. movq $1, v
  5083. |$\{\ttm{v},\ttm{rsp}\}$|
  5084. movq $42, w
  5085. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5086. movq v, x
  5087. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5088. addq $7, x
  5089. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5090. movq x, y
  5091. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5092. movq x, z
  5093. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5094. addq w, z
  5095. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5096. movq y, t
  5097. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5098. negq t
  5099. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5100. movq z, %rax
  5101. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5102. addq t, %rax
  5103. |$\{\ttm{rax},\ttm{rsp}\}$|
  5104. jmp conclusion
  5105. \end{lstlisting}
  5106. \fi}
  5107. {\if\edition\pythonEd\pythonColor
  5108. \begin{lstlisting}
  5109. movq $1, v
  5110. |$\{\ttm{v}\}$|
  5111. movq $42, w
  5112. |$\{\ttm{w}, \ttm{v}\}$|
  5113. movq v, x
  5114. |$\{\ttm{w}, \ttm{x}\}$|
  5115. addq $7, x
  5116. |$\{\ttm{w}, \ttm{x}\}$|
  5117. movq x, y
  5118. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5119. movq x, z
  5120. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5121. addq w, z
  5122. |$\{\ttm{y}, \ttm{z}\}$|
  5123. movq y, tmp_0
  5124. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5125. negq tmp_0
  5126. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5127. movq z, tmp_1
  5128. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5129. addq tmp_0, tmp_1
  5130. |$\{\ttm{tmp\_1}\}$|
  5131. movq tmp_1, %rdi
  5132. |$\{\ttm{rdi}\}$|
  5133. callq print_int
  5134. |$\{\}$|
  5135. \end{lstlisting}
  5136. \fi}
  5137. \end{tcolorbox}
  5138. \end{minipage}
  5139. \caption{The running example annotated with live-after sets.}
  5140. \label{fig:live-eg}
  5141. \end{figure}
  5142. \begin{exercise}\normalfont\normalsize
  5143. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5144. %
  5145. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5146. field of the \code{Block} structure.}
  5147. %
  5148. \python{Return a dictionary that maps each instruction to its
  5149. live-after set.}
  5150. %
  5151. \racket{We recommend creating an auxiliary function that takes a list
  5152. of instructions and an initial live-after set (typically empty) and
  5153. returns the list of live-after sets.}
  5154. %
  5155. We recommend creating auxiliary functions to (1) compute the set
  5156. of locations that appear in an \Arg{}, (2) compute the locations read
  5157. by an instruction (the $R$ function), and (3) the locations written by
  5158. an instruction (the $W$ function). The \code{callq} instruction should
  5159. include all the caller-saved registers in its write set $W$ because
  5160. the calling convention says that those registers may be written to
  5161. during the function call. Likewise, the \code{callq} instruction
  5162. should include the appropriate argument-passing registers in its
  5163. read set $R$, depending on the arity of the function being
  5164. called. (This is why the abstract syntax for \code{callq} includes the
  5165. arity.)
  5166. \end{exercise}
  5167. %\clearpage
  5168. \section{Build the Interference Graph}
  5169. \label{sec:build-interference}
  5170. {\if\edition\racketEd
  5171. \begin{figure}[tp]
  5172. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5173. \small
  5174. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5175. A \emph{graph} is a collection of vertices and edges where each
  5176. edge connects two vertices. A graph is \emph{directed} if each
  5177. edge points from a source to a target. Otherwise the graph is
  5178. \emph{undirected}.
  5179. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5180. \begin{description}
  5181. %% We currently don't use directed graphs. We instead use
  5182. %% directed multi-graphs. -Jeremy
  5183. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5184. directed graph from a list of edges. Each edge is a list
  5185. containing the source and target vertex.
  5186. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5187. undirected graph from a list of edges. Each edge is represented by
  5188. a list containing two vertices.
  5189. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5190. inserts a vertex into the graph.
  5191. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5192. inserts an edge between the two vertices.
  5193. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5194. returns a sequence of vertices adjacent to the vertex.
  5195. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5196. returns a sequence of all vertices in the graph.
  5197. \end{description}
  5198. \end{tcolorbox}
  5199. %\end{wrapfigure}
  5200. \caption{The Racket \code{graph} package.}
  5201. \label{fig:graph}
  5202. \end{figure}
  5203. \fi}
  5204. On the basis of the liveness analysis, we know where each location is
  5205. live. However, during register allocation, we need to answer
  5206. questions of the specific form: are locations $u$ and $v$ live at the
  5207. same time? (If so, they cannot be assigned to the same register.) To
  5208. make this question more efficient to answer, we create an explicit
  5209. data structure, an \emph{interference
  5210. graph}\index{subject}{interference graph}. An interference graph is
  5211. an undirected graph that has a node for every variable and register
  5212. and has an edge between two nodes if they are
  5213. live at the same time, that is, if they interfere with each other.
  5214. %
  5215. \racket{We recommend using the Racket \code{graph} package
  5216. (figure~\ref{fig:graph}) to represent the interference graph.}
  5217. %
  5218. \python{We provide implementations of directed and undirected graph
  5219. data structures in the file \code{graph.py} of the support code.}
  5220. A straightforward way to compute the interference graph is to look at
  5221. the set of live locations between each instruction and add an edge to
  5222. the graph for every pair of variables in the same set. This approach
  5223. is less than ideal for two reasons. First, it can be expensive because
  5224. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5225. locations. Second, in the special case in which two locations hold the
  5226. same value (because one was assigned to the other), they can be live
  5227. at the same time without interfering with each other.
  5228. A better way to compute the interference graph is to focus on
  5229. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5230. must not overwrite something in a live location. So for each
  5231. instruction, we create an edge between the locations being written to
  5232. and the live locations. (However, a location never interferes with
  5233. itself.) For the \key{callq} instruction, we consider all the
  5234. caller-saved registers to have been written to, so an edge is added
  5235. between every live variable and every caller-saved register. Also, for
  5236. \key{movq} there is the special case of two variables holding the same
  5237. value. If a live variable $v$ is the same as the source of the
  5238. \key{movq}, then there is no need to add an edge between $v$ and the
  5239. destination, because they both hold the same value.
  5240. %
  5241. Hence we have the following two rules:
  5242. \begin{enumerate}
  5243. \item If instruction $I_k$ is a move instruction of the form
  5244. \key{movq} $s$\key{,} $d$, then for every $v \in
  5245. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5246. $(d,v)$.
  5247. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5248. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5249. $(d,v)$.
  5250. \end{enumerate}
  5251. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5252. these rules to each instruction. We highlight a few of the
  5253. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5254. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5255. so \code{v} interferes with \code{rsp}.}
  5256. %
  5257. \python{The first instruction is \lstinline{movq $1, v}, and the
  5258. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  5259. no interference because $\ttm{v}$ is the destination of the move.}
  5260. %
  5261. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5262. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  5263. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5264. %
  5265. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5266. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  5267. $\ttm{x}$ interferes with \ttm{w}.}
  5268. %
  5269. \racket{The next instruction is \lstinline{movq x, y}, and the
  5270. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5271. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5272. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5273. \ttm{x} and \ttm{y} hold the same value.}
  5274. %
  5275. \python{The next instruction is \lstinline{movq x, y}, and the
  5276. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5277. applies, so \ttm{y} interferes with \ttm{w} but not
  5278. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5279. \ttm{x} and \ttm{y} hold the same value.}
  5280. %
  5281. Figure~\ref{fig:interference-results} lists the interference results
  5282. for all the instructions, and the resulting interference graph is
  5283. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5284. the interference graph in figure~\ref{fig:interfere} because there
  5285. were no interference edges involving registers and we did not wish to
  5286. clutter the graph, but in general one needs to include all the
  5287. registers in the interference graph.
  5288. \begin{figure}[tbp]
  5289. \begin{tcolorbox}[colback=white]
  5290. \begin{quote}
  5291. {\if\edition\racketEd
  5292. \begin{tabular}{ll}
  5293. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5294. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5295. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5296. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5297. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5298. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5299. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5300. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5301. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5302. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5303. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5304. \lstinline!jmp conclusion!& no interference.
  5305. \end{tabular}
  5306. \fi}
  5307. {\if\edition\pythonEd\pythonColor
  5308. \begin{tabular}{ll}
  5309. \lstinline!movq $1, v!& no interference\\
  5310. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5311. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5312. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5313. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5314. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5315. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5316. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5317. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5318. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5319. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5320. \lstinline!movq tmp_1, %rdi! & no interference \\
  5321. \lstinline!callq print_int!& no interference.
  5322. \end{tabular}
  5323. \fi}
  5324. \end{quote}
  5325. \end{tcolorbox}
  5326. \caption{Interference results for the running example.}
  5327. \label{fig:interference-results}
  5328. \end{figure}
  5329. \begin{figure}[tbp]
  5330. \begin{tcolorbox}[colback=white]
  5331. \large
  5332. {\if\edition\racketEd
  5333. \[
  5334. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5335. \node (rax) at (0,0) {$\ttm{rax}$};
  5336. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5337. \node (t1) at (0,2) {$\ttm{t}$};
  5338. \node (z) at (3,2) {$\ttm{z}$};
  5339. \node (x) at (6,2) {$\ttm{x}$};
  5340. \node (y) at (3,0) {$\ttm{y}$};
  5341. \node (w) at (6,0) {$\ttm{w}$};
  5342. \node (v) at (9,0) {$\ttm{v}$};
  5343. \draw (t1) to (rax);
  5344. \draw (t1) to (z);
  5345. \draw (z) to (y);
  5346. \draw (z) to (w);
  5347. \draw (x) to (w);
  5348. \draw (y) to (w);
  5349. \draw (v) to (w);
  5350. \draw (v) to (rsp);
  5351. \draw (w) to (rsp);
  5352. \draw (x) to (rsp);
  5353. \draw (y) to (rsp);
  5354. \path[-.,bend left=15] (z) edge node {} (rsp);
  5355. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5356. \draw (rax) to (rsp);
  5357. \end{tikzpicture}
  5358. \]
  5359. \fi}
  5360. {\if\edition\pythonEd\pythonColor
  5361. \[
  5362. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5363. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5364. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5365. \node (z) at (3,2) {$\ttm{z}$};
  5366. \node (x) at (6,2) {$\ttm{x}$};
  5367. \node (y) at (3,0) {$\ttm{y}$};
  5368. \node (w) at (6,0) {$\ttm{w}$};
  5369. \node (v) at (9,0) {$\ttm{v}$};
  5370. \draw (t0) to (t1);
  5371. \draw (t0) to (z);
  5372. \draw (z) to (y);
  5373. \draw (z) to (w);
  5374. \draw (x) to (w);
  5375. \draw (y) to (w);
  5376. \draw (v) to (w);
  5377. \end{tikzpicture}
  5378. \]
  5379. \fi}
  5380. \end{tcolorbox}
  5381. \caption{The interference graph of the example program.}
  5382. \label{fig:interfere}
  5383. \end{figure}
  5384. \begin{exercise}\normalfont\normalsize
  5385. \racket{Implement the compiler pass named \code{build\_interference} according
  5386. to the algorithm suggested here. We recommend using the Racket
  5387. \code{graph} package to create and inspect the interference graph.
  5388. The output graph of this pass should be stored in the $\itm{info}$ field of
  5389. the program, under the key \code{conflicts}.}
  5390. %
  5391. \python{Implement a function named \code{build\_interference}
  5392. according to the algorithm suggested above that
  5393. returns the interference graph.}
  5394. \end{exercise}
  5395. \section{Graph Coloring via Sudoku}
  5396. \label{sec:graph-coloring}
  5397. \index{subject}{graph coloring}
  5398. \index{subject}{sudoku}
  5399. \index{subject}{color}
  5400. We come to the main event discussed in this chapter, mapping variables
  5401. to registers and stack locations. Variables that interfere with each
  5402. other must be mapped to different locations. In terms of the
  5403. interference graph, this means that adjacent vertices must be mapped
  5404. to different locations. If we think of locations as colors, the
  5405. register allocation problem becomes the graph coloring
  5406. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5407. The reader may be more familiar with the graph coloring problem than he
  5408. or she realizes; the popular game of sudoku is an instance of the
  5409. graph coloring problem. The following describes how to build a graph
  5410. out of an initial sudoku board.
  5411. \begin{itemize}
  5412. \item There is one vertex in the graph for each sudoku square.
  5413. \item There is an edge between two vertices if the corresponding squares
  5414. are in the same row, in the same column, or in the same $3\times 3$ region.
  5415. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5416. \item On the basis of the initial assignment of numbers to squares on the
  5417. sudoku board, assign the corresponding colors to the corresponding
  5418. vertices in the graph.
  5419. \end{itemize}
  5420. If you can color the remaining vertices in the graph with the nine
  5421. colors, then you have also solved the corresponding game of sudoku.
  5422. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5423. the corresponding graph with colored vertices. Here we use a
  5424. monochrome representation of colors, mapping the sudoku number 1 to
  5425. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5426. of the vertices (the colored ones) because showing edges for all the
  5427. vertices would make the graph unreadable.
  5428. \begin{figure}[tbp]
  5429. \begin{tcolorbox}[colback=white]
  5430. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5431. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5432. \end{tcolorbox}
  5433. \caption{A sudoku game board and the corresponding colored graph.}
  5434. \label{fig:sudoku-graph}
  5435. \end{figure}
  5436. Some techniques for playing sudoku correspond to heuristics used in
  5437. graph coloring algorithms. For example, one of the basic techniques
  5438. for sudoku is called Pencil Marks. The idea is to use a process of
  5439. elimination to determine what numbers are no longer available for a
  5440. square and to write those numbers in the square (writing very
  5441. small). For example, if the number $1$ is assigned to a square, then
  5442. write the pencil mark $1$ in all the squares in the same row, column,
  5443. and region to indicate that $1$ is no longer an option for those other
  5444. squares.
  5445. %
  5446. The Pencil Marks technique corresponds to the notion of
  5447. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5448. saturation of a vertex, in sudoku terms, is the set of numbers that
  5449. are no longer available. In graph terminology, we have the following
  5450. definition:
  5451. \begin{equation*}
  5452. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5453. \text{ and } \mathrm{color}(v) = c \}
  5454. \end{equation*}
  5455. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5456. edge with $u$.
  5457. The Pencil Marks technique leads to a simple strategy for filling in
  5458. numbers: if there is a square with only one possible number left, then
  5459. choose that number! But what if there are no squares with only one
  5460. possibility left? One brute-force approach is to try them all: choose
  5461. the first one, and if that ultimately leads to a solution, great. If
  5462. not, backtrack and choose the next possibility. One good thing about
  5463. Pencil Marks is that it reduces the degree of branching in the search
  5464. tree. Nevertheless, backtracking can be terribly time consuming. One
  5465. way to reduce the amount of backtracking is to use the
  5466. most-constrained-first heuristic (aka minimum remaining
  5467. values)~\citep{Russell2003}. That is, in choosing a square, always
  5468. choose one with the fewest possibilities left (the vertex with the
  5469. highest saturation). The idea is that choosing highly constrained
  5470. squares earlier rather than later is better, because later on there may
  5471. not be any possibilities left in the highly saturated squares.
  5472. However, register allocation is easier than sudoku, because the
  5473. register allocator can fall back to assigning variables to stack
  5474. locations when the registers run out. Thus, it makes sense to replace
  5475. backtracking with greedy search: make the best choice at the time and
  5476. keep going. We still wish to minimize the number of colors needed, so
  5477. we use the most-constrained-first heuristic in the greedy search.
  5478. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5479. algorithm for register allocation based on saturation and the
  5480. most-constrained-first heuristic. It is roughly equivalent to the
  5481. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5482. sudoku, the algorithm represents colors with integers. The integers
  5483. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5484. register allocation. In particular, we recommend the following
  5485. correspondence, with $k=11$.
  5486. \begin{lstlisting}
  5487. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5488. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5489. \end{lstlisting}
  5490. The integers $k$ and larger correspond to stack locations. The
  5491. registers that are not used for register allocation, such as
  5492. \code{rax}, are assigned to negative integers. In particular, we
  5493. recommend the following correspondence.
  5494. \begin{lstlisting}
  5495. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5496. \end{lstlisting}
  5497. %% One might wonder why we include registers at all in the liveness
  5498. %% analysis and interference graph. For example, we never allocate a
  5499. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5500. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5501. %% to use register for passing arguments to functions, it will be
  5502. %% necessary for those registers to appear in the interference graph
  5503. %% because those registers will also be assigned to variables, and we
  5504. %% don't want those two uses to encroach on each other. Regarding
  5505. %% registers such as \code{rax} and \code{rsp} that are not used for
  5506. %% variables, we could omit them from the interference graph but that
  5507. %% would require adding special cases to our algorithm, which would
  5508. %% complicate the logic for little gain.
  5509. \begin{figure}[btp]
  5510. \begin{tcolorbox}[colback=white]
  5511. \centering
  5512. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5513. Algorithm: DSATUR
  5514. Input: A graph |$G$|
  5515. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5516. |$W \gets \mathrm{vertices}(G)$|
  5517. while |$W \neq \emptyset$| do
  5518. pick a vertex |$u$| from |$W$| with the highest saturation,
  5519. breaking ties randomly
  5520. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5521. |$\mathrm{color}[u] \gets c$|
  5522. |$W \gets W - \{u\}$|
  5523. \end{lstlisting}
  5524. \end{tcolorbox}
  5525. \caption{The saturation-based greedy graph coloring algorithm.}
  5526. \label{fig:satur-algo}
  5527. \end{figure}
  5528. {\if\edition\racketEd
  5529. With the DSATUR algorithm in hand, let us return to the running
  5530. example and consider how to color the interference graph shown in
  5531. figure~\ref{fig:interfere}.
  5532. %
  5533. We start by assigning each register node to its own color. For
  5534. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5535. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5536. (To reduce clutter in the interference graph, we elide nodes
  5537. that do not have interference edges, such as \code{rcx}.)
  5538. The variables are not yet colored, so they are annotated with a dash. We
  5539. then update the saturation for vertices that are adjacent to a
  5540. register, obtaining the following annotated graph. For example, the
  5541. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5542. \code{rax} and \code{rsp}.
  5543. \[
  5544. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5545. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5546. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5547. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5548. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5549. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5550. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5551. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5552. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5553. \draw (t1) to (rax);
  5554. \draw (t1) to (z);
  5555. \draw (z) to (y);
  5556. \draw (z) to (w);
  5557. \draw (x) to (w);
  5558. \draw (y) to (w);
  5559. \draw (v) to (w);
  5560. \draw (v) to (rsp);
  5561. \draw (w) to (rsp);
  5562. \draw (x) to (rsp);
  5563. \draw (y) to (rsp);
  5564. \path[-.,bend left=15] (z) edge node {} (rsp);
  5565. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5566. \draw (rax) to (rsp);
  5567. \end{tikzpicture}
  5568. \]
  5569. The algorithm says to select a maximally saturated vertex. So, we pick
  5570. $\ttm{t}$ and color it with the first available integer, which is
  5571. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5572. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5573. \[
  5574. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5575. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5576. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5577. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5578. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5579. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5580. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5581. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5582. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5583. \draw (t1) to (rax);
  5584. \draw (t1) to (z);
  5585. \draw (z) to (y);
  5586. \draw (z) to (w);
  5587. \draw (x) to (w);
  5588. \draw (y) to (w);
  5589. \draw (v) to (w);
  5590. \draw (v) to (rsp);
  5591. \draw (w) to (rsp);
  5592. \draw (x) to (rsp);
  5593. \draw (y) to (rsp);
  5594. \path[-.,bend left=15] (z) edge node {} (rsp);
  5595. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5596. \draw (rax) to (rsp);
  5597. \end{tikzpicture}
  5598. \]
  5599. We repeat the process, selecting a maximally saturated vertex,
  5600. choosing \code{z}, and coloring it with the first available number, which
  5601. is $1$. We add $1$ to the saturation for the neighboring vertices
  5602. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5603. \[
  5604. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5605. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5606. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5607. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5608. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5609. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5610. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5611. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5612. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5613. \draw (t1) to (rax);
  5614. \draw (t1) to (z);
  5615. \draw (z) to (y);
  5616. \draw (z) to (w);
  5617. \draw (x) to (w);
  5618. \draw (y) to (w);
  5619. \draw (v) to (w);
  5620. \draw (v) to (rsp);
  5621. \draw (w) to (rsp);
  5622. \draw (x) to (rsp);
  5623. \draw (y) to (rsp);
  5624. \path[-.,bend left=15] (z) edge node {} (rsp);
  5625. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5626. \draw (rax) to (rsp);
  5627. \end{tikzpicture}
  5628. \]
  5629. The most saturated vertices are now \code{w} and \code{y}. We color
  5630. \code{w} with the first available color, which is $0$.
  5631. \[
  5632. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5633. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5634. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5635. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5636. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5637. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5638. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5639. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5640. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5641. \draw (t1) to (rax);
  5642. \draw (t1) to (z);
  5643. \draw (z) to (y);
  5644. \draw (z) to (w);
  5645. \draw (x) to (w);
  5646. \draw (y) to (w);
  5647. \draw (v) to (w);
  5648. \draw (v) to (rsp);
  5649. \draw (w) to (rsp);
  5650. \draw (x) to (rsp);
  5651. \draw (y) to (rsp);
  5652. \path[-.,bend left=15] (z) edge node {} (rsp);
  5653. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5654. \draw (rax) to (rsp);
  5655. \end{tikzpicture}
  5656. \]
  5657. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5658. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5659. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5660. and \code{z}, whose colors are $0$ and $1$ respectively.
  5661. \[
  5662. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5663. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5664. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5665. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5666. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5667. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5668. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5669. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5670. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5671. \draw (t1) to (rax);
  5672. \draw (t1) to (z);
  5673. \draw (z) to (y);
  5674. \draw (z) to (w);
  5675. \draw (x) to (w);
  5676. \draw (y) to (w);
  5677. \draw (v) to (w);
  5678. \draw (v) to (rsp);
  5679. \draw (w) to (rsp);
  5680. \draw (x) to (rsp);
  5681. \draw (y) to (rsp);
  5682. \path[-.,bend left=15] (z) edge node {} (rsp);
  5683. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5684. \draw (rax) to (rsp);
  5685. \end{tikzpicture}
  5686. \]
  5687. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5688. \[
  5689. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5690. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5691. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5692. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5693. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5694. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5695. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5696. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5697. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5698. \draw (t1) to (rax);
  5699. \draw (t1) to (z);
  5700. \draw (z) to (y);
  5701. \draw (z) to (w);
  5702. \draw (x) to (w);
  5703. \draw (y) to (w);
  5704. \draw (v) to (w);
  5705. \draw (v) to (rsp);
  5706. \draw (w) to (rsp);
  5707. \draw (x) to (rsp);
  5708. \draw (y) to (rsp);
  5709. \path[-.,bend left=15] (z) edge node {} (rsp);
  5710. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5711. \draw (rax) to (rsp);
  5712. \end{tikzpicture}
  5713. \]
  5714. In the last step of the algorithm, we color \code{x} with $1$.
  5715. \[
  5716. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5717. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5718. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5719. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5720. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5721. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5722. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5723. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5724. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5725. \draw (t1) to (rax);
  5726. \draw (t1) to (z);
  5727. \draw (z) to (y);
  5728. \draw (z) to (w);
  5729. \draw (x) to (w);
  5730. \draw (y) to (w);
  5731. \draw (v) to (w);
  5732. \draw (v) to (rsp);
  5733. \draw (w) to (rsp);
  5734. \draw (x) to (rsp);
  5735. \draw (y) to (rsp);
  5736. \path[-.,bend left=15] (z) edge node {} (rsp);
  5737. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5738. \draw (rax) to (rsp);
  5739. \end{tikzpicture}
  5740. \]
  5741. So, we obtain the following coloring:
  5742. \[
  5743. \{
  5744. \ttm{rax} \mapsto -1,
  5745. \ttm{rsp} \mapsto -2,
  5746. \ttm{t} \mapsto 0,
  5747. \ttm{z} \mapsto 1,
  5748. \ttm{x} \mapsto 1,
  5749. \ttm{y} \mapsto 2,
  5750. \ttm{w} \mapsto 0,
  5751. \ttm{v} \mapsto 1
  5752. \}
  5753. \]
  5754. \fi}
  5755. %
  5756. {\if\edition\pythonEd\pythonColor
  5757. %
  5758. With the DSATUR algorithm in hand, let us return to the running
  5759. example and consider how to color the interference graph in
  5760. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5761. to indicate that it has not yet been assigned a color. Each register
  5762. node (not shown) should be assigned the number that the register
  5763. corresponds to, for example, color \code{rcx} with the number \code{0}
  5764. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5765. each node; all of them start as the empty set. We do not show the
  5766. register nodes in the graph below because there were no interference
  5767. edges involving registers in this program, but in general there can
  5768. be.
  5769. %
  5770. \[
  5771. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5772. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5773. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5774. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5775. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5776. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5777. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5778. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5779. \draw (t0) to (t1);
  5780. \draw (t0) to (z);
  5781. \draw (z) to (y);
  5782. \draw (z) to (w);
  5783. \draw (x) to (w);
  5784. \draw (y) to (w);
  5785. \draw (v) to (w);
  5786. \end{tikzpicture}
  5787. \]
  5788. The algorithm says to select a maximally saturated vertex, but they
  5789. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5790. then color it with the first available integer, which is $0$. We mark
  5791. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5792. they interfere with $\ttm{tmp\_0}$.
  5793. \[
  5794. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5795. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5796. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5797. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5798. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5799. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5800. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5801. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5802. \draw (t0) to (t1);
  5803. \draw (t0) to (z);
  5804. \draw (z) to (y);
  5805. \draw (z) to (w);
  5806. \draw (x) to (w);
  5807. \draw (y) to (w);
  5808. \draw (v) to (w);
  5809. \end{tikzpicture}
  5810. \]
  5811. We repeat the process. The most saturated vertices are \code{z} and
  5812. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5813. available number, which is $1$. We add $1$ to the saturation for the
  5814. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5815. \[
  5816. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5817. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5818. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5819. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5820. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5821. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5822. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  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 most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5834. \code{y}. We color \code{w} with the first available color, which
  5835. is $0$.
  5836. \[
  5837. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5838. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5839. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5840. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5841. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5842. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5843. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5844. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5845. \draw (t0) to (t1);
  5846. \draw (t0) to (z);
  5847. \draw (z) to (y);
  5848. \draw (z) to (w);
  5849. \draw (x) to (w);
  5850. \draw (y) to (w);
  5851. \draw (v) to (w);
  5852. \end{tikzpicture}
  5853. \]
  5854. Now \code{y} is the most saturated, so we color it with $2$.
  5855. \[
  5856. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5857. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5858. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5859. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5860. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5861. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5862. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5863. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5864. \draw (t0) to (t1);
  5865. \draw (t0) to (z);
  5866. \draw (z) to (y);
  5867. \draw (z) to (w);
  5868. \draw (x) to (w);
  5869. \draw (y) to (w);
  5870. \draw (v) to (w);
  5871. \end{tikzpicture}
  5872. \]
  5873. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5874. We choose to color \code{v} with $1$.
  5875. \[
  5876. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5877. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5878. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5879. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5880. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5881. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5882. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5883. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5884. \draw (t0) to (t1);
  5885. \draw (t0) to (z);
  5886. \draw (z) to (y);
  5887. \draw (z) to (w);
  5888. \draw (x) to (w);
  5889. \draw (y) to (w);
  5890. \draw (v) to (w);
  5891. \end{tikzpicture}
  5892. \]
  5893. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5894. \[
  5895. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5896. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5897. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5898. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5899. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5900. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5901. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5902. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5903. \draw (t0) to (t1);
  5904. \draw (t0) to (z);
  5905. \draw (z) to (y);
  5906. \draw (z) to (w);
  5907. \draw (x) to (w);
  5908. \draw (y) to (w);
  5909. \draw (v) to (w);
  5910. \end{tikzpicture}
  5911. \]
  5912. So, we obtain the following coloring:
  5913. \[
  5914. \{ \ttm{tmp\_0} \mapsto 0,
  5915. \ttm{tmp\_1} \mapsto 1,
  5916. \ttm{z} \mapsto 1,
  5917. \ttm{x} \mapsto 1,
  5918. \ttm{y} \mapsto 2,
  5919. \ttm{w} \mapsto 0,
  5920. \ttm{v} \mapsto 1 \}
  5921. \]
  5922. \fi}
  5923. We recommend creating an auxiliary function named \code{color\_graph}
  5924. that takes an interference graph and a list of all the variables in
  5925. the program. This function should return a mapping of variables to
  5926. their colors (represented as natural numbers). By creating this helper
  5927. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5928. when we add support for functions.
  5929. To prioritize the processing of highly saturated nodes inside the
  5930. \code{color\_graph} function, we recommend using the priority queue
  5931. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5932. addition, you will need to maintain a mapping from variables to their
  5933. handles in the priority queue so that you can notify the priority
  5934. queue when their saturation changes.}
  5935. {\if\edition\racketEd
  5936. \begin{figure}[tp]
  5937. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5938. \small
  5939. \begin{tcolorbox}[title=Priority Queue]
  5940. A \emph{priority queue}\index{subject}{priority queue}
  5941. is a collection of items in which the
  5942. removal of items is governed by priority. In a \emph{min} queue,
  5943. lower priority items are removed first. An implementation is in
  5944. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  5945. \begin{description}
  5946. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5947. priority queue that uses the $\itm{cmp}$ predicate to determine
  5948. whether its first argument has lower or equal priority to its
  5949. second argument.
  5950. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5951. items in the queue.
  5952. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5953. the item into the queue and returns a handle for the item in the
  5954. queue.
  5955. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5956. the lowest priority.
  5957. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5958. notifies the queue that the priority has decreased for the item
  5959. associated with the given handle.
  5960. \end{description}
  5961. \end{tcolorbox}
  5962. %\end{wrapfigure}
  5963. \caption{The priority queue data structure.}
  5964. \label{fig:priority-queue}
  5965. \end{figure}
  5966. \fi}
  5967. With the coloring complete, we finalize the assignment of variables to
  5968. registers and stack locations. We map the first $k$ colors to the $k$
  5969. registers and the rest of the colors to stack locations. Suppose for
  5970. the moment that we have just one register to use for register
  5971. allocation, \key{rcx}. Then we have the following map from colors to
  5972. locations.
  5973. \[
  5974. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5975. \]
  5976. Composing this mapping with the coloring, we arrive at the following
  5977. assignment of variables to locations.
  5978. {\if\edition\racketEd
  5979. \begin{gather*}
  5980. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5981. \ttm{w} \mapsto \key{\%rcx}, \,
  5982. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5983. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5984. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5985. \ttm{t} \mapsto \key{\%rcx} \}
  5986. \end{gather*}
  5987. \fi}
  5988. {\if\edition\pythonEd\pythonColor
  5989. \begin{gather*}
  5990. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5991. \ttm{w} \mapsto \key{\%rcx}, \,
  5992. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5993. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5994. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5995. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5996. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5997. \end{gather*}
  5998. \fi}
  5999. Adapt the code from the \code{assign\_homes} pass
  6000. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6001. assigned location. Applying this assignment to our running
  6002. example shown next, on the left, yields the program on the right.
  6003. % why frame size of 32? -JGS
  6004. \begin{center}
  6005. {\if\edition\racketEd
  6006. \begin{minipage}{0.35\textwidth}
  6007. \begin{lstlisting}
  6008. movq $1, v
  6009. movq $42, w
  6010. movq v, x
  6011. addq $7, x
  6012. movq x, y
  6013. movq x, z
  6014. addq w, z
  6015. movq y, t
  6016. negq t
  6017. movq z, %rax
  6018. addq t, %rax
  6019. jmp conclusion
  6020. \end{lstlisting}
  6021. \end{minipage}
  6022. $\Rightarrow\qquad$
  6023. \begin{minipage}{0.45\textwidth}
  6024. \begin{lstlisting}
  6025. movq $1, -8(%rbp)
  6026. movq $42, %rcx
  6027. movq -8(%rbp), -8(%rbp)
  6028. addq $7, -8(%rbp)
  6029. movq -8(%rbp), -16(%rbp)
  6030. movq -8(%rbp), -8(%rbp)
  6031. addq %rcx, -8(%rbp)
  6032. movq -16(%rbp), %rcx
  6033. negq %rcx
  6034. movq -8(%rbp), %rax
  6035. addq %rcx, %rax
  6036. jmp conclusion
  6037. \end{lstlisting}
  6038. \end{minipage}
  6039. \fi}
  6040. {\if\edition\pythonEd\pythonColor
  6041. \begin{minipage}{0.35\textwidth}
  6042. \begin{lstlisting}
  6043. movq $1, v
  6044. movq $42, w
  6045. movq v, x
  6046. addq $7, x
  6047. movq x, y
  6048. movq x, z
  6049. addq w, z
  6050. movq y, tmp_0
  6051. negq tmp_0
  6052. movq z, tmp_1
  6053. addq tmp_0, tmp_1
  6054. movq tmp_1, %rdi
  6055. callq print_int
  6056. \end{lstlisting}
  6057. \end{minipage}
  6058. $\Rightarrow\qquad$
  6059. \begin{minipage}{0.45\textwidth}
  6060. \begin{lstlisting}
  6061. movq $1, -8(%rbp)
  6062. movq $42, %rcx
  6063. movq -8(%rbp), -8(%rbp)
  6064. addq $7, -8(%rbp)
  6065. movq -8(%rbp), -16(%rbp)
  6066. movq -8(%rbp), -8(%rbp)
  6067. addq %rcx, -8(%rbp)
  6068. movq -16(%rbp), %rcx
  6069. negq %rcx
  6070. movq -8(%rbp), -8(%rbp)
  6071. addq %rcx, -8(%rbp)
  6072. movq -8(%rbp), %rdi
  6073. callq print_int
  6074. \end{lstlisting}
  6075. \end{minipage}
  6076. \fi}
  6077. \end{center}
  6078. \begin{exercise}\normalfont\normalsize
  6079. Implement the \code{allocate\_registers} pass.
  6080. Create five programs that exercise all aspects of the register
  6081. allocation algorithm, including spilling variables to the stack.
  6082. %
  6083. {\if\edition\racketEd
  6084. Replace \code{assign\_homes} in the list of \code{passes} in the
  6085. \code{run-tests.rkt} script with the three new passes:
  6086. \code{uncover\_live}, \code{build\_interference}, and
  6087. \code{allocate\_registers}.
  6088. Temporarily remove the call to \code{compiler-tests}.
  6089. Run the script to test the register allocator.
  6090. \fi}
  6091. %
  6092. {\if\edition\pythonEd\pythonColor
  6093. Run the \code{run-tests.py} script to to check whether the
  6094. output programs produce the same result as the input programs.
  6095. \fi}
  6096. \end{exercise}
  6097. \section{Patch Instructions}
  6098. \label{sec:patch-instructions}
  6099. The remaining step in the compilation to x86 is to ensure that the
  6100. instructions have at most one argument that is a memory access.
  6101. %
  6102. In the running example, the instruction \code{movq -8(\%rbp),
  6103. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6104. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6105. then move \code{rax} into \code{-16(\%rbp)}.
  6106. %
  6107. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6108. problematic, but they can simply be deleted. In general, we recommend
  6109. deleting all the trivial moves whose source and destination are the
  6110. same location.
  6111. %
  6112. The following is the output of \code{patch\_instructions} on the
  6113. running example.
  6114. \begin{center}
  6115. {\if\edition\racketEd
  6116. \begin{minipage}{0.35\textwidth}
  6117. \begin{lstlisting}
  6118. movq $1, -8(%rbp)
  6119. movq $42, %rcx
  6120. movq -8(%rbp), -8(%rbp)
  6121. addq $7, -8(%rbp)
  6122. movq -8(%rbp), -16(%rbp)
  6123. movq -8(%rbp), -8(%rbp)
  6124. addq %rcx, -8(%rbp)
  6125. movq -16(%rbp), %rcx
  6126. negq %rcx
  6127. movq -8(%rbp), %rax
  6128. addq %rcx, %rax
  6129. jmp conclusion
  6130. \end{lstlisting}
  6131. \end{minipage}
  6132. $\Rightarrow\qquad$
  6133. \begin{minipage}{0.45\textwidth}
  6134. \begin{lstlisting}
  6135. movq $1, -8(%rbp)
  6136. movq $42, %rcx
  6137. addq $7, -8(%rbp)
  6138. movq -8(%rbp), %rax
  6139. movq %rax, -16(%rbp)
  6140. addq %rcx, -8(%rbp)
  6141. movq -16(%rbp), %rcx
  6142. negq %rcx
  6143. movq -8(%rbp), %rax
  6144. addq %rcx, %rax
  6145. jmp conclusion
  6146. \end{lstlisting}
  6147. \end{minipage}
  6148. \fi}
  6149. {\if\edition\pythonEd\pythonColor
  6150. \begin{minipage}{0.35\textwidth}
  6151. \begin{lstlisting}
  6152. movq $1, -8(%rbp)
  6153. movq $42, %rcx
  6154. movq -8(%rbp), -8(%rbp)
  6155. addq $7, -8(%rbp)
  6156. movq -8(%rbp), -16(%rbp)
  6157. movq -8(%rbp), -8(%rbp)
  6158. addq %rcx, -8(%rbp)
  6159. movq -16(%rbp), %rcx
  6160. negq %rcx
  6161. movq -8(%rbp), -8(%rbp)
  6162. addq %rcx, -8(%rbp)
  6163. movq -8(%rbp), %rdi
  6164. callq print_int
  6165. \end{lstlisting}
  6166. \end{minipage}
  6167. $\Rightarrow\qquad$
  6168. \begin{minipage}{0.45\textwidth}
  6169. \begin{lstlisting}
  6170. movq $1, -8(%rbp)
  6171. movq $42, %rcx
  6172. addq $7, -8(%rbp)
  6173. movq -8(%rbp), %rax
  6174. movq %rax, -16(%rbp)
  6175. addq %rcx, -8(%rbp)
  6176. movq -16(%rbp), %rcx
  6177. negq %rcx
  6178. addq %rcx, -8(%rbp)
  6179. movq -8(%rbp), %rdi
  6180. callq print_int
  6181. \end{lstlisting}
  6182. \end{minipage}
  6183. \fi}
  6184. \end{center}
  6185. \begin{exercise}\normalfont\normalsize
  6186. %
  6187. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6188. %
  6189. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6190. %in the \code{run-tests.rkt} script.
  6191. %
  6192. Run the script to test the \code{patch\_instructions} pass.
  6193. \end{exercise}
  6194. \section{Prelude and Conclusion}
  6195. \label{sec:print-x86-reg-alloc}
  6196. \index{subject}{calling conventions}
  6197. \index{subject}{prelude}\index{subject}{conclusion}
  6198. Recall that this pass generates the prelude and conclusion
  6199. instructions to satisfy the x86 calling conventions
  6200. (section~\ref{sec:calling-conventions}). With the addition of the
  6201. register allocator, the callee-saved registers used by the register
  6202. allocator must be saved in the prelude and restored in the conclusion.
  6203. In the \code{allocate\_registers} pass,
  6204. %
  6205. \racket{add an entry to the \itm{info}
  6206. of \code{X86Program} named \code{used\_callee}}
  6207. %
  6208. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6209. %
  6210. that stores the set of callee-saved registers that were assigned to
  6211. variables. The \code{prelude\_and\_conclusion} pass can then access
  6212. this information to decide which callee-saved registers need to be
  6213. saved and restored.
  6214. %
  6215. When calculating the amount to adjust the \code{rsp} in the prelude,
  6216. make sure to take into account the space used for saving the
  6217. callee-saved registers. Also, remember that the frame needs to be a
  6218. multiple of 16 bytes! We recommend using the following equation for
  6219. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6220. of stack locations used by spilled variables\footnote{Sometimes two or
  6221. more spilled variables are assigned to the same stack location, so
  6222. $S$ can be less than the number of spilled variables.} and $C$ be
  6223. the number of callee-saved registers that were
  6224. allocated\index{subject}{allocate} to
  6225. variables. The $\itm{align}$ function rounds a number up to the
  6226. nearest 16 bytes.
  6227. \[
  6228. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6229. \]
  6230. The reason we subtract $8\itm{C}$ in this equation is that the
  6231. prelude uses \code{pushq} to save each of the callee-saved registers,
  6232. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6233. \racket{An overview of all the passes involved in register
  6234. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6235. {\if\edition\racketEd
  6236. \begin{figure}[tbp]
  6237. \begin{tcolorbox}[colback=white]
  6238. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6239. \node (Lvar) at (0,2) {\large \LangVar{}};
  6240. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6241. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6242. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6243. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6244. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6245. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6246. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6247. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6248. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6249. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6250. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6251. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6252. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6253. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6254. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6255. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6256. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6257. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6258. \end{tikzpicture}
  6259. \end{tcolorbox}
  6260. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6261. \label{fig:reg-alloc-passes}
  6262. \end{figure}
  6263. \fi}
  6264. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6265. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6266. use of registers and the stack, we limit the register allocator for
  6267. this example to use just two registers: \code{rcx} (color $0$) and
  6268. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6269. \code{main} function, we push \code{rbx} onto the stack because it is
  6270. a callee-saved register and it was assigned to a variable by the
  6271. register allocator. We subtract \code{8} from the \code{rsp} at the
  6272. end of the prelude to reserve space for the one spilled variable.
  6273. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6274. Moving on to the program proper, we see how the registers were
  6275. allocated.
  6276. %
  6277. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6278. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6279. %
  6280. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6281. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  6282. were assigned to \code{rbx}.}
  6283. %
  6284. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6285. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6286. callee-save register \code{rbx} onto the stack. The spilled variables
  6287. must be placed lower on the stack than the saved callee-save
  6288. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6289. \code{-16(\%rbp)}.
  6290. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6291. done in the prelude. We move the stack pointer up by \code{8} bytes
  6292. (the room for spilled variables), then pop the old values of
  6293. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6294. \code{retq} to return control to the operating system.
  6295. \begin{figure}[tbp]
  6296. \begin{minipage}{0.55\textwidth}
  6297. \begin{tcolorbox}[colback=white]
  6298. % var_test_28.rkt
  6299. % (use-minimal-set-of-registers! #t)
  6300. % 0 -> rcx
  6301. % 1 -> rbx
  6302. %
  6303. % t 0 rcx
  6304. % z 1 rbx
  6305. % w 0 rcx
  6306. % y 2 rbp -16
  6307. % v 1 rbx
  6308. % x 1 rbx
  6309. {\if\edition\racketEd
  6310. \begin{lstlisting}
  6311. start:
  6312. movq $1, %rbx
  6313. movq $42, %rcx
  6314. addq $7, %rbx
  6315. movq %rbx, -16(%rbp)
  6316. addq %rcx, %rbx
  6317. movq -16(%rbp), %rcx
  6318. negq %rcx
  6319. movq %rbx, %rax
  6320. addq %rcx, %rax
  6321. jmp conclusion
  6322. .globl main
  6323. main:
  6324. pushq %rbp
  6325. movq %rsp, %rbp
  6326. pushq %rbx
  6327. subq $8, %rsp
  6328. jmp start
  6329. conclusion:
  6330. addq $8, %rsp
  6331. popq %rbx
  6332. popq %rbp
  6333. retq
  6334. \end{lstlisting}
  6335. \fi}
  6336. {\if\edition\pythonEd\pythonColor
  6337. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6338. \begin{lstlisting}
  6339. .globl main
  6340. main:
  6341. pushq %rbp
  6342. movq %rsp, %rbp
  6343. pushq %rbx
  6344. subq $8, %rsp
  6345. movq $1, %rcx
  6346. movq $42, %rbx
  6347. addq $7, %rcx
  6348. movq %rcx, -16(%rbp)
  6349. addq %rbx, -16(%rbp)
  6350. negq %rcx
  6351. movq -16(%rbp), %rbx
  6352. addq %rcx, %rbx
  6353. movq %rbx, %rdi
  6354. callq print_int
  6355. addq $8, %rsp
  6356. popq %rbx
  6357. popq %rbp
  6358. retq
  6359. \end{lstlisting}
  6360. \fi}
  6361. \end{tcolorbox}
  6362. \end{minipage}
  6363. \caption{The x86 output from the running example
  6364. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6365. and \code{rcx}.}
  6366. \label{fig:running-example-x86}
  6367. \end{figure}
  6368. \begin{exercise}\normalfont\normalsize
  6369. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6370. %
  6371. \racket{
  6372. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6373. list of passes and the call to \code{compiler-tests}.}
  6374. %
  6375. Run the script to test the complete compiler for \LangVar{} that
  6376. performs register allocation.
  6377. \end{exercise}
  6378. \section{Challenge: Move Biasing}
  6379. \label{sec:move-biasing}
  6380. \index{subject}{move biasing}
  6381. This section describes an enhancement to the register allocator,
  6382. called move biasing, for students who are looking for an extra
  6383. challenge.
  6384. {\if\edition\racketEd
  6385. To motivate the need for move biasing we return to the running example,
  6386. but this time we use all the general purpose registers. So, we have
  6387. the following mapping of color numbers to registers.
  6388. \[
  6389. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6390. \]
  6391. Using the same assignment of variables to color numbers that was
  6392. produced by the register allocator described in the last section, we
  6393. get the following program.
  6394. \begin{center}
  6395. \begin{minipage}{0.35\textwidth}
  6396. \begin{lstlisting}
  6397. movq $1, v
  6398. movq $42, w
  6399. movq v, x
  6400. addq $7, x
  6401. movq x, y
  6402. movq x, z
  6403. addq w, z
  6404. movq y, t
  6405. negq t
  6406. movq z, %rax
  6407. addq t, %rax
  6408. jmp conclusion
  6409. \end{lstlisting}
  6410. \end{minipage}
  6411. $\Rightarrow\qquad$
  6412. \begin{minipage}{0.45\textwidth}
  6413. \begin{lstlisting}
  6414. movq $1, %rdx
  6415. movq $42, %rcx
  6416. movq %rdx, %rdx
  6417. addq $7, %rdx
  6418. movq %rdx, %rsi
  6419. movq %rdx, %rdx
  6420. addq %rcx, %rdx
  6421. movq %rsi, %rcx
  6422. negq %rcx
  6423. movq %rdx, %rax
  6424. addq %rcx, %rax
  6425. jmp conclusion
  6426. \end{lstlisting}
  6427. \end{minipage}
  6428. \end{center}
  6429. In this output code there are two \key{movq} instructions that
  6430. can be removed because their source and target are the same. However,
  6431. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6432. register, we could instead remove three \key{movq} instructions. We
  6433. can accomplish this by taking into account which variables appear in
  6434. \key{movq} instructions with which other variables.
  6435. \fi}
  6436. {\if\edition\pythonEd\pythonColor
  6437. %
  6438. To motivate the need for move biasing we return to the running example
  6439. and recall that in section~\ref{sec:patch-instructions} we were able to
  6440. remove three trivial move instructions from the running
  6441. example. However, we could remove another trivial move if we were able
  6442. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6443. We say that two variables $p$ and $q$ are \emph{move
  6444. related}\index{subject}{move related} if they participate together in
  6445. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6446. \key{movq} $q$\key{,} $p$.
  6447. %
  6448. Recall that we color variables that are more saturated before coloring
  6449. variables that are less saturated, and in the case of equally
  6450. saturated variables, we choose randomly. Now we break such ties by
  6451. giving preference to variables that have an available color that is
  6452. the same as the color of a move-related variable.
  6453. %
  6454. Furthermore, when the register allocator chooses a color for a
  6455. variable, it should prefer a color that has already been used for a
  6456. move-related variable if one exists (and assuming that they do not
  6457. interfere). This preference should not override the preference for
  6458. registers over stack locations. So, this preference should be used as
  6459. a tie breaker in choosing between two registers or in choosing between
  6460. two stack locations.
  6461. We recommend representing the move relationships in a graph, similarly
  6462. to how we represented interference. The following is the \emph{move
  6463. graph} for our running example.
  6464. {\if\edition\racketEd
  6465. \[
  6466. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6467. \node (rax) at (0,0) {$\ttm{rax}$};
  6468. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6469. \node (t) at (0,2) {$\ttm{t}$};
  6470. \node (z) at (3,2) {$\ttm{z}$};
  6471. \node (x) at (6,2) {$\ttm{x}$};
  6472. \node (y) at (3,0) {$\ttm{y}$};
  6473. \node (w) at (6,0) {$\ttm{w}$};
  6474. \node (v) at (9,0) {$\ttm{v}$};
  6475. \draw (v) to (x);
  6476. \draw (x) to (y);
  6477. \draw (x) to (z);
  6478. \draw (y) to (t);
  6479. \end{tikzpicture}
  6480. \]
  6481. \fi}
  6482. %
  6483. {\if\edition\pythonEd\pythonColor
  6484. \[
  6485. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6486. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6487. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6488. \node (z) at (3,2) {$\ttm{z}$};
  6489. \node (x) at (6,2) {$\ttm{x}$};
  6490. \node (y) at (3,0) {$\ttm{y}$};
  6491. \node (w) at (6,0) {$\ttm{w}$};
  6492. \node (v) at (9,0) {$\ttm{v}$};
  6493. \draw (y) to (t0);
  6494. \draw (z) to (x);
  6495. \draw (z) to (t1);
  6496. \draw (x) to (y);
  6497. \draw (x) to (v);
  6498. \end{tikzpicture}
  6499. \]
  6500. \fi}
  6501. {\if\edition\racketEd
  6502. Now we replay the graph coloring, pausing to see the coloring of
  6503. \code{y}. Recall the following configuration. The most saturated vertices
  6504. were \code{w} and \code{y}.
  6505. \[
  6506. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6507. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6508. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6509. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6510. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6511. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6512. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6513. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6514. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6515. \draw (t1) to (rax);
  6516. \draw (t1) to (z);
  6517. \draw (z) to (y);
  6518. \draw (z) to (w);
  6519. \draw (x) to (w);
  6520. \draw (y) to (w);
  6521. \draw (v) to (w);
  6522. \draw (v) to (rsp);
  6523. \draw (w) to (rsp);
  6524. \draw (x) to (rsp);
  6525. \draw (y) to (rsp);
  6526. \path[-.,bend left=15] (z) edge node {} (rsp);
  6527. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6528. \draw (rax) to (rsp);
  6529. \end{tikzpicture}
  6530. \]
  6531. %
  6532. The last time, we chose to color \code{w} with $0$. This time, we see
  6533. that \code{w} is not move-related to any vertex, but \code{y} is
  6534. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6535. the same color as \code{t}.
  6536. \[
  6537. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6538. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6539. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6540. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6541. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6542. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6543. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6544. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6545. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6546. \draw (t1) to (rax);
  6547. \draw (t1) to (z);
  6548. \draw (z) to (y);
  6549. \draw (z) to (w);
  6550. \draw (x) to (w);
  6551. \draw (y) to (w);
  6552. \draw (v) to (w);
  6553. \draw (v) to (rsp);
  6554. \draw (w) to (rsp);
  6555. \draw (x) to (rsp);
  6556. \draw (y) to (rsp);
  6557. \path[-.,bend left=15] (z) edge node {} (rsp);
  6558. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6559. \draw (rax) to (rsp);
  6560. \end{tikzpicture}
  6561. \]
  6562. Now \code{w} is the most saturated, so we color it $2$.
  6563. \[
  6564. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6565. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6566. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6567. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6568. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6569. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6570. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6571. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6572. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6573. \draw (t1) to (rax);
  6574. \draw (t1) to (z);
  6575. \draw (z) to (y);
  6576. \draw (z) to (w);
  6577. \draw (x) to (w);
  6578. \draw (y) to (w);
  6579. \draw (v) to (w);
  6580. \draw (v) to (rsp);
  6581. \draw (w) to (rsp);
  6582. \draw (x) to (rsp);
  6583. \draw (y) to (rsp);
  6584. \path[-.,bend left=15] (z) edge node {} (rsp);
  6585. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6586. \draw (rax) to (rsp);
  6587. \end{tikzpicture}
  6588. \]
  6589. At this point, vertices \code{x} and \code{v} are most saturated, but
  6590. \code{x} is move related to \code{y} and \code{z}, so we color
  6591. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6592. \[
  6593. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6594. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6595. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6596. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6597. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6598. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6599. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6600. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6601. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6602. \draw (t1) to (rax);
  6603. \draw (t) to (z);
  6604. \draw (z) to (y);
  6605. \draw (z) to (w);
  6606. \draw (x) to (w);
  6607. \draw (y) to (w);
  6608. \draw (v) to (w);
  6609. \draw (v) to (rsp);
  6610. \draw (w) to (rsp);
  6611. \draw (x) to (rsp);
  6612. \draw (y) to (rsp);
  6613. \path[-.,bend left=15] (z) edge node {} (rsp);
  6614. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6615. \draw (rax) to (rsp);
  6616. \end{tikzpicture}
  6617. \]
  6618. \fi}
  6619. %
  6620. {\if\edition\pythonEd\pythonColor
  6621. Now we replay the graph coloring, pausing before the coloring of
  6622. \code{w}. Recall the following configuration. The most saturated vertices
  6623. were \code{tmp\_1}, \code{w}, and \code{y}.
  6624. \[
  6625. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6626. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6627. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6628. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6629. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6630. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6631. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6632. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6633. \draw (t0) to (t1);
  6634. \draw (t0) to (z);
  6635. \draw (z) to (y);
  6636. \draw (z) to (w);
  6637. \draw (x) to (w);
  6638. \draw (y) to (w);
  6639. \draw (v) to (w);
  6640. \end{tikzpicture}
  6641. \]
  6642. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6643. or \code{y}, but note that \code{w} is not move related to any
  6644. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6645. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6646. \code{y} and color it $0$, we can delete another move instruction.
  6647. \[
  6648. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6649. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6650. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6651. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6652. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6653. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6654. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6655. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6656. \draw (t0) to (t1);
  6657. \draw (t0) to (z);
  6658. \draw (z) to (y);
  6659. \draw (z) to (w);
  6660. \draw (x) to (w);
  6661. \draw (y) to (w);
  6662. \draw (v) to (w);
  6663. \end{tikzpicture}
  6664. \]
  6665. Now \code{w} is the most saturated, so we color it $2$.
  6666. \[
  6667. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6668. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6669. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6670. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6671. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6672. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6673. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6674. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6675. \draw (t0) to (t1);
  6676. \draw (t0) to (z);
  6677. \draw (z) to (y);
  6678. \draw (z) to (w);
  6679. \draw (x) to (w);
  6680. \draw (y) to (w);
  6681. \draw (v) to (w);
  6682. \end{tikzpicture}
  6683. \]
  6684. To finish the coloring, \code{x} and \code{v} get $0$ and
  6685. \code{tmp\_1} gets $1$.
  6686. \[
  6687. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6688. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6689. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6690. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6691. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6692. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6693. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6694. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6695. \draw (t0) to (t1);
  6696. \draw (t0) to (z);
  6697. \draw (z) to (y);
  6698. \draw (z) to (w);
  6699. \draw (x) to (w);
  6700. \draw (y) to (w);
  6701. \draw (v) to (w);
  6702. \end{tikzpicture}
  6703. \]
  6704. \fi}
  6705. So, we have the following assignment of variables to registers.
  6706. {\if\edition\racketEd
  6707. \begin{gather*}
  6708. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6709. \ttm{w} \mapsto \key{\%rsi}, \,
  6710. \ttm{x} \mapsto \key{\%rcx}, \,
  6711. \ttm{y} \mapsto \key{\%rcx}, \,
  6712. \ttm{z} \mapsto \key{\%rdx}, \,
  6713. \ttm{t} \mapsto \key{\%rcx} \}
  6714. \end{gather*}
  6715. \fi}
  6716. {\if\edition\pythonEd\pythonColor
  6717. \begin{gather*}
  6718. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6719. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6720. \ttm{x} \mapsto \key{\%rcx}, \,
  6721. \ttm{y} \mapsto \key{\%rcx}, \\
  6722. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6723. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6724. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6725. \end{gather*}
  6726. \fi}
  6727. %
  6728. We apply this register assignment to the running example shown next,
  6729. on the left, to obtain the code in the middle. The
  6730. \code{patch\_instructions} then deletes the trivial moves to obtain
  6731. the code on the right.
  6732. {\if\edition\racketEd
  6733. \begin{center}
  6734. \begin{minipage}{0.2\textwidth}
  6735. \begin{lstlisting}
  6736. movq $1, v
  6737. movq $42, w
  6738. movq v, x
  6739. addq $7, x
  6740. movq x, y
  6741. movq x, z
  6742. addq w, z
  6743. movq y, t
  6744. negq t
  6745. movq z, %rax
  6746. addq t, %rax
  6747. jmp conclusion
  6748. \end{lstlisting}
  6749. \end{minipage}
  6750. $\Rightarrow\qquad$
  6751. \begin{minipage}{0.25\textwidth}
  6752. \begin{lstlisting}
  6753. movq $1, %rcx
  6754. movq $42, %rsi
  6755. movq %rcx, %rcx
  6756. addq $7, %rcx
  6757. movq %rcx, %rcx
  6758. movq %rcx, %rdx
  6759. addq %rsi, %rdx
  6760. movq %rcx, %rcx
  6761. negq %rcx
  6762. movq %rdx, %rax
  6763. addq %rcx, %rax
  6764. jmp conclusion
  6765. \end{lstlisting}
  6766. \end{minipage}
  6767. $\Rightarrow\qquad$
  6768. \begin{minipage}{0.23\textwidth}
  6769. \begin{lstlisting}
  6770. movq $1, %rcx
  6771. movq $42, %rsi
  6772. addq $7, %rcx
  6773. movq %rcx, %rdx
  6774. addq %rsi, %rdx
  6775. negq %rcx
  6776. movq %rdx, %rax
  6777. addq %rcx, %rax
  6778. jmp conclusion
  6779. \end{lstlisting}
  6780. \end{minipage}
  6781. \end{center}
  6782. \fi}
  6783. {\if\edition\pythonEd\pythonColor
  6784. \begin{center}
  6785. \begin{minipage}{0.20\textwidth}
  6786. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6787. movq $1, v
  6788. movq $42, w
  6789. movq v, x
  6790. addq $7, x
  6791. movq x, y
  6792. movq x, z
  6793. addq w, z
  6794. movq y, tmp_0
  6795. negq tmp_0
  6796. movq z, tmp_1
  6797. addq tmp_0, tmp_1
  6798. movq tmp_1, %rdi
  6799. callq _print_int
  6800. \end{lstlisting}
  6801. \end{minipage}
  6802. ${\Rightarrow\qquad}$
  6803. \begin{minipage}{0.35\textwidth}
  6804. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6805. movq $1, %rcx
  6806. movq $42, -16(%rbp)
  6807. movq %rcx, %rcx
  6808. addq $7, %rcx
  6809. movq %rcx, %rcx
  6810. movq %rcx, -8(%rbp)
  6811. addq -16(%rbp), -8(%rbp)
  6812. movq %rcx, %rcx
  6813. negq %rcx
  6814. movq -8(%rbp), -8(%rbp)
  6815. addq %rcx, -8(%rbp)
  6816. movq -8(%rbp), %rdi
  6817. callq _print_int
  6818. \end{lstlisting}
  6819. \end{minipage}
  6820. ${\Rightarrow\qquad}$
  6821. \begin{minipage}{0.20\textwidth}
  6822. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6823. movq $1, %rcx
  6824. movq $42, -16(%rbp)
  6825. addq $7, %rcx
  6826. movq %rcx, -8(%rbp)
  6827. movq -16(%rbp), %rax
  6828. addq %rax, -8(%rbp)
  6829. negq %rcx
  6830. addq %rcx, -8(%rbp)
  6831. movq -8(%rbp), %rdi
  6832. callq print_int
  6833. \end{lstlisting}
  6834. \end{minipage}
  6835. \end{center}
  6836. \fi}
  6837. \begin{exercise}\normalfont\normalsize
  6838. Change your implementation of \code{allocate\_registers} to take move
  6839. biasing into account. Create two new tests that include at least one
  6840. opportunity for move biasing, and visually inspect the output x86
  6841. programs to make sure that your move biasing is working properly. Make
  6842. sure that your compiler still passes all the tests.
  6843. \end{exercise}
  6844. %To do: another neat challenge would be to do
  6845. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6846. %% \subsection{Output of the Running Example}
  6847. %% \label{sec:reg-alloc-output}
  6848. % challenge: prioritize variables based on execution frequencies
  6849. % and the number of uses of a variable
  6850. % challenge: enhance the coloring algorithm using Chaitin's
  6851. % approach of prioritizing high-degree variables
  6852. % by removing low-degree variables (coloring them later)
  6853. % from the interference graph
  6854. \section{Further Reading}
  6855. \label{sec:register-allocation-further-reading}
  6856. Early register allocation algorithms were developed for Fortran
  6857. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6858. of graph coloring began in the late 1970s and early 1980s with the
  6859. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6860. algorithm is based on the following observation of
  6861. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6862. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6863. $v$ removed is also $k$ colorable. To see why, suppose that the
  6864. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6865. different colors, but because there are fewer than $k$ neighbors, there
  6866. will be one or more colors left over to use for coloring $v$ in $G$.
  6867. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6868. less than $k$ from the graph and recursively colors the rest of the
  6869. graph. Upon returning from the recursion, it colors $v$ with one of
  6870. the available colors and returns. \citet{Chaitin:1982vn} augments
  6871. this algorithm to handle spilling as follows. If there are no vertices
  6872. of degree lower than $k$ then pick a vertex at random, spill it,
  6873. remove it from the graph, and proceed recursively to color the rest of
  6874. the graph.
  6875. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6876. move-related and that don't interfere with each other, in a process
  6877. called \emph{coalescing}. Although coalescing decreases the number of
  6878. moves, it can make the graph more difficult to
  6879. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6880. which two variables are merged only if they have fewer than $k$
  6881. neighbors of high degree. \citet{George:1996aa} observes that
  6882. conservative coalescing is sometimes too conservative and made it more
  6883. aggressive by iterating the coalescing with the removal of low-degree
  6884. vertices.
  6885. %
  6886. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6887. also proposed \emph{biased coloring}, in which a variable is assigned to
  6888. the same color as another move-related variable if possible, as
  6889. discussed in section~\ref{sec:move-biasing}.
  6890. %
  6891. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6892. performs coalescing, graph coloring, and spill code insertion until
  6893. all variables have been assigned a location.
  6894. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6895. spilled variables that don't have to be: a high-degree variable can be
  6896. colorable if many of its neighbors are assigned the same color.
  6897. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6898. high-degree vertex is not immediately spilled. Instead the decision is
  6899. deferred until after the recursive call, at which point it is apparent
  6900. whether there is actually an available color or not. We observe that
  6901. this algorithm is equivalent to the smallest-last ordering
  6902. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6903. be registers and the rest to be stack locations.
  6904. %% biased coloring
  6905. Earlier editions of the compiler course at Indiana University
  6906. \citep{Dybvig:2010aa} were based on the algorithm of
  6907. \citet{Briggs:1994kx}.
  6908. The smallest-last ordering algorithm is one of many \emph{greedy}
  6909. coloring algorithms. A greedy coloring algorithm visits all the
  6910. vertices in a particular order and assigns each one the first
  6911. available color. An \emph{offline} greedy algorithm chooses the
  6912. ordering up front, prior to assigning colors. The algorithm of
  6913. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6914. ordering does not depend on the colors assigned. Other orderings are
  6915. possible. For example, \citet{Chow:1984ys} ordered variables according
  6916. to an estimate of runtime cost.
  6917. An \emph{online} greedy coloring algorithm uses information about the
  6918. current assignment of colors to influence the order in which the
  6919. remaining vertices are colored. The saturation-based algorithm
  6920. described in this chapter is one such algorithm. We choose to use
  6921. saturation-based coloring because it is fun to introduce graph
  6922. coloring via sudoku!
  6923. A register allocator may choose to map each variable to just one
  6924. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6925. variable to one or more locations. The latter can be achieved by
  6926. \emph{live range splitting}, where a variable is replaced by several
  6927. variables that each handle part of its live
  6928. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6929. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6930. %% replacement algorithm, bottom-up local
  6931. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6932. %% Cooper: top-down (priority bassed), bottom-up
  6933. %% top-down
  6934. %% order variables by priority (estimated cost)
  6935. %% caveat: split variables into two groups:
  6936. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6937. %% color the constrained ones first
  6938. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6939. %% cite J. Cocke for an algorithm that colors variables
  6940. %% in a high-degree first ordering
  6941. %Register Allocation via Usage Counts, Freiburghouse CACM
  6942. \citet{Palsberg:2007si} observes that many of the interference graphs
  6943. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6944. that is, every cycle with four or more edges has an edge that is not
  6945. part of the cycle but that connects two vertices on the cycle. Such
  6946. graphs can be optimally colored by the greedy algorithm with a vertex
  6947. ordering determined by maximum cardinality search.
  6948. In situations in which compile time is of utmost importance, such as
  6949. in just-in-time compilers, graph coloring algorithms can be too
  6950. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6951. be more appropriate.
  6952. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6953. {\if\edition\racketEd
  6954. \addtocontents{toc}{\newpage}
  6955. \fi}
  6956. \chapter{Booleans and Conditionals}
  6957. \label{ch:Lif}
  6958. \setcounter{footnote}{0}
  6959. The \LangVar{} language has only a single kind of value, the
  6960. integers. In this chapter we add a second kind of value, the Booleans,
  6961. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6962. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  6963. are written
  6964. \TRUE{}\index{subject}{True@\TRUE{}} and
  6965. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  6966. language includes several operations that involve Booleans
  6967. (\key{and}\index{subject}{and@\ANDNAME{}},
  6968. \key{or}\index{subject}{or@\ORNAME{}},
  6969. \key{not}\index{subject}{not@\NOTNAME{}},
  6970. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  6971. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  6972. \key{if}\index{subject}{IfExp@\IFNAME{}}
  6973. conditional expression\index{subject}{conditional expression}
  6974. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  6975. With the addition of \key{if}, programs can have
  6976. nontrivial control flow\index{subject}{control flow} which
  6977. %
  6978. \racket{impacts \code{explicate\_control} and liveness analysis.}
  6979. %
  6980. \python{impacts liveness analysis and motivates a new pass named
  6981. \code{explicate\_control}.}%
  6982. %
  6983. Also, because we now have two kinds of values, we need to handle
  6984. programs that apply an operation to the wrong kind of value, such as
  6985. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6986. There are two language design options for such situations. One option
  6987. is to signal an error and the other is to provide a wider
  6988. interpretation of the operation. \racket{The Racket
  6989. language}\python{Python} uses a mixture of these two options,
  6990. depending on the operation and the kind of value. For example, the
  6991. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6992. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6993. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6994. %
  6995. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6996. in Racket because \code{car} expects a pair.}
  6997. %
  6998. \python{On the other hand, \code{1[0]} results in a runtime error
  6999. in Python because an ``\code{int} object is not subscriptable''.}
  7000. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7001. design choices as \racket{Racket}\python{Python}, except that much of the
  7002. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7003. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7004. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7005. \python{MyPy} reports a compile-time error
  7006. %
  7007. \racket{because Racket expects the type of the argument to be of the form
  7008. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7009. %
  7010. \python{stating that a ``value of type \code{int} is not indexable''.}
  7011. The \LangIf{} language performs type checking during compilation just as
  7012. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7013. the alternative choice, that is, a dynamically typed language like
  7014. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7015. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7016. restrictive, for example, rejecting \racket{\code{(not
  7017. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7018. fairly simple because the focus of this book is on compilation and not
  7019. type systems, about which there are already several excellent
  7020. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7021. This chapter is organized as follows. We begin by defining the syntax
  7022. and interpreter for the \LangIf{} language
  7023. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7024. checking (aka semantic analysis\index{subject}{semantic analysis})
  7025. and define a type checker for \LangIf{}
  7026. (section~\ref{sec:type-check-Lif}).
  7027. %
  7028. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7029. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7030. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7031. %
  7032. The remaining sections of this chapter discuss how Booleans and
  7033. conditional control flow require changes to the existing compiler
  7034. passes and the addition of new ones. We introduce the \code{shrink}
  7035. pass to translate some operators into others, thereby reducing the
  7036. number of operators that need to be handled in later passes.
  7037. %
  7038. The main event of this chapter is the \code{explicate\_control} pass
  7039. that is responsible for translating \code{if}s into conditional
  7040. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7041. %
  7042. Regarding register allocation, there is the interesting question of
  7043. how to handle conditional \code{goto}s during liveness analysis.
  7044. \section{The \LangIf{} Language}
  7045. \label{sec:lang-if}
  7046. Definitions of the concrete syntax and abstract syntax of the
  7047. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7048. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7049. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7050. literals\index{subject}{literals}
  7051. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7052. \python{, and the \code{if} statement}. We expand the set of
  7053. operators to include
  7054. \begin{enumerate}
  7055. \item the logical operators \key{and}, \key{or}, and \key{not},
  7056. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7057. for comparing integers or Booleans for equality, and
  7058. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7059. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7060. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7061. comparing integers.
  7062. \end{enumerate}
  7063. \racket{We reorganize the abstract syntax for the primitive
  7064. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7065. rule for all of them. This means that the grammar no longer checks
  7066. whether the arity of an operator matches the number of
  7067. arguments. That responsibility is moved to the type checker for
  7068. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7069. \newcommand{\LifGrammarRacket}{
  7070. \begin{array}{lcl}
  7071. \Type &::=& \key{Boolean} \\
  7072. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7073. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7074. \Exp &::=& \itm{bool}
  7075. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7076. \MID (\key{not}\;\Exp) \\
  7077. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7078. \end{array}
  7079. }
  7080. \newcommand{\LifASTRacket}{
  7081. \begin{array}{lcl}
  7082. \Type &::=& \key{Boolean} \\
  7083. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7084. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7085. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7086. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7087. \end{array}
  7088. }
  7089. \newcommand{\LintOpAST}{
  7090. \begin{array}{rcl}
  7091. \Type &::=& \key{Integer} \\
  7092. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7093. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7094. \end{array}
  7095. }
  7096. \newcommand{\LifGrammarPython}{
  7097. \begin{array}{rcl}
  7098. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7099. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7100. \MID \key{not}~\Exp \\
  7101. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7102. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7103. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7104. \end{array}
  7105. }
  7106. \newcommand{\LifASTPython}{
  7107. \begin{array}{lcl}
  7108. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7109. \itm{unaryop} &::=& \code{Not()} \\
  7110. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7111. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7112. \Exp &::=& \BOOL{\itm{bool}}
  7113. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7114. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7115. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7116. \end{array}
  7117. }
  7118. \begin{figure}[tp]
  7119. \centering
  7120. \begin{tcolorbox}[colback=white]
  7121. {\if\edition\racketEd
  7122. \[
  7123. \begin{array}{l}
  7124. \gray{\LintGrammarRacket{}} \\ \hline
  7125. \gray{\LvarGrammarRacket{}} \\ \hline
  7126. \LifGrammarRacket{} \\
  7127. \begin{array}{lcl}
  7128. \LangIfM{} &::=& \Exp
  7129. \end{array}
  7130. \end{array}
  7131. \]
  7132. \fi}
  7133. {\if\edition\pythonEd\pythonColor
  7134. \[
  7135. \begin{array}{l}
  7136. \gray{\LintGrammarPython} \\ \hline
  7137. \gray{\LvarGrammarPython} \\ \hline
  7138. \LifGrammarPython \\
  7139. \begin{array}{rcl}
  7140. \LangIfM{} &::=& \Stmt^{*}
  7141. \end{array}
  7142. \end{array}
  7143. \]
  7144. \fi}
  7145. \end{tcolorbox}
  7146. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7147. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7148. \label{fig:Lif-concrete-syntax}
  7149. \end{figure}
  7150. \begin{figure}[tp]
  7151. %\begin{minipage}{0.66\textwidth}
  7152. \begin{tcolorbox}[colback=white]
  7153. \centering
  7154. {\if\edition\racketEd
  7155. \[
  7156. \begin{array}{l}
  7157. \gray{\LintOpAST} \\ \hline
  7158. \gray{\LvarASTRacket{}} \\ \hline
  7159. \LifASTRacket{} \\
  7160. \begin{array}{lcl}
  7161. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7162. \end{array}
  7163. \end{array}
  7164. \]
  7165. \fi}
  7166. {\if\edition\pythonEd\pythonColor
  7167. \[
  7168. \begin{array}{l}
  7169. \gray{\LintASTPython} \\ \hline
  7170. \gray{\LvarASTPython} \\ \hline
  7171. \LifASTPython \\
  7172. \begin{array}{lcl}
  7173. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7174. \end{array}
  7175. \end{array}
  7176. \]
  7177. \fi}
  7178. \end{tcolorbox}
  7179. %\end{minipage}
  7180. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7181. \python{
  7182. \index{subject}{BoolOp@\texttt{BoolOp}}
  7183. \index{subject}{Compare@\texttt{Compare}}
  7184. \index{subject}{Lt@\texttt{Lt}}
  7185. \index{subject}{LtE@\texttt{LtE}}
  7186. \index{subject}{Gt@\texttt{Gt}}
  7187. \index{subject}{GtE@\texttt{GtE}}
  7188. }
  7189. \caption{The abstract syntax of \LangIf{}.}
  7190. \label{fig:Lif-syntax}
  7191. \end{figure}
  7192. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7193. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7194. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  7195. evaluate to the corresponding Boolean values. The conditional
  7196. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  7197. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  7198. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  7199. \code{or}, and \code{not} behave according to propositional logic. In
  7200. addition, the \code{and} and \code{or} operations perform
  7201. \emph{short-circuit evaluation}.
  7202. %
  7203. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7204. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7205. %
  7206. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7207. evaluated if $e_1$ evaluates to \TRUE{}.
  7208. \racket{With the increase in the number of primitive operations, the
  7209. interpreter would become repetitive without some care. We refactor
  7210. the case for \code{Prim}, moving the code that differs with each
  7211. operation into the \code{interp\_op} method shown in
  7212. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7213. \code{or} operations separately because of their short-circuiting
  7214. behavior.}
  7215. \begin{figure}[tbp]
  7216. \begin{tcolorbox}[colback=white]
  7217. {\if\edition\racketEd
  7218. \begin{lstlisting}
  7219. (define interp-Lif-class
  7220. (class interp-Lvar-class
  7221. (super-new)
  7222. (define/public (interp_op op) ...)
  7223. (define/override ((interp_exp env) e)
  7224. (define recur (interp_exp env))
  7225. (match e
  7226. [(Bool b) b]
  7227. [(If cnd thn els)
  7228. (match (recur cnd)
  7229. [#t (recur thn)]
  7230. [#f (recur els)])]
  7231. [(Prim 'and (list e1 e2))
  7232. (match (recur e1)
  7233. [#t (match (recur e2) [#t #t] [#f #f])]
  7234. [#f #f])]
  7235. [(Prim 'or (list e1 e2))
  7236. (define v1 (recur e1))
  7237. (match v1
  7238. [#t #t]
  7239. [#f (match (recur e2) [#t #t] [#f #f])])]
  7240. [(Prim op args)
  7241. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7242. [else ((super interp_exp env) e)]))
  7243. ))
  7244. (define (interp_Lif p)
  7245. (send (new interp-Lif-class) interp_program p))
  7246. \end{lstlisting}
  7247. \fi}
  7248. {\if\edition\pythonEd\pythonColor
  7249. \begin{lstlisting}
  7250. class InterpLif(InterpLvar):
  7251. def interp_exp(self, e, env):
  7252. match e:
  7253. case IfExp(test, body, orelse):
  7254. if self.interp_exp(test, env):
  7255. return self.interp_exp(body, env)
  7256. else:
  7257. return self.interp_exp(orelse, env)
  7258. case UnaryOp(Not(), v):
  7259. return not self.interp_exp(v, env)
  7260. case BoolOp(And(), values):
  7261. if self.interp_exp(values[0], env):
  7262. return self.interp_exp(values[1], env)
  7263. else:
  7264. return False
  7265. case BoolOp(Or(), values):
  7266. if self.interp_exp(values[0], env):
  7267. return True
  7268. else:
  7269. return self.interp_exp(values[1], env)
  7270. case Compare(left, [cmp], [right]):
  7271. l = self.interp_exp(left, env)
  7272. r = self.interp_exp(right, env)
  7273. return self.interp_cmp(cmp)(l, r)
  7274. case _:
  7275. return super().interp_exp(e, env)
  7276. def interp_stmt(self, s, env, cont):
  7277. match s:
  7278. case If(test, body, orelse):
  7279. match self.interp_exp(test, env):
  7280. case True:
  7281. return self.interp_stmts(body + cont, env)
  7282. case False:
  7283. return self.interp_stmts(orelse + cont, env)
  7284. case _:
  7285. return super().interp_stmt(s, env, cont)
  7286. ...
  7287. \end{lstlisting}
  7288. \fi}
  7289. \end{tcolorbox}
  7290. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7291. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7292. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7293. \label{fig:interp-Lif}
  7294. \end{figure}
  7295. {\if\edition\racketEd
  7296. \begin{figure}[tbp]
  7297. \begin{tcolorbox}[colback=white]
  7298. \begin{lstlisting}
  7299. (define/public (interp_op op)
  7300. (match op
  7301. ['+ fx+]
  7302. ['- fx-]
  7303. ['read read-fixnum]
  7304. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7305. ['eq? (lambda (v1 v2)
  7306. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7307. (and (boolean? v1) (boolean? v2))
  7308. (and (vector? v1) (vector? v2)))
  7309. (eq? v1 v2)]))]
  7310. ['< (lambda (v1 v2)
  7311. (cond [(and (fixnum? v1) (fixnum? v2))
  7312. (< v1 v2)]))]
  7313. ['<= (lambda (v1 v2)
  7314. (cond [(and (fixnum? v1) (fixnum? v2))
  7315. (<= v1 v2)]))]
  7316. ['> (lambda (v1 v2)
  7317. (cond [(and (fixnum? v1) (fixnum? v2))
  7318. (> v1 v2)]))]
  7319. ['>= (lambda (v1 v2)
  7320. (cond [(and (fixnum? v1) (fixnum? v2))
  7321. (>= v1 v2)]))]
  7322. [else (error 'interp_op "unknown operator")]))
  7323. \end{lstlisting}
  7324. \end{tcolorbox}
  7325. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7326. \label{fig:interp-op-Lif}
  7327. \end{figure}
  7328. \fi}
  7329. {\if\edition\pythonEd\pythonColor
  7330. \begin{figure}
  7331. \begin{tcolorbox}[colback=white]
  7332. \begin{lstlisting}
  7333. class InterpLif(InterpLvar):
  7334. ...
  7335. def interp_cmp(self, cmp):
  7336. match cmp:
  7337. case Lt():
  7338. return lambda x, y: x < y
  7339. case LtE():
  7340. return lambda x, y: x <= y
  7341. case Gt():
  7342. return lambda x, y: x > y
  7343. case GtE():
  7344. return lambda x, y: x >= y
  7345. case Eq():
  7346. return lambda x, y: x == y
  7347. case NotEq():
  7348. return lambda x, y: x != y
  7349. \end{lstlisting}
  7350. \end{tcolorbox}
  7351. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7352. \label{fig:interp-cmp-Lif}
  7353. \end{figure}
  7354. \fi}
  7355. \section{Type Checking \LangIf{} Programs}
  7356. \label{sec:type-check-Lif}
  7357. It is helpful to think about type checking\index{subject}{type
  7358. checking} in two complementary ways. A type checker predicts the
  7359. type of value that will be produced by each expression in the program.
  7360. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7361. type checker should predict that {\if\edition\racketEd
  7362. \begin{lstlisting}
  7363. (+ 10 (- (+ 12 20)))
  7364. \end{lstlisting}
  7365. \fi}
  7366. {\if\edition\pythonEd\pythonColor
  7367. \begin{lstlisting}
  7368. 10 + -(12 + 20)
  7369. \end{lstlisting}
  7370. \fi}
  7371. \noindent produces a value of type \INTTY{}, whereas
  7372. {\if\edition\racketEd
  7373. \begin{lstlisting}
  7374. (and (not #f) #t)
  7375. \end{lstlisting}
  7376. \fi}
  7377. {\if\edition\pythonEd\pythonColor
  7378. \begin{lstlisting}
  7379. (not False) and True
  7380. \end{lstlisting}
  7381. \fi}
  7382. \noindent produces a value of type \BOOLTY{}.
  7383. A second way to think about type checking is that it enforces a set of
  7384. rules about which operators can be applied to which kinds of
  7385. values. For example, our type checker for \LangIf{} signals an error
  7386. for the following expression:
  7387. %
  7388. {\if\edition\racketEd
  7389. \begin{lstlisting}
  7390. (not (+ 10 (- (+ 12 20))))
  7391. \end{lstlisting}
  7392. \fi}
  7393. {\if\edition\pythonEd\pythonColor
  7394. \begin{lstlisting}
  7395. not (10 + -(12 + 20))
  7396. \end{lstlisting}
  7397. \fi}
  7398. \noindent The subexpression
  7399. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7400. \python{\code{(10 + -(12 + 20))}}
  7401. has type \INTTY{}, but the type checker enforces the rule that the
  7402. argument of \code{not} must be an expression of type \BOOLTY{}.
  7403. We implement type checking using classes and methods because they
  7404. provide the open recursion needed to reuse code as we extend the type
  7405. checker in subsequent chapters, analogous to the use of classes and methods
  7406. for the interpreters (section~\ref{sec:extensible-interp}).
  7407. We separate the type checker for the \LangVar{} subset into its own
  7408. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7409. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7410. from the type checker for \LangVar{}. These type checkers are in the
  7411. files
  7412. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7413. and
  7414. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7415. of the support code.
  7416. %
  7417. Each type checker is a structurally recursive function over the AST.
  7418. Given an input expression \code{e}, the type checker either signals an
  7419. error or returns \racket{an expression and} its type.
  7420. %
  7421. \racket{It returns an expression because there are situations in which
  7422. we want to change or update the expression.}
  7423. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7424. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7425. constant is \INTTY{}. To handle variables, the type checker uses the
  7426. environment \code{env} to map variables to types.
  7427. %
  7428. \racket{Consider the case for \key{let}. We type check the
  7429. initializing expression to obtain its type \key{T} and then
  7430. associate type \code{T} with the variable \code{x} in the
  7431. environment used to type check the body of the \key{let}. Thus,
  7432. when the type checker encounters a use of variable \code{x}, it can
  7433. find its type in the environment.}
  7434. %
  7435. \python{Consider the case for assignment. We type check the
  7436. initializing expression to obtain its type \key{t}. If the variable
  7437. \code{lhs.id} is already in the environment because there was a
  7438. prior assignment, we check that this initializer has the same type
  7439. as the prior one. If this is the first assignment to the variable,
  7440. we associate type \code{t} with the variable \code{lhs.id} in the
  7441. environment. Thus, when the type checker encounters a use of
  7442. variable \code{x}, it can find its type in the environment.}
  7443. %
  7444. \racket{Regarding primitive operators, we recursively analyze the
  7445. arguments and then invoke \code{type\_check\_op} to check whether
  7446. the argument types are allowed.}
  7447. %
  7448. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7449. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7450. \racket{Several auxiliary methods are used in the type checker. The
  7451. method \code{operator-types} defines a dictionary that maps the
  7452. operator names to their parameter and return types. The
  7453. \code{type-equal?} method determines whether two types are equal,
  7454. which for now simply dispatches to \code{equal?} (deep
  7455. equality). The \code{check-type-equal?} method triggers an error if
  7456. the two types are not equal. The \code{type-check-op} method looks
  7457. up the operator in the \code{operator-types} dictionary and then
  7458. checks whether the argument types are equal to the parameter types.
  7459. The result is the return type of the operator.}
  7460. %
  7461. \python{The auxiliary method \code{check\_type\_equal} triggers
  7462. an error if the two types are not equal.}
  7463. \begin{figure}[tbp]
  7464. \begin{tcolorbox}[colback=white]
  7465. {\if\edition\racketEd
  7466. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7467. (define type-check-Lvar-class
  7468. (class object%
  7469. (super-new)
  7470. (define/public (operator-types)
  7471. '((+ . ((Integer Integer) . Integer))
  7472. (- . ((Integer Integer) . Integer))
  7473. (read . (() . Integer))))
  7474. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7475. (define/public (check-type-equal? t1 t2 e)
  7476. (unless (type-equal? t1 t2)
  7477. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7478. (define/public (type-check-op op arg-types e)
  7479. (match (dict-ref (operator-types) op)
  7480. [`(,param-types . ,return-type)
  7481. (for ([at arg-types] [pt param-types])
  7482. (check-type-equal? at pt e))
  7483. return-type]
  7484. [else (error 'type-check-op "unrecognized ~a" op)]))
  7485. (define/public (type-check-exp env)
  7486. (lambda (e)
  7487. (match e
  7488. [(Int n) (values (Int n) 'Integer)]
  7489. [(Var x) (values (Var x) (dict-ref env x))]
  7490. [(Let x e body)
  7491. (define-values (e^ Te) ((type-check-exp env) e))
  7492. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7493. (values (Let x e^ b) Tb)]
  7494. [(Prim op es)
  7495. (define-values (new-es ts)
  7496. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7497. (values (Prim op new-es) (type-check-op op ts e))]
  7498. [else (error 'type-check-exp "couldn't match" e)])))
  7499. (define/public (type-check-program e)
  7500. (match e
  7501. [(Program info body)
  7502. (define-values (body^ Tb) ((type-check-exp '()) body))
  7503. (check-type-equal? Tb 'Integer body)
  7504. (Program info body^)]
  7505. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7506. ))
  7507. (define (type-check-Lvar p)
  7508. (send (new type-check-Lvar-class) type-check-program p))
  7509. \end{lstlisting}
  7510. \fi}
  7511. {\if\edition\pythonEd\pythonColor
  7512. \begin{lstlisting}[escapechar=`]
  7513. class TypeCheckLvar:
  7514. def check_type_equal(self, t1, t2, e):
  7515. if t1 != t2:
  7516. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7517. raise Exception(msg)
  7518. def type_check_exp(self, e, env):
  7519. match e:
  7520. case BinOp(left, (Add() | Sub()), right):
  7521. l = self.type_check_exp(left, env)
  7522. check_type_equal(l, int, left)
  7523. r = self.type_check_exp(right, env)
  7524. check_type_equal(r, int, right)
  7525. return int
  7526. case UnaryOp(USub(), v):
  7527. t = self.type_check_exp(v, env)
  7528. check_type_equal(t, int, v)
  7529. return int
  7530. case Name(id):
  7531. return env[id]
  7532. case Constant(value) if isinstance(value, int):
  7533. return int
  7534. case Call(Name('input_int'), []):
  7535. return int
  7536. def type_check_stmts(self, ss, env):
  7537. if len(ss) == 0:
  7538. return
  7539. match ss[0]:
  7540. case Assign([lhs], value):
  7541. t = self.type_check_exp(value, env)
  7542. if lhs.id in env:
  7543. check_type_equal(env[lhs.id], t, value)
  7544. else:
  7545. env[lhs.id] = t
  7546. return self.type_check_stmts(ss[1:], env)
  7547. case Expr(Call(Name('print'), [arg])):
  7548. t = self.type_check_exp(arg, env)
  7549. check_type_equal(t, int, arg)
  7550. return self.type_check_stmts(ss[1:], env)
  7551. case Expr(value):
  7552. self.type_check_exp(value, env)
  7553. return self.type_check_stmts(ss[1:], env)
  7554. def type_check_P(self, p):
  7555. match p:
  7556. case Module(body):
  7557. self.type_check_stmts(body, {})
  7558. \end{lstlisting}
  7559. \fi}
  7560. \end{tcolorbox}
  7561. \caption{Type checker for the \LangVar{} language.}
  7562. \label{fig:type-check-Lvar}
  7563. \end{figure}
  7564. \begin{figure}[tbp]
  7565. \begin{tcolorbox}[colback=white]
  7566. {\if\edition\racketEd
  7567. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7568. (define type-check-Lif-class
  7569. (class type-check-Lvar-class
  7570. (super-new)
  7571. (inherit check-type-equal?)
  7572. (define/override (operator-types)
  7573. (append '((and . ((Boolean Boolean) . Boolean))
  7574. (or . ((Boolean Boolean) . Boolean))
  7575. (< . ((Integer Integer) . Boolean))
  7576. (<= . ((Integer Integer) . Boolean))
  7577. (> . ((Integer Integer) . Boolean))
  7578. (>= . ((Integer Integer) . Boolean))
  7579. (not . ((Boolean) . Boolean)))
  7580. (super operator-types)))
  7581. (define/override (type-check-exp env)
  7582. (lambda (e)
  7583. (match e
  7584. [(Bool b) (values (Bool b) 'Boolean)]
  7585. [(Prim 'eq? (list e1 e2))
  7586. (define-values (e1^ T1) ((type-check-exp env) e1))
  7587. (define-values (e2^ T2) ((type-check-exp env) e2))
  7588. (check-type-equal? T1 T2 e)
  7589. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7590. [(If cnd thn els)
  7591. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7592. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7593. (define-values (els^ Te) ((type-check-exp env) els))
  7594. (check-type-equal? Tc 'Boolean e)
  7595. (check-type-equal? Tt Te e)
  7596. (values (If cnd^ thn^ els^) Te)]
  7597. [else ((super type-check-exp env) e)])))
  7598. ))
  7599. (define (type-check-Lif p)
  7600. (send (new type-check-Lif-class) type-check-program p))
  7601. \end{lstlisting}
  7602. \fi}
  7603. {\if\edition\pythonEd\pythonColor
  7604. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7605. class TypeCheckLif(TypeCheckLvar):
  7606. def type_check_exp(self, e, env):
  7607. match e:
  7608. case Constant(value) if isinstance(value, bool):
  7609. return bool
  7610. case BinOp(left, Sub(), right):
  7611. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7612. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7613. return int
  7614. case UnaryOp(Not(), v):
  7615. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7616. return bool
  7617. case BoolOp(op, values):
  7618. left = values[0] ; right = values[1]
  7619. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7620. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7621. return bool
  7622. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7623. or isinstance(cmp, NotEq):
  7624. l = self.type_check_exp(left, env)
  7625. r = self.type_check_exp(right, env)
  7626. check_type_equal(l, r, e)
  7627. return bool
  7628. case Compare(left, [cmp], [right]):
  7629. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7630. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7631. return bool
  7632. case IfExp(test, body, orelse):
  7633. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7634. b = self.type_check_exp(body, env)
  7635. o = self.type_check_exp(orelse, env)
  7636. check_type_equal(b, o, e)
  7637. return b
  7638. case _:
  7639. return super().type_check_exp(e, env)
  7640. def type_check_stmts(self, ss, env):
  7641. if len(ss) == 0:
  7642. return
  7643. match ss[0]:
  7644. case If(test, body, orelse):
  7645. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7646. b = self.type_check_stmts(body, env)
  7647. o = self.type_check_stmts(orelse, env)
  7648. check_type_equal(b, o, ss[0])
  7649. return self.type_check_stmts(ss[1:], env)
  7650. case _:
  7651. return super().type_check_stmts(ss, env)
  7652. \end{lstlisting}
  7653. \fi}
  7654. \end{tcolorbox}
  7655. \caption{Type checker for the \LangIf{} language.}
  7656. \label{fig:type-check-Lif}
  7657. \end{figure}
  7658. The definition of the type checker for \LangIf{} is shown in
  7659. figure~\ref{fig:type-check-Lif}.
  7660. %
  7661. The type of a Boolean constant is \BOOLTY{}.
  7662. %
  7663. \racket{The \code{operator-types} function adds dictionary entries for
  7664. the new operators.}
  7665. %
  7666. \python{Logical not requires its argument to be a \BOOLTY{} and
  7667. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  7668. %
  7669. The equality operator requires the two arguments to have the same type,
  7670. and therefore we handle it separately from the other operators.
  7671. %
  7672. \python{The other comparisons (less-than, etc.) require their
  7673. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  7674. %
  7675. The condition of an \code{if} must
  7676. be of \BOOLTY{} type, and the two branches must have the same type.
  7677. \begin{exercise}\normalfont\normalsize
  7678. Create ten new test programs in \LangIf{}. Half the programs should
  7679. have a type error. For those programs, create an empty file with the
  7680. same base name and with file extension \code{.tyerr}. For example, if
  7681. the test
  7682. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7683. is expected to error, then create
  7684. an empty file named \code{cond\_test\_14.tyerr}.
  7685. %
  7686. \racket{This indicates to \code{interp-tests} and
  7687. \code{compiler-tests} that a type error is expected. }
  7688. %
  7689. The other half of the test programs should not have type errors.
  7690. %
  7691. \racket{In the \code{run-tests.rkt} script, change the second argument
  7692. of \code{interp-tests} and \code{compiler-tests} to
  7693. \code{type-check-Lif}, which causes the type checker to run prior to
  7694. the compiler passes. Temporarily change the \code{passes} to an
  7695. empty list and run the script, thereby checking that the new test
  7696. programs either type check or do not, as intended.}
  7697. %
  7698. Run the test script to check that these test programs type check as
  7699. expected.
  7700. \end{exercise}
  7701. \clearpage
  7702. \section{The \LangCIf{} Intermediate Language}
  7703. \label{sec:Cif}
  7704. {\if\edition\racketEd
  7705. %
  7706. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7707. comparison operators to the \Exp{} nonterminal and the literals
  7708. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7709. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7710. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7711. comparison operation and the branches are \code{goto} statements,
  7712. making it straightforward to compile \code{if} statements to x86. The
  7713. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7714. expressions. A \code{goto} statement transfers control to the $\Tail$
  7715. expression corresponding to its label.
  7716. %
  7717. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7718. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7719. defines its abstract syntax.
  7720. %
  7721. \fi}
  7722. %
  7723. {\if\edition\pythonEd\pythonColor
  7724. %
  7725. The output of \key{explicate\_control} is a language similar to the
  7726. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7727. \code{goto} statements, so we name it \LangCIf{}.
  7728. %
  7729. The \LangCIf{} language supports the same operators as \LangIf{} but
  7730. the arguments of operators are restricted to atomic expressions. The
  7731. \LangCIf{} language does not include \code{if} expressions but it does
  7732. include a restricted form of \code{if} statement. The condition must be
  7733. a comparison and the two branches may only contain \code{goto}
  7734. statements. These restrictions make it easier to translate \code{if}
  7735. statements to x86. The \LangCIf{} language also adds a \code{return}
  7736. statement to finish the program with a specified value.
  7737. %
  7738. The \key{CProgram} construct contains a dictionary mapping labels to
  7739. lists of statements that end with a \code{return} statement, a
  7740. \code{goto}, or a conditional \code{goto}.
  7741. %% Statement lists of this
  7742. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  7743. %% is a control transfer at the end and control only enters at the
  7744. %% beginning of the list, which is marked by the label.
  7745. %
  7746. A \code{goto} statement transfers control to the sequence of statements
  7747. associated with its label.
  7748. %
  7749. The concrete syntax for \LangCIf{} is defined in
  7750. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  7751. in figure~\ref{fig:c1-syntax}.
  7752. %
  7753. \fi}
  7754. %
  7755. \newcommand{\CifGrammarRacket}{
  7756. \begin{array}{lcl}
  7757. \Atm &::=& \itm{bool} \\
  7758. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7759. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7760. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7761. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7762. \end{array}
  7763. }
  7764. \newcommand{\CifASTRacket}{
  7765. \begin{array}{lcl}
  7766. \Atm &::=& \BOOL{\itm{bool}} \\
  7767. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7768. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7769. \Tail &::= & \GOTO{\itm{label}} \\
  7770. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7771. \end{array}
  7772. }
  7773. \newcommand{\CifGrammarPython}{
  7774. \begin{array}{lcl}
  7775. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7776. \Exp &::= & \Atm \MID \CREAD{}
  7777. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7778. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7779. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7780. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  7781. &\MID& \CASSIGN{\Var}{\Exp}
  7782. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7783. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7784. \end{array}
  7785. }
  7786. \newcommand{\CifASTPython}{
  7787. \begin{array}{lcl}
  7788. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7789. \Exp &::= & \Atm \MID \READ{} \\
  7790. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7791. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7792. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7793. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7794. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  7795. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7796. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7797. \end{array}
  7798. }
  7799. \begin{figure}[tbp]
  7800. \begin{tcolorbox}[colback=white]
  7801. \small
  7802. {\if\edition\racketEd
  7803. \[
  7804. \begin{array}{l}
  7805. \gray{\CvarGrammarRacket} \\ \hline
  7806. \CifGrammarRacket \\
  7807. \begin{array}{lcl}
  7808. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7809. \end{array}
  7810. \end{array}
  7811. \]
  7812. \fi}
  7813. {\if\edition\pythonEd\pythonColor
  7814. \[
  7815. \begin{array}{l}
  7816. \CifGrammarPython \\
  7817. \begin{array}{lcl}
  7818. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  7819. \end{array}
  7820. \end{array}
  7821. \]
  7822. \fi}
  7823. \end{tcolorbox}
  7824. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7825. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7826. \label{fig:c1-concrete-syntax}
  7827. \end{figure}
  7828. \begin{figure}[tp]
  7829. \begin{tcolorbox}[colback=white]
  7830. \small
  7831. {\if\edition\racketEd
  7832. \[
  7833. \begin{array}{l}
  7834. \gray{\CvarASTRacket} \\ \hline
  7835. \CifASTRacket \\
  7836. \begin{array}{lcl}
  7837. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7838. \end{array}
  7839. \end{array}
  7840. \]
  7841. \fi}
  7842. {\if\edition\pythonEd\pythonColor
  7843. \[
  7844. \begin{array}{l}
  7845. \CifASTPython \\
  7846. \begin{array}{lcl}
  7847. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  7848. \end{array}
  7849. \end{array}
  7850. \]
  7851. \fi}
  7852. \end{tcolorbox}
  7853. \racket{
  7854. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7855. }
  7856. \index{subject}{Goto@\texttt{Goto}}
  7857. \index{subject}{Return@\texttt{Return}}
  7858. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7859. (figure~\ref{fig:c0-syntax})}.}
  7860. \label{fig:c1-syntax}
  7861. \end{figure}
  7862. \section{The \LangXIf{} Language}
  7863. \label{sec:x86-if}
  7864. \index{subject}{x86} To implement the new logical operations, the
  7865. comparison operations, and the \key{if} expression\python{ and
  7866. statement}, we delve further into the x86
  7867. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7868. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7869. subset of x86, which includes instructions for logical operations,
  7870. comparisons, and \racket{conditional} jumps.
  7871. %
  7872. \python{The abstract syntax for an \LangXIf{} program contains a
  7873. dictionary mapping labels to sequences of instructions, each of
  7874. which we refer to as a \emph{basic block}\index{subject}{basic
  7875. block}.}
  7876. One challenge is that x86 does not provide an instruction that
  7877. directly implements logical negation (\code{not} in \LangIf{} and
  7878. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7879. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7880. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7881. bit of its arguments, and writes the results into its second argument.
  7882. Recall the following truth table for exclusive-or:
  7883. \begin{center}
  7884. \begin{tabular}{l|cc}
  7885. & 0 & 1 \\ \hline
  7886. 0 & 0 & 1 \\
  7887. 1 & 1 & 0
  7888. \end{tabular}
  7889. \end{center}
  7890. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7891. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7892. for the bit $1$, the result is the opposite of the second bit. Thus,
  7893. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7894. the first argument, as follows, where $\Arg$ is the translation of
  7895. $\Atm$ to x86:
  7896. \[
  7897. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7898. \qquad\Rightarrow\qquad
  7899. \begin{array}{l}
  7900. \key{movq}~ \Arg\key{,} \Var\\
  7901. \key{xorq}~ \key{\$1,} \Var
  7902. \end{array}
  7903. \]
  7904. \newcommand{\GrammarXIf}{
  7905. \begin{array}{lcl}
  7906. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7907. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7908. \Arg &::=& \key{\%}\itm{bytereg}\\
  7909. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7910. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7911. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7912. \MID \key{set}cc~\Arg
  7913. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7914. &\MID& \key{j}cc~\itm{label} \\
  7915. \end{array}
  7916. }
  7917. \begin{figure}[tp]
  7918. \begin{tcolorbox}[colback=white]
  7919. \[
  7920. \begin{array}{l}
  7921. \gray{\GrammarXInt} \\ \hline
  7922. \GrammarXIf \\
  7923. \begin{array}{lcl}
  7924. \LangXIfM{} &::= & \key{.globl main} \\
  7925. & & \key{main:} \; \Instr\ldots
  7926. \end{array}
  7927. \end{array}
  7928. \]
  7929. \end{tcolorbox}
  7930. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7931. \label{fig:x86-1-concrete}
  7932. \end{figure}
  7933. \newcommand{\ASTXIfRacket}{
  7934. \begin{array}{lcl}
  7935. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7936. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7937. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7938. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7939. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7940. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7941. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7942. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7943. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7944. \end{array}
  7945. }
  7946. \begin{figure}[tp]
  7947. \begin{tcolorbox}[colback=white]
  7948. \small
  7949. {\if\edition\racketEd
  7950. \[\arraycolsep=3pt
  7951. \begin{array}{l}
  7952. \gray{\ASTXIntRacket} \\ \hline
  7953. \ASTXIfRacket \\
  7954. \begin{array}{lcl}
  7955. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7956. \end{array}
  7957. \end{array}
  7958. \]
  7959. \fi}
  7960. %
  7961. {\if\edition\pythonEd\pythonColor
  7962. \[
  7963. \begin{array}{lcl}
  7964. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7965. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7966. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7967. \MID \BYTEREG{\itm{bytereg}} \\
  7968. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7969. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7970. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7971. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7972. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7973. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7974. \MID \PUSHQ{\Arg}} \\
  7975. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7976. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7977. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7978. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7979. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7980. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7981. \Block &::= & \Instr^{+} \\
  7982. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7983. \end{array}
  7984. \]
  7985. \fi}
  7986. \end{tcolorbox}
  7987. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  7988. \label{fig:x86-1}
  7989. \end{figure}
  7990. Next we consider the x86 instructions that are relevant for compiling
  7991. the comparison operations. The \key{cmpq} instruction compares its two
  7992. arguments to determine whether one argument is less than, equal to, or
  7993. greater than the other argument. The \key{cmpq} instruction is unusual
  7994. regarding the order of its arguments and where the result is
  7995. placed. The argument order is backward: if you want to test whether
  7996. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7997. \key{cmpq} is placed in the special EFLAGS register. This register
  7998. cannot be accessed directly, but it can be queried by a number of
  7999. instructions, including the \key{set} instruction. The instruction
  8000. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8001. depending on whether the contents of the EFLAGS register matches the
  8002. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8003. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8004. The \key{set} instruction has a quirk in that its destination argument
  8005. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8006. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8007. register. Thankfully, the \key{movzbq} instruction can be used to
  8008. move from a single-byte register to a normal 64-bit register. The
  8009. abstract syntax for the \code{set} instruction differs from the
  8010. concrete syntax in that it separates the instruction name from the
  8011. condition code.
  8012. \python{The x86 instructions for jumping are relevant to the
  8013. compilation of \key{if} expressions.}
  8014. %
  8015. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8016. counter to the address of the instruction after the specified
  8017. label.}
  8018. %
  8019. \racket{The x86 instruction for conditional jump is relevant to the
  8020. compilation of \key{if} expressions.}
  8021. %
  8022. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8023. counter to point to the instruction after \itm{label}, depending on
  8024. whether the result in the EFLAGS register matches the condition code
  8025. \itm{cc}; otherwise, the jump instruction falls through to the next
  8026. instruction. Like the abstract syntax for \code{set}, the abstract
  8027. syntax for conditional jump separates the instruction name from the
  8028. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8029. corresponds to \code{jle foo}. Because the conditional jump instruction
  8030. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8031. a \key{cmpq} instruction to set the EFLAGS register.
  8032. \section{Shrink the \LangIf{} Language}
  8033. \label{sec:shrink-Lif}
  8034. The \LangIf{} language includes several features that are easily
  8035. expressible with other features. For example, \code{and} and \code{or}
  8036. are expressible using \code{if} as follows.
  8037. \begin{align*}
  8038. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8039. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8040. \end{align*}
  8041. By performing these translations in the front end of the compiler,
  8042. subsequent passes of the compiler do not need to deal with these features,
  8043. thus making the passes shorter.
  8044. On the other hand, translations sometimes reduce the efficiency of the
  8045. generated code by increasing the number of instructions. For example,
  8046. expressing subtraction in terms of negation
  8047. \[
  8048. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8049. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8050. \]
  8051. produces code with two x86 instructions (\code{negq} and \code{addq})
  8052. instead of just one (\code{subq}).
  8053. \begin{exercise}\normalfont\normalsize
  8054. %
  8055. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8056. the language by translating them to \code{if} expressions in \LangIf{}.
  8057. %
  8058. Create four test programs that involve these operators.
  8059. %
  8060. {\if\edition\racketEd
  8061. In the \code{run-tests.rkt} script, add the following entry for
  8062. \code{shrink} to the list of passes (it should be the only pass at
  8063. this point).
  8064. \begin{lstlisting}
  8065. (list "shrink" shrink interp_Lif type-check-Lif)
  8066. \end{lstlisting}
  8067. This instructs \code{interp-tests} to run the interpreter
  8068. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8069. output of \code{shrink}.
  8070. \fi}
  8071. %
  8072. Run the script to test your compiler on all the test programs.
  8073. \end{exercise}
  8074. {\if\edition\racketEd
  8075. \section{Uniquify Variables}
  8076. \label{sec:uniquify-Lif}
  8077. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8078. \code{if} expressions.
  8079. \begin{exercise}\normalfont\normalsize
  8080. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8081. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8082. \begin{lstlisting}
  8083. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8084. \end{lstlisting}
  8085. Run the script to test your compiler.
  8086. \end{exercise}
  8087. \fi}
  8088. \section{Remove Complex Operands}
  8089. \label{sec:remove-complex-opera-Lif}
  8090. The output language of \code{remove\_complex\_operands} is
  8091. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8092. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8093. but the \code{if} expression is not. All three subexpressions of an
  8094. \code{if} are allowed to be complex expressions, but the operands of
  8095. the \code{not} operator and comparison operators must be atomic.
  8096. %
  8097. \python{We add a new language form, the \code{Begin} expression, to aid
  8098. in the translation of \code{if} expressions. When we recursively
  8099. process the two branches of the \code{if}, we generate temporary
  8100. variables and their initializing expressions. However, these
  8101. expressions may contain side effects and should only be executed
  8102. when the condition of the \code{if} is true (for the ``then''
  8103. branch) or false (for the ``else'' branch). The \code{Begin} provides
  8104. a way to initialize the temporary variables within the two branches
  8105. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8106. form execute the statements $ss$ and then returns the result of
  8107. expression $e$.}
  8108. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8109. the new features in \LangIf{}. In recursively processing
  8110. subexpressions, recall that you should invoke \code{rco\_atom} when
  8111. the output needs to be an \Atm{} (as specified in the grammar for
  8112. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8113. \Exp{}. Regarding \code{if}, it is particularly important
  8114. \emph{not} to replace its condition with a temporary variable, because
  8115. that would interfere with the generation of high-quality output in the
  8116. upcoming \code{explicate\_control} pass.
  8117. \newcommand{\LifMonadASTRacket}{
  8118. \begin{array}{rcl}
  8119. \Atm &::=& \BOOL{\itm{bool}}\\
  8120. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8121. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8122. \MID \IF{\Exp}{\Exp}{\Exp}
  8123. \end{array}
  8124. }
  8125. \newcommand{\LifMonadASTPython}{
  8126. \begin{array}{rcl}
  8127. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  8128. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  8129. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  8130. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  8131. \Atm &::=& \BOOL{\itm{bool}}\\
  8132. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8133. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  8134. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8135. \end{array}
  8136. }
  8137. \begin{figure}[tp]
  8138. \centering
  8139. \begin{tcolorbox}[colback=white]
  8140. {\if\edition\racketEd
  8141. \[
  8142. \begin{array}{l}
  8143. \gray{\LvarMonadASTRacket} \\ \hline
  8144. \LifMonadASTRacket \\
  8145. \begin{array}{rcl}
  8146. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8147. \end{array}
  8148. \end{array}
  8149. \]
  8150. \fi}
  8151. {\if\edition\pythonEd\pythonColor
  8152. \[
  8153. \begin{array}{l}
  8154. \gray{\LvarMonadASTPython} \\ \hline
  8155. \LifMonadASTPython \\
  8156. \begin{array}{rcl}
  8157. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8158. \end{array}
  8159. \end{array}
  8160. \]
  8161. \fi}
  8162. \end{tcolorbox}
  8163. \python{\index{subject}{Begin@\texttt{Begin}}}
  8164. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8165. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8166. \label{fig:Lif-anf-syntax}
  8167. \end{figure}
  8168. \begin{exercise}\normalfont\normalsize
  8169. %
  8170. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8171. and \code{rco\_exp} functions in \code{compiler.rkt}.
  8172. %
  8173. Create three new \LangIf{} programs that exercise the interesting
  8174. code in this pass.
  8175. %
  8176. {\if\edition\racketEd
  8177. In the \code{run-tests.rkt} script, add the following entry to the
  8178. list of \code{passes} and then run the script to test your compiler.
  8179. \begin{lstlisting}
  8180. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8181. \end{lstlisting}
  8182. \fi}
  8183. \end{exercise}
  8184. \section{Explicate Control}
  8185. \label{sec:explicate-control-Lif}
  8186. \racket{Recall that the purpose of \code{explicate\_control} is to
  8187. make the order of evaluation explicit in the syntax of the program.
  8188. With the addition of \key{if}, this becomes more interesting.}
  8189. %
  8190. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8191. %
  8192. The main challenge to overcome is that the condition of an \key{if}
  8193. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8194. condition must be a comparison.
  8195. As a motivating example, consider the following program that has an
  8196. \key{if} expression nested in the condition of another \key{if}:%
  8197. \python{\footnote{Programmers rarely write nested \code{if}
  8198. expressions, but it is not uncommon for the condition of an
  8199. \code{if} statement to be a call of a function that also contains an
  8200. \code{if} statement. When such a function is inlined, the result is
  8201. a nested \code{if} that requires the techniques discussed in this
  8202. section.}}
  8203. % cond_test_41.rkt, if_lt_eq.py
  8204. \begin{center}
  8205. \begin{minipage}{0.96\textwidth}
  8206. {\if\edition\racketEd
  8207. \begin{lstlisting}
  8208. (let ([x (read)])
  8209. (let ([y (read)])
  8210. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8211. (+ y 2)
  8212. (+ y 10))))
  8213. \end{lstlisting}
  8214. \fi}
  8215. {\if\edition\pythonEd\pythonColor
  8216. \begin{lstlisting}
  8217. x = input_int()
  8218. y = input_int()
  8219. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8220. \end{lstlisting}
  8221. \fi}
  8222. \end{minipage}
  8223. \end{center}
  8224. %
  8225. The naive way to compile \key{if} and the comparison operations would
  8226. be to handle each of them in isolation, regardless of their context.
  8227. Each comparison would be translated into a \key{cmpq} instruction
  8228. followed by several instructions to move the result from the EFLAGS
  8229. register into a general purpose register or stack location. Each
  8230. \key{if} would be translated into a \key{cmpq} instruction followed by
  8231. a conditional jump. The generated code for the inner \key{if} in this
  8232. example would be as follows:
  8233. \begin{center}
  8234. \begin{minipage}{0.96\textwidth}
  8235. \begin{lstlisting}
  8236. cmpq $1, x
  8237. setl %al
  8238. movzbq %al, tmp
  8239. cmpq $1, tmp
  8240. je then_branch_1
  8241. jmp else_branch_1
  8242. \end{lstlisting}
  8243. \end{minipage}
  8244. \end{center}
  8245. Notice that the three instructions starting with \code{setl} are
  8246. redundant; the conditional jump could come immediately after the first
  8247. \code{cmpq}.
  8248. Our goal is to compile \key{if} expressions so that the relevant
  8249. comparison instruction appears directly before the conditional jump.
  8250. For example, we want to generate the following code for the inner
  8251. \code{if}:
  8252. \begin{center}
  8253. \begin{minipage}{0.96\textwidth}
  8254. \begin{lstlisting}
  8255. cmpq $1, x
  8256. jl then_branch_1
  8257. jmp else_branch_1
  8258. \end{lstlisting}
  8259. \end{minipage}
  8260. \end{center}
  8261. One way to achieve this goal is to reorganize the code at the level of
  8262. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8263. the following code:
  8264. \begin{center}
  8265. \begin{minipage}{0.96\textwidth}
  8266. {\if\edition\racketEd
  8267. \begin{lstlisting}
  8268. (let ([x (read)])
  8269. (let ([y (read)])
  8270. (if (< x 1)
  8271. (if (eq? x 0)
  8272. (+ y 2)
  8273. (+ y 10))
  8274. (if (eq? x 2)
  8275. (+ y 2)
  8276. (+ y 10)))))
  8277. \end{lstlisting}
  8278. \fi}
  8279. {\if\edition\pythonEd\pythonColor
  8280. \begin{lstlisting}
  8281. x = input_int()
  8282. y = input_int()
  8283. print(((y + 2) if x == 0 else (y + 10)) \
  8284. if (x < 1) \
  8285. else ((y + 2) if (x == 2) else (y + 10)))
  8286. \end{lstlisting}
  8287. \fi}
  8288. \end{minipage}
  8289. \end{center}
  8290. Unfortunately, this approach duplicates the two branches from the
  8291. outer \code{if}, and a compiler must never duplicate code! After all,
  8292. the two branches could be very large expressions.
  8293. How can we apply this transformation without duplicating code? In
  8294. other words, how can two different parts of a program refer to one
  8295. piece of code?
  8296. %
  8297. The answer is that we must move away from abstract syntax \emph{trees}
  8298. and instead use \emph{graphs}.
  8299. %
  8300. At the level of x86 assembly, this is straightforward because we can
  8301. label the code for each branch and insert jumps in all the places that
  8302. need to execute the branch. In this way, jump instructions are edges
  8303. in the graph and the basic blocks are the nodes.
  8304. %
  8305. Likewise, our language \LangCIf{} provides the ability to label a
  8306. sequence of statements and to jump to a label via \code{goto}.
  8307. As a preview of what \code{explicate\_control} will do,
  8308. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8309. \code{explicate\_control} on this example. Note how the condition of
  8310. every \code{if} is a comparison operation and that we have not
  8311. duplicated any code but instead have used labels and \code{goto} to
  8312. enable sharing of code.
  8313. \begin{figure}[tbp]
  8314. \begin{tcolorbox}[colback=white]
  8315. {\if\edition\racketEd
  8316. \begin{tabular}{lll}
  8317. \begin{minipage}{0.4\textwidth}
  8318. % cond_test_41.rkt
  8319. \begin{lstlisting}
  8320. (let ([x (read)])
  8321. (let ([y (read)])
  8322. (if (if (< x 1)
  8323. (eq? x 0)
  8324. (eq? x 2))
  8325. (+ y 2)
  8326. (+ y 10))))
  8327. \end{lstlisting}
  8328. \end{minipage}
  8329. &
  8330. $\Rightarrow$
  8331. &
  8332. \begin{minipage}{0.55\textwidth}
  8333. \begin{lstlisting}
  8334. start:
  8335. x = (read);
  8336. y = (read);
  8337. if (< x 1)
  8338. goto block_4;
  8339. else
  8340. goto block_5;
  8341. block_4:
  8342. if (eq? x 0)
  8343. goto block_2;
  8344. else
  8345. goto block_3;
  8346. block_5:
  8347. if (eq? x 2)
  8348. goto block_2;
  8349. else
  8350. goto block_3;
  8351. block_2:
  8352. return (+ y 2);
  8353. block_3:
  8354. return (+ y 10);
  8355. \end{lstlisting}
  8356. \end{minipage}
  8357. \end{tabular}
  8358. \fi}
  8359. {\if\edition\pythonEd\pythonColor
  8360. \begin{tabular}{lll}
  8361. \begin{minipage}{0.4\textwidth}
  8362. % cond_test_41.rkt
  8363. \begin{lstlisting}
  8364. x = input_int()
  8365. y = input_int()
  8366. print(y + 2 \
  8367. if (x == 0 \
  8368. if x < 1 \
  8369. else x == 2) \
  8370. else y + 10)
  8371. \end{lstlisting}
  8372. \end{minipage}
  8373. &
  8374. $\Rightarrow$
  8375. &
  8376. \begin{minipage}{0.55\textwidth}
  8377. \begin{lstlisting}
  8378. start:
  8379. x = input_int()
  8380. y = input_int()
  8381. if x < 1:
  8382. goto block_8
  8383. else:
  8384. goto block_9
  8385. block_8:
  8386. if x == 0:
  8387. goto block_4
  8388. else:
  8389. goto block_5
  8390. block_9:
  8391. if x == 2:
  8392. goto block_6
  8393. else:
  8394. goto block_7
  8395. block_4:
  8396. goto block_2
  8397. block_5:
  8398. goto block_3
  8399. block_6:
  8400. goto block_2
  8401. block_7:
  8402. goto block_3
  8403. block_2:
  8404. tmp_0 = y + 2
  8405. goto block_1
  8406. block_3:
  8407. tmp_0 = y + 10
  8408. goto block_1
  8409. block_1:
  8410. print(tmp_0)
  8411. return 0
  8412. \end{lstlisting}
  8413. \end{minipage}
  8414. \end{tabular}
  8415. \fi}
  8416. \end{tcolorbox}
  8417. \caption{Translation from \LangIf{} to \LangCIf{}
  8418. via the \code{explicate\_control}.}
  8419. \label{fig:explicate-control-s1-38}
  8420. \end{figure}
  8421. {\if\edition\racketEd
  8422. %
  8423. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8424. \code{explicate\_control} for \LangVar{} using two recursive
  8425. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8426. former function translates expressions in tail position, whereas the
  8427. latter function translates expressions on the right-hand side of a
  8428. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8429. have a new kind of position to deal with: the predicate position of
  8430. the \key{if}. We need another function, \code{explicate\_pred}, that
  8431. decides how to compile an \key{if} by analyzing its condition. So,
  8432. \code{explicate\_pred} takes an \LangIf{} expression and two
  8433. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8434. and outputs a tail. In the following paragraphs we discuss specific
  8435. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8436. \code{explicate\_pred} functions.
  8437. %
  8438. \fi}
  8439. %
  8440. {\if\edition\pythonEd\pythonColor
  8441. %
  8442. We recommend implementing \code{explicate\_control} using the
  8443. following four auxiliary functions.
  8444. \begin{description}
  8445. \item[\code{explicate\_effect}] generates code for expressions as
  8446. statements, so their result is ignored and only their side effects
  8447. matter.
  8448. \item[\code{explicate\_assign}] generates code for expressions
  8449. on the right-hand side of an assignment.
  8450. \item[\code{explicate\_pred}] generates code for an \code{if}
  8451. expression or statement by analyzing the condition expression.
  8452. \item[\code{explicate\_stmt}] generates code for statements.
  8453. \end{description}
  8454. These four functions should build the dictionary of basic blocks. The
  8455. following auxiliary function can be used to create a new basic block
  8456. from a list of statements. It returns a \code{goto} statement that
  8457. jumps to the new basic block.
  8458. \begin{center}
  8459. \begin{minipage}{\textwidth}
  8460. \begin{lstlisting}
  8461. def create_block(stmts, basic_blocks):
  8462. label = label_name(generate_name('block'))
  8463. basic_blocks[label] = stmts
  8464. return Goto(label)
  8465. \end{lstlisting}
  8466. \end{minipage}
  8467. \end{center}
  8468. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8469. \code{explicate\_control} pass.
  8470. The \code{explicate\_effect} function has three parameters: 1) the
  8471. expression to be compiled, 2) the already-compiled code for this
  8472. expression's \emph{continuation}, that is, the list of statements that
  8473. should execute after this expression, and 3) the dictionary of
  8474. generated basic blocks. The \code{explicate\_effect} function returns
  8475. a list of \LangCIf{} statements and it may add to the dictionary of
  8476. basic blocks.
  8477. %
  8478. Let's consider a few of the cases for the expression to be compiled.
  8479. If the expression to be compiled is a constant, then it can be
  8480. discarded because it has no side effects. If it's a \CREAD{}, then it
  8481. has a side-effect and should be preserved. So the expression should be
  8482. translated into a statement using the \code{Expr} AST class. If the
  8483. expression to be compiled is an \code{if} expression, we translate the
  8484. two branches using \code{explicate\_effect} and then translate the
  8485. condition expression using \code{explicate\_pred}, which generates
  8486. code for the entire \code{if}.
  8487. The \code{explicate\_assign} function has four parameters: 1) the
  8488. right-hand side of the assignment, 2) the left-hand side of the
  8489. assignment (the variable), 3) the continuation, and 4) the dictionary
  8490. of basic blocks. The \code{explicate\_assign} function returns a list
  8491. of \LangCIf{} statements and it may add to the dictionary of basic
  8492. blocks.
  8493. When the right-hand side is an \code{if} expression, there is some
  8494. work to do. In particular, the two branches should be translated using
  8495. \code{explicate\_assign} and the condition expression should be
  8496. translated using \code{explicate\_pred}. Otherwise we can simply
  8497. generate an assignment statement, with the given left and right-hand
  8498. sides, concatenated with its continuation.
  8499. \begin{figure}[tbp]
  8500. \begin{tcolorbox}[colback=white]
  8501. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8502. def explicate_effect(e, cont, basic_blocks):
  8503. match e:
  8504. case IfExp(test, body, orelse):
  8505. ...
  8506. case Call(func, args):
  8507. ...
  8508. case Begin(body, result):
  8509. ...
  8510. case _:
  8511. ...
  8512. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8513. match rhs:
  8514. case IfExp(test, body, orelse):
  8515. ...
  8516. case Begin(body, result):
  8517. ...
  8518. case _:
  8519. return [Assign([lhs], rhs)] + cont
  8520. def explicate_pred(cnd, thn, els, basic_blocks):
  8521. match cnd:
  8522. case Compare(left, [op], [right]):
  8523. goto_thn = create_block(thn, basic_blocks)
  8524. goto_els = create_block(els, basic_blocks)
  8525. return [If(cnd, [goto_thn], [goto_els])]
  8526. case Constant(True):
  8527. return thn;
  8528. case Constant(False):
  8529. return els;
  8530. case UnaryOp(Not(), operand):
  8531. ...
  8532. case IfExp(test, body, orelse):
  8533. ...
  8534. case Begin(body, result):
  8535. ...
  8536. case _:
  8537. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8538. [create_block(els, basic_blocks)],
  8539. [create_block(thn, basic_blocks)])]
  8540. def explicate_stmt(s, cont, basic_blocks):
  8541. match s:
  8542. case Assign([lhs], rhs):
  8543. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8544. case Expr(value):
  8545. return explicate_effect(value, cont, basic_blocks)
  8546. case If(test, body, orelse):
  8547. ...
  8548. def explicate_control(p):
  8549. match p:
  8550. case Module(body):
  8551. new_body = [Return(Constant(0))]
  8552. basic_blocks = {}
  8553. for s in reversed(body):
  8554. new_body = explicate_stmt(s, new_body, basic_blocks)
  8555. basic_blocks[label_name('start')] = new_body
  8556. return CProgram(basic_blocks)
  8557. \end{lstlisting}
  8558. \end{tcolorbox}
  8559. \caption{Skeleton for the \code{explicate\_control} pass.}
  8560. \label{fig:explicate-control-Lif}
  8561. \end{figure}
  8562. \fi}
  8563. {\if\edition\racketEd
  8564. \subsection{Explicate Tail and Assign}
  8565. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8566. additional cases for Boolean constants and \key{if}. The cases for
  8567. \code{if} should recursively compile the two branches using either
  8568. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8569. cases should then invoke \code{explicate\_pred} on the condition
  8570. expression, passing in the generated code for the two branches. For
  8571. example, consider the following program with an \code{if} in tail
  8572. position.
  8573. % cond_test_6.rkt
  8574. \begin{lstlisting}
  8575. (let ([x (read)])
  8576. (if (eq? x 0) 42 777))
  8577. \end{lstlisting}
  8578. The two branches are recursively compiled to return statements. We
  8579. then delegate to \code{explicate\_pred}, passing the condition
  8580. \code{(eq? x 0)} and the two return statements. We return to this
  8581. example shortly when we discuss \code{explicate\_pred}.
  8582. Next let us consider a program with an \code{if} on the right-hand
  8583. side of a \code{let}.
  8584. \begin{lstlisting}
  8585. (let ([y (read)])
  8586. (let ([x (if (eq? y 0) 40 777)])
  8587. (+ x 2)))
  8588. \end{lstlisting}
  8589. Note that the body of the inner \code{let} will have already been
  8590. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8591. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8592. to recursively process both branches of the \code{if}, and we do not
  8593. want to duplicate code, so we generate the following block using an
  8594. auxiliary function named \code{create\_block}, discussed in the next
  8595. section.
  8596. \begin{lstlisting}
  8597. block_6:
  8598. return (+ x 2)
  8599. \end{lstlisting}
  8600. We then use \code{goto block\_6;} as the \code{cont} argument for
  8601. compiling the branches. So the two branches compile to
  8602. \begin{center}
  8603. \begin{minipage}{0.2\textwidth}
  8604. \begin{lstlisting}
  8605. x = 40;
  8606. goto block_6;
  8607. \end{lstlisting}
  8608. \end{minipage}
  8609. \hspace{0.5in} and \hspace{0.5in}
  8610. \begin{minipage}{0.2\textwidth}
  8611. \begin{lstlisting}
  8612. x = 777;
  8613. goto block_6;
  8614. \end{lstlisting}
  8615. \end{minipage}
  8616. \end{center}
  8617. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8618. \code{(eq? y 0)} and the previously presented code for the branches.
  8619. \subsection{Create Block}
  8620. We recommend implementing the \code{create\_block} auxiliary function
  8621. as follows, using a global variable \code{basic-blocks} to store a
  8622. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8623. that \code{create\_block} generates a new label and then associates
  8624. the given \code{tail} with the new label in the \code{basic-blocks}
  8625. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8626. new label. However, if the given \code{tail} is already a \code{Goto},
  8627. then there is no need to generate a new label and entry in
  8628. \code{basic-blocks}; we can simply return that \code{Goto}.
  8629. %
  8630. \begin{lstlisting}
  8631. (define (create_block tail)
  8632. (match tail
  8633. [(Goto label) (Goto label)]
  8634. [else
  8635. (let ([label (gensym 'block)])
  8636. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8637. (Goto label))]))
  8638. \end{lstlisting}
  8639. \fi}
  8640. {\if\edition\racketEd
  8641. \subsection{Explicate Predicate}
  8642. The skeleton for the \code{explicate\_pred} function is given in
  8643. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8644. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8645. the code generated by explicate for the \emph{then} branch; and (3)
  8646. \code{els}, the code generated by explicate for the \emph{else}
  8647. branch. The \code{explicate\_pred} function should match on
  8648. \code{cnd} with a case for every kind of expression that can have type
  8649. \BOOLTY{}.
  8650. \begin{figure}[tbp]
  8651. \begin{tcolorbox}[colback=white]
  8652. \begin{lstlisting}
  8653. (define (explicate_pred cnd thn els)
  8654. (match cnd
  8655. [(Var x) ___]
  8656. [(Let x rhs body) ___]
  8657. [(Prim 'not (list e)) ___]
  8658. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8659. (IfStmt (Prim op es) (create_block thn)
  8660. (create_block els))]
  8661. [(Bool b) (if b thn els)]
  8662. [(If cnd^ thn^ els^) ___]
  8663. [else (error "explicate_pred unhandled case" cnd)]))
  8664. \end{lstlisting}
  8665. \end{tcolorbox}
  8666. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8667. \label{fig:explicate-pred}
  8668. \end{figure}
  8669. \fi}
  8670. %
  8671. {\if\edition\pythonEd\pythonColor
  8672. The \code{explicate\_pred} function has four parameters: 1) the
  8673. condition expression, 2) the generated statements for the ``then''
  8674. branch, 3) the generated statements for the ``else'' branch, and 4)
  8675. the dictionary of basic blocks. The \code{explicate\_pred} function
  8676. returns a list of \LangCIf{} statements and it may add to the
  8677. dictionary of basic blocks.
  8678. \fi}
  8679. Consider the case for comparison operators. We translate the
  8680. comparison to an \code{if} statement whose branches are \code{goto}
  8681. statements created by applying \code{create\_block} to the code
  8682. generated for the \code{thn} and \code{els} branches. Let us
  8683. illustrate this translation by returning to the program with an
  8684. \code{if} expression in tail position, shown next. We invoke
  8685. \code{explicate\_pred} on its condition
  8686. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8687. %
  8688. {\if\edition\racketEd
  8689. \begin{lstlisting}
  8690. (let ([x (read)])
  8691. (if (eq? x 0) 42 777))
  8692. \end{lstlisting}
  8693. \fi}
  8694. %
  8695. {\if\edition\pythonEd\pythonColor
  8696. \begin{lstlisting}
  8697. x = input_int()
  8698. 42 if x == 0 else 777
  8699. \end{lstlisting}
  8700. \fi}
  8701. %
  8702. \noindent The two branches \code{42} and \code{777} were already
  8703. compiled to \code{return} statements, from which we now create the
  8704. following blocks:
  8705. %
  8706. \begin{center}
  8707. \begin{minipage}{\textwidth}
  8708. \begin{lstlisting}
  8709. block_1:
  8710. return 42;
  8711. block_2:
  8712. return 777;
  8713. \end{lstlisting}
  8714. \end{minipage}
  8715. \end{center}
  8716. %
  8717. After that, \code{explicate\_pred} compiles the comparison
  8718. \racket{\code{(eq? x 0)}}
  8719. \python{\code{x == 0}}
  8720. to the following \code{if} statement:
  8721. %
  8722. {\if\edition\racketEd
  8723. \begin{center}
  8724. \begin{minipage}{\textwidth}
  8725. \begin{lstlisting}
  8726. if (eq? x 0)
  8727. goto block_1;
  8728. else
  8729. goto block_2;
  8730. \end{lstlisting}
  8731. \end{minipage}
  8732. \end{center}
  8733. \fi}
  8734. {\if\edition\pythonEd\pythonColor
  8735. \begin{center}
  8736. \begin{minipage}{\textwidth}
  8737. \begin{lstlisting}
  8738. if x == 0:
  8739. goto block_1;
  8740. else
  8741. goto block_2;
  8742. \end{lstlisting}
  8743. \end{minipage}
  8744. \end{center}
  8745. \fi}
  8746. Next consider the case for Boolean constants. We perform a kind of
  8747. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8748. either the \code{thn} or \code{els} branch, depending on whether the
  8749. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8750. following program:
  8751. {\if\edition\racketEd
  8752. \begin{lstlisting}
  8753. (if #t 42 777)
  8754. \end{lstlisting}
  8755. \fi}
  8756. {\if\edition\pythonEd\pythonColor
  8757. \begin{lstlisting}
  8758. 42 if True else 777
  8759. \end{lstlisting}
  8760. \fi}
  8761. %
  8762. \noindent Again, the two branches \code{42} and \code{777} were
  8763. compiled to \code{return} statements, so \code{explicate\_pred}
  8764. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8765. code for the \emph{then} branch.
  8766. \begin{lstlisting}
  8767. return 42;
  8768. \end{lstlisting}
  8769. This case demonstrates that we sometimes discard the \code{thn} or
  8770. \code{els} blocks that are input to \code{explicate\_pred}.
  8771. The case for \key{if} expressions in \code{explicate\_pred} is
  8772. particularly illuminating because it deals with the challenges
  8773. discussed previously regarding nested \key{if} expressions
  8774. (figure~\ref{fig:explicate-control-s1-38}). The
  8775. \racket{\lstinline{thn^}}\python{\code{body}} and
  8776. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8777. \key{if} inherit their context from the current one, that is,
  8778. predicate context. So, you should recursively apply
  8779. \code{explicate\_pred} to the
  8780. \racket{\lstinline{thn^}}\python{\code{body}} and
  8781. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8782. those recursive calls, pass \code{thn} and \code{els} as the extra
  8783. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8784. inside each recursive call. As discussed previously, to avoid
  8785. duplicating code, we need to add them to the dictionary of basic
  8786. blocks so that we can instead refer to them by name and execute them
  8787. with a \key{goto}.
  8788. {\if\edition\pythonEd\pythonColor
  8789. %
  8790. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8791. three parameters: 1) the statement to be compiled, 2) the code for its
  8792. continuation, and 3) the dictionary of basic blocks. The
  8793. \code{explicate\_stmt} returns a list of statements and it may add to
  8794. the dictionary of basic blocks. The cases for assignment and an
  8795. expression-statement are given in full in the skeleton code: they
  8796. simply dispatch to \code{explicate\_assign} and
  8797. \code{explicate\_effect}, respectively. The case for \code{if}
  8798. statements is not given, and is similar to the case for \code{if}
  8799. expressions.
  8800. The \code{explicate\_control} function itself is given in
  8801. figure~\ref{fig:explicate-control-Lif}. It applies
  8802. \code{explicate\_stmt} to each statement in the program, from back to
  8803. front. Thus, the result so-far, stored in \code{new\_body}, can be
  8804. used as the continuation parameter in the next call to
  8805. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8806. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8807. the dictionary of basic blocks, labeling it as the ``start'' block.
  8808. %
  8809. \fi}
  8810. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8811. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8812. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8813. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8814. %% results from the two recursive calls. We complete the case for
  8815. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8816. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8817. %% the result $B_5$.
  8818. %% \[
  8819. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8820. %% \quad\Rightarrow\quad
  8821. %% B_5
  8822. %% \]
  8823. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8824. %% inherit the current context, so they are in tail position. Thus, the
  8825. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8826. %% \code{explicate\_tail}.
  8827. %% %
  8828. %% We need to pass $B_0$ as the accumulator argument for both of these
  8829. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8830. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8831. %% to the control-flow graph and obtain a promised goto $G_0$.
  8832. %% %
  8833. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8834. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8835. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8836. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8837. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8838. %% \[
  8839. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8840. %% \]
  8841. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8842. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8843. %% should not be confused with the labels for the blocks that appear in
  8844. %% the generated code. We initially construct unlabeled blocks; we only
  8845. %% attach labels to blocks when we add them to the control-flow graph, as
  8846. %% we see in the next case.
  8847. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8848. %% function. The context of the \key{if} is an assignment to some
  8849. %% variable $x$ and then the control continues to some promised block
  8850. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8851. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8852. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8853. %% branches of the \key{if} inherit the current context, so they are in
  8854. %% assignment positions. Let $B_2$ be the result of applying
  8855. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8856. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8857. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8858. %% the result of applying \code{explicate\_pred} to the predicate
  8859. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8860. %% translates to the promise $B_4$.
  8861. %% \[
  8862. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8863. %% \]
  8864. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8865. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8866. \code{remove\_complex\_operands} pass and then the
  8867. \code{explicate\_control} pass on the example program. We walk through
  8868. the output program.
  8869. %
  8870. Following the order of evaluation in the output of
  8871. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8872. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8873. in the predicate of the inner \key{if}. In the output of
  8874. \code{explicate\_control}, in the
  8875. block labeled \code{start}, two assignment statements are followed by an
  8876. \code{if} statement that branches to \code{block\_4} or
  8877. \code{block\_5}. The blocks associated with those labels contain the
  8878. translations of the code
  8879. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8880. and
  8881. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8882. respectively. In particular, we start \code{block\_4} with the
  8883. comparison
  8884. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8885. and then branch to \code{block\_2} or \code{block\_3},
  8886. which correspond to the two branches of the outer \key{if}, that is,
  8887. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8888. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8889. %
  8890. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8891. %
  8892. \python{The \code{block\_1} corresponds to the \code{print} statement
  8893. at the end of the program.}
  8894. {\if\edition\racketEd
  8895. \subsection{Interactions between Explicate and Shrink}
  8896. The way in which the \code{shrink} pass transforms logical operations
  8897. such as \code{and} and \code{or} can impact the quality of code
  8898. generated by \code{explicate\_control}. For example, consider the
  8899. following program:
  8900. % cond_test_21.rkt, and_eq_input.py
  8901. \begin{lstlisting}
  8902. (if (and (eq? (read) 0) (eq? (read) 1))
  8903. 0
  8904. 42)
  8905. \end{lstlisting}
  8906. The \code{and} operation should transform into something that the
  8907. \code{explicate\_pred} function can analyze and descend through to
  8908. reach the underlying \code{eq?} conditions. Ideally, for this program
  8909. your \code{explicate\_control} pass should generate code similar to
  8910. the following:
  8911. \begin{center}
  8912. \begin{minipage}{\textwidth}
  8913. \begin{lstlisting}
  8914. start:
  8915. tmp1 = (read);
  8916. if (eq? tmp1 0) goto block40;
  8917. else goto block39;
  8918. block40:
  8919. tmp2 = (read);
  8920. if (eq? tmp2 1) goto block38;
  8921. else goto block39;
  8922. block38:
  8923. return 0;
  8924. block39:
  8925. return 42;
  8926. \end{lstlisting}
  8927. \end{minipage}
  8928. \end{center}
  8929. \fi}
  8930. \begin{exercise}\normalfont\normalsize
  8931. \racket{
  8932. Implement the pass \code{explicate\_control} by adding the cases for
  8933. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8934. \code{explicate\_assign} functions. Implement the auxiliary function
  8935. \code{explicate\_pred} for predicate contexts.}
  8936. \python{Implement \code{explicate\_control} pass with its
  8937. four auxiliary functions.}
  8938. %
  8939. Create test cases that exercise all the new cases in the code for
  8940. this pass.
  8941. %
  8942. {\if\edition\racketEd
  8943. Add the following entry to the list of \code{passes} in
  8944. \code{run-tests.rkt}:
  8945. \begin{lstlisting}
  8946. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8947. \end{lstlisting}
  8948. and then run \code{run-tests.rkt} to test your compiler.
  8949. \fi}
  8950. \end{exercise}
  8951. \section{Select Instructions}
  8952. \label{sec:select-Lif}
  8953. \index{subject}{select instructions}
  8954. The \code{select\_instructions} pass translates \LangCIf{} to
  8955. \LangXIfVar{}.
  8956. %
  8957. \racket{Recall that we implement this pass using three auxiliary
  8958. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8959. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8960. %
  8961. \racket{For $\Atm$, we have new cases for the Booleans.}
  8962. %
  8963. \python{We begin with the Boolean constants.}
  8964. We take the usual approach of encoding them as integers.
  8965. \[
  8966. \TRUE{} \quad\Rightarrow\quad \key{1}
  8967. \qquad\qquad
  8968. \FALSE{} \quad\Rightarrow\quad \key{0}
  8969. \]
  8970. For translating statements, we discuss some of the cases. The
  8971. \code{not} operation can be implemented in terms of \code{xorq}, as we
  8972. discussed at the beginning of this section. Given an assignment, if
  8973. the left-hand-side variable is the same as the argument of \code{not},
  8974. then just the \code{xorq} instruction suffices.
  8975. \[
  8976. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8977. \quad\Rightarrow\quad
  8978. \key{xorq}~\key{\$}1\key{,}~\Var
  8979. \]
  8980. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8981. semantics of x86. In the following translation, let $\Arg$ be the
  8982. result of translating $\Atm$ to x86.
  8983. \[
  8984. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8985. \quad\Rightarrow\quad
  8986. \begin{array}{l}
  8987. \key{movq}~\Arg\key{,}~\Var\\
  8988. \key{xorq}~\key{\$}1\key{,}~\Var
  8989. \end{array}
  8990. \]
  8991. Next consider the cases for equality comparisons. Translating this
  8992. operation to x86 is slightly involved due to the unusual nature of the
  8993. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8994. We recommend translating an assignment with an equality on the
  8995. right-hand side into a sequence of three instructions. \\
  8996. \begin{tabular}{lll}
  8997. \begin{minipage}{0.4\textwidth}
  8998. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8999. \end{minipage}
  9000. &
  9001. $\Rightarrow$
  9002. &
  9003. \begin{minipage}{0.4\textwidth}
  9004. \begin{lstlisting}
  9005. cmpq |$\Arg_2$|, |$\Arg_1$|
  9006. sete %al
  9007. movzbq %al, |$\Var$|
  9008. \end{lstlisting}
  9009. \end{minipage}
  9010. \end{tabular} \\
  9011. The translations for the other comparison operators are similar to
  9012. this but use different condition codes for the \code{set} instruction.
  9013. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9014. \key{goto} and \key{if} statements. Both are straightforward to
  9015. translate to x86.}
  9016. %
  9017. A \key{goto} statement becomes a jump instruction.
  9018. \[
  9019. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9020. \]
  9021. %
  9022. An \key{if} statement becomes a compare instruction followed by a
  9023. conditional jump (for the \emph{then} branch), and the fall-through is to
  9024. a regular jump (for the \emph{else} branch).\\
  9025. \begin{tabular}{lll}
  9026. \begin{minipage}{0.4\textwidth}
  9027. \begin{lstlisting}
  9028. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9029. goto |$\ell_1$||$\racket{\key{;}}$|
  9030. else|$\python{\key{:}}$|
  9031. goto |$\ell_2$||$\racket{\key{;}}$|
  9032. \end{lstlisting}
  9033. \end{minipage}
  9034. &
  9035. $\Rightarrow$
  9036. &
  9037. \begin{minipage}{0.4\textwidth}
  9038. \begin{lstlisting}
  9039. cmpq |$\Arg_2$|, |$\Arg_1$|
  9040. je |$\ell_1$|
  9041. jmp |$\ell_2$|
  9042. \end{lstlisting}
  9043. \end{minipage}
  9044. \end{tabular} \\
  9045. Again, the translations for the other comparison operators are similar to this
  9046. but use different condition codes for the conditional jump instruction.
  9047. \python{Regarding the \key{return} statement, we recommend treating it
  9048. as an assignment to the \key{rax} register followed by a jump to the
  9049. conclusion of the \code{main} function.}
  9050. \begin{exercise}\normalfont\normalsize
  9051. Expand your \code{select\_instructions} pass to handle the new
  9052. features of the \LangCIf{} language.
  9053. %
  9054. {\if\edition\racketEd
  9055. Add the following entry to the list of \code{passes} in
  9056. \code{run-tests.rkt}
  9057. \begin{lstlisting}
  9058. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9059. \end{lstlisting}
  9060. \fi}
  9061. %
  9062. Run the script to test your compiler on all the test programs.
  9063. \end{exercise}
  9064. \section{Register Allocation}
  9065. \label{sec:register-allocation-Lif}
  9066. \index{subject}{register allocation}
  9067. The changes required for compiling \LangIf{} affect liveness analysis,
  9068. building the interference graph, and assigning homes, but the graph
  9069. coloring algorithm itself does not change.
  9070. \subsection{Liveness Analysis}
  9071. \label{sec:liveness-analysis-Lif}
  9072. \index{subject}{liveness analysis}
  9073. Recall that for \LangVar{} we implemented liveness analysis for a
  9074. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9075. the addition of \key{if} expressions to \LangIf{},
  9076. \code{explicate\_control} produces many basic blocks.
  9077. %% We recommend that you create a new auxiliary function named
  9078. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9079. %% control-flow graph.
  9080. The first question is, in what order should we process the basic blocks?
  9081. Recall that to perform liveness analysis on a basic block we need to
  9082. know the live-after set for the last instruction in the block. If a
  9083. basic block has no successors (i.e., contains no jumps to other
  9084. blocks), then it has an empty live-after set and we can immediately
  9085. apply liveness analysis to it. If a basic block has some successors,
  9086. then we need to complete liveness analysis on those blocks
  9087. first. These ordering constraints are the reverse of a
  9088. \emph{topological order}\index{subject}{topological order} on a graph
  9089. representation of the program. In particular, the \emph{control flow
  9090. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9091. of a program has a node for each basic block and an edge for each jump
  9092. from one block to another. It is straightforward to generate a CFG
  9093. from the dictionary of basic blocks. One then transposes the CFG and
  9094. applies the topological sort algorithm.
  9095. %
  9096. %
  9097. \racket{We recommend using the \code{tsort} and \code{transpose}
  9098. functions of the Racket \code{graph} package to accomplish this.}
  9099. %
  9100. \python{We provide implementations of \code{topological\_sort} and
  9101. \code{transpose} in the file \code{graph.py} of the support code.}
  9102. %
  9103. As an aside, a topological ordering is only guaranteed to exist if the
  9104. graph does not contain any cycles. This is the case for the
  9105. control-flow graphs that we generate from \LangIf{} programs.
  9106. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9107. and learn how to handle cycles in the control-flow graph.
  9108. \racket{You need to construct a directed graph to represent the
  9109. control-flow graph. Do not use the \code{directed-graph} of the
  9110. \code{graph} package because that allows at most one edge
  9111. between each pair of vertices, whereas a control-flow graph may have
  9112. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9113. file in the support code implements a graph representation that
  9114. allows multiple edges between a pair of vertices.}
  9115. {\if\edition\racketEd
  9116. The next question is how to analyze jump instructions. Recall that in
  9117. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9118. \code{label->live} that maps each label to the set of live locations
  9119. at the beginning of its block. We use \code{label->live} to determine
  9120. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9121. that we have many basic blocks, \code{label->live} needs to be updated
  9122. as we process the blocks. In particular, after performing liveness
  9123. analysis on a block, we take the live-before set of its first
  9124. instruction and associate that with the block's label in the
  9125. \code{label->live} alist.
  9126. \fi}
  9127. %
  9128. {\if\edition\pythonEd\pythonColor
  9129. %
  9130. The next question is how to analyze jump instructions. The locations
  9131. that are live before a \code{jmp} should be the locations in
  9132. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9133. maintaining a dictionary named \code{live\_before\_block} that maps each
  9134. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9135. block. After performing liveness analysis on each block, we take the
  9136. live-before set of its first instruction and associate that with the
  9137. block's label in the \code{live\_before\_block} dictionary.
  9138. %
  9139. \fi}
  9140. In \LangXIfVar{} we also have the conditional jump
  9141. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9142. this instruction is particularly interesting because during
  9143. compilation, we do not know which way a conditional jump will go. Thus
  9144. we do not know whether to use the live-before set for the block
  9145. associated with the $\itm{label}$ or the live-before set for the
  9146. following instruction. However, there is no harm to the correctness
  9147. of the generated code if we classify more locations as live than the
  9148. ones that are truly live during one particular execution of the
  9149. instruction. Thus, we can take the union of the live-before sets from
  9150. the following instruction and from the mapping for $\itm{label}$ in
  9151. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9152. The auxiliary functions for computing the variables in an
  9153. instruction's argument and for computing the variables read-from ($R$)
  9154. or written-to ($W$) by an instruction need to be updated to handle the
  9155. new kinds of arguments and instructions in \LangXIfVar{}.
  9156. \begin{exercise}\normalfont\normalsize
  9157. {\if\edition\racketEd
  9158. %
  9159. Update the \code{uncover\_live} pass to apply liveness analysis to
  9160. every basic block in the program.
  9161. %
  9162. Add the following entry to the list of \code{passes} in the
  9163. \code{run-tests.rkt} script:
  9164. \begin{lstlisting}
  9165. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9166. \end{lstlisting}
  9167. \fi}
  9168. {\if\edition\pythonEd\pythonColor
  9169. %
  9170. Update the \code{uncover\_live} function to perform liveness analysis,
  9171. in reverse topological order, on all the basic blocks in the
  9172. program.
  9173. %
  9174. \fi}
  9175. % Check that the live-after sets that you generate for
  9176. % example X matches the following... -Jeremy
  9177. \end{exercise}
  9178. \subsection{Build the Interference Graph}
  9179. \label{sec:build-interference-Lif}
  9180. Many of the new instructions in \LangXIfVar{} can be handled in the
  9181. same way as the instructions in \LangXVar{}.
  9182. % Thus, if your code was
  9183. % already quite general, it will not need to be changed to handle the
  9184. % new instructions. If your code is not general enough, we recommend that
  9185. % you change your code to be more general. For example, you can factor
  9186. % out the computing of the the read and write sets for each kind of
  9187. % instruction into auxiliary functions.
  9188. %
  9189. Some instructions, such as the \key{movzbq} instruction, require special care,
  9190. similar to the \key{movq} instruction. Refer to rule number 1 in
  9191. section~\ref{sec:build-interference}.
  9192. \begin{exercise}\normalfont\normalsize
  9193. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9194. {\if\edition\racketEd
  9195. Add the following entries to the list of \code{passes} in the
  9196. \code{run-tests.rkt} script:
  9197. \begin{lstlisting}
  9198. (list "build_interference" build_interference interp-pseudo-x86-1)
  9199. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9200. \end{lstlisting}
  9201. \fi}
  9202. % Check that the interference graph that you generate for
  9203. % example X matches the following graph G... -Jeremy
  9204. \end{exercise}
  9205. \section{Patch Instructions}
  9206. The new instructions \key{cmpq} and \key{movzbq} have some special
  9207. restrictions that need to be handled in the \code{patch\_instructions}
  9208. pass.
  9209. %
  9210. The second argument of the \key{cmpq} instruction must not be an
  9211. immediate value (such as an integer). So, if you are comparing two
  9212. immediates, we recommend inserting a \key{movq} instruction to put the
  9213. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  9214. one memory reference.
  9215. %
  9216. The second argument of the \key{movzbq} must be a register.
  9217. \begin{exercise}\normalfont\normalsize
  9218. %
  9219. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9220. %
  9221. {\if\edition\racketEd
  9222. Add the following entry to the list of \code{passes} in
  9223. \code{run-tests.rkt}, and then run this script to test your compiler.
  9224. \begin{lstlisting}
  9225. (list "patch_instructions" patch_instructions interp-x86-1)
  9226. \end{lstlisting}
  9227. \fi}
  9228. \end{exercise}
  9229. {\if\edition\pythonEd\pythonColor
  9230. \section{Prelude and Conclusion}
  9231. \label{sec:prelude-conclusion-cond}
  9232. The generation of the \code{main} function with its prelude and
  9233. conclusion must change to accommodate how the program now consists of
  9234. one or more basic blocks. After the prelude in \code{main}, jump to
  9235. the \code{start} block. Place the conclusion in a basic block labeled
  9236. with \code{conclusion}.
  9237. \fi}
  9238. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9239. \LangIf{} translated to x86, showing the results of
  9240. \code{explicate\_control}, \code{select\_instructions}, and the final
  9241. x86 assembly.
  9242. \begin{figure}[tbp]
  9243. \begin{tcolorbox}[colback=white]
  9244. {\if\edition\racketEd
  9245. \begin{tabular}{lll}
  9246. \begin{minipage}{0.4\textwidth}
  9247. % cond_test_20.rkt, eq_input.py
  9248. \begin{lstlisting}
  9249. (if (eq? (read) 1) 42 0)
  9250. \end{lstlisting}
  9251. $\Downarrow$
  9252. \begin{lstlisting}
  9253. start:
  9254. tmp7951 = (read);
  9255. if (eq? tmp7951 1)
  9256. goto block7952;
  9257. else
  9258. goto block7953;
  9259. block7952:
  9260. return 42;
  9261. block7953:
  9262. return 0;
  9263. \end{lstlisting}
  9264. $\Downarrow$
  9265. \begin{lstlisting}
  9266. start:
  9267. callq read_int
  9268. movq %rax, tmp7951
  9269. cmpq $1, tmp7951
  9270. je block7952
  9271. jmp block7953
  9272. block7953:
  9273. movq $0, %rax
  9274. jmp conclusion
  9275. block7952:
  9276. movq $42, %rax
  9277. jmp conclusion
  9278. \end{lstlisting}
  9279. \end{minipage}
  9280. &
  9281. $\Rightarrow\qquad$
  9282. \begin{minipage}{0.4\textwidth}
  9283. \begin{lstlisting}
  9284. start:
  9285. callq read_int
  9286. movq %rax, %rcx
  9287. cmpq $1, %rcx
  9288. je block7952
  9289. jmp block7953
  9290. block7953:
  9291. movq $0, %rax
  9292. jmp conclusion
  9293. block7952:
  9294. movq $42, %rax
  9295. jmp conclusion
  9296. .globl main
  9297. main:
  9298. pushq %rbp
  9299. movq %rsp, %rbp
  9300. pushq %r13
  9301. pushq %r12
  9302. pushq %rbx
  9303. pushq %r14
  9304. subq $0, %rsp
  9305. jmp start
  9306. conclusion:
  9307. addq $0, %rsp
  9308. popq %r14
  9309. popq %rbx
  9310. popq %r12
  9311. popq %r13
  9312. popq %rbp
  9313. retq
  9314. \end{lstlisting}
  9315. \end{minipage}
  9316. \end{tabular}
  9317. \fi}
  9318. {\if\edition\pythonEd\pythonColor
  9319. \begin{tabular}{lll}
  9320. \begin{minipage}{0.4\textwidth}
  9321. % cond_test_20.rkt, eq_input.py
  9322. \begin{lstlisting}
  9323. print(42 if input_int() == 1 else 0)
  9324. \end{lstlisting}
  9325. $\Downarrow$
  9326. \begin{lstlisting}
  9327. start:
  9328. tmp_0 = input_int()
  9329. if tmp_0 == 1:
  9330. goto block_3
  9331. else:
  9332. goto block_4
  9333. block_3:
  9334. tmp_1 = 42
  9335. goto block_2
  9336. block_4:
  9337. tmp_1 = 0
  9338. goto block_2
  9339. block_2:
  9340. print(tmp_1)
  9341. return 0
  9342. \end{lstlisting}
  9343. $\Downarrow$
  9344. \begin{lstlisting}
  9345. start:
  9346. callq read_int
  9347. movq %rax, tmp_0
  9348. cmpq 1, tmp_0
  9349. je block_3
  9350. jmp block_4
  9351. block_3:
  9352. movq 42, tmp_1
  9353. jmp block_2
  9354. block_4:
  9355. movq 0, tmp_1
  9356. jmp block_2
  9357. block_2:
  9358. movq tmp_1, %rdi
  9359. callq print_int
  9360. movq 0, %rax
  9361. jmp conclusion
  9362. \end{lstlisting}
  9363. \end{minipage}
  9364. &
  9365. $\Rightarrow\qquad$
  9366. \begin{minipage}{0.4\textwidth}
  9367. \begin{lstlisting}
  9368. .globl main
  9369. main:
  9370. pushq %rbp
  9371. movq %rsp, %rbp
  9372. subq $0, %rsp
  9373. jmp start
  9374. start:
  9375. callq read_int
  9376. movq %rax, %rcx
  9377. cmpq $1, %rcx
  9378. je block_3
  9379. jmp block_4
  9380. block_3:
  9381. movq $42, %rcx
  9382. jmp block_2
  9383. block_4:
  9384. movq $0, %rcx
  9385. jmp block_2
  9386. block_2:
  9387. movq %rcx, %rdi
  9388. callq print_int
  9389. movq $0, %rax
  9390. jmp conclusion
  9391. conclusion:
  9392. addq $0, %rsp
  9393. popq %rbp
  9394. retq
  9395. \end{lstlisting}
  9396. \end{minipage}
  9397. \end{tabular}
  9398. \fi}
  9399. \end{tcolorbox}
  9400. \caption{Example compilation of an \key{if} expression to x86, showing
  9401. the results of \code{explicate\_control},
  9402. \code{select\_instructions}, and the final x86 assembly code. }
  9403. \label{fig:if-example-x86}
  9404. \end{figure}
  9405. \begin{figure}[tbp]
  9406. \begin{tcolorbox}[colback=white]
  9407. {\if\edition\racketEd
  9408. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9409. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9410. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9411. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9412. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9413. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9414. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9415. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9416. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9417. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9418. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9419. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9420. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9421. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9422. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9423. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9424. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9425. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9426. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9427. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9428. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9429. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9430. \end{tikzpicture}
  9431. \fi}
  9432. {\if\edition\pythonEd\pythonColor
  9433. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9434. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9435. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9436. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9437. \node (C-1) at (0,0) {\large \LangCIf{}};
  9438. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9439. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9440. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9441. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9442. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9443. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9444. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9445. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9446. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9447. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9448. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9449. \end{tikzpicture}
  9450. \fi}
  9451. \end{tcolorbox}
  9452. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9453. \label{fig:Lif-passes}
  9454. \end{figure}
  9455. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9456. compilation of \LangIf{}.
  9457. \section{Challenge: Optimize Blocks and Remove Jumps}
  9458. \label{sec:opt-jumps}
  9459. We discuss two optional challenges that involve optimizing the
  9460. control-flow of the program.
  9461. \subsection{Optimize Blocks}
  9462. The algorithm for \code{explicate\_control} that we discussed in
  9463. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9464. blocks. It creates a basic block whenever a continuation \emph{might}
  9465. get used more than once (for example, whenever the \code{cont} parameter is
  9466. passed into two or more recursive calls). However, some continuation
  9467. arguments may not be used at all. For example, consider the case for
  9468. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  9469. \code{els} continuation.
  9470. %
  9471. {\if\edition\racketEd
  9472. The following example program falls into this
  9473. case, and it creates two unused blocks.
  9474. \begin{center}
  9475. \begin{tabular}{lll}
  9476. \begin{minipage}{0.4\textwidth}
  9477. % cond_test_82.rkt
  9478. \begin{lstlisting}
  9479. (let ([y (if #t
  9480. (read)
  9481. (if (eq? (read) 0)
  9482. 777
  9483. (let ([x (read)])
  9484. (+ 1 x))))])
  9485. (+ y 2))
  9486. \end{lstlisting}
  9487. \end{minipage}
  9488. &
  9489. $\Rightarrow$
  9490. &
  9491. \begin{minipage}{0.55\textwidth}
  9492. \begin{lstlisting}
  9493. start:
  9494. y = (read);
  9495. goto block_5;
  9496. block_5:
  9497. return (+ y 2);
  9498. block_6:
  9499. y = 777;
  9500. goto block_5;
  9501. block_7:
  9502. x = (read);
  9503. y = (+ 1 x2);
  9504. goto block_5;
  9505. \end{lstlisting}
  9506. \end{minipage}
  9507. \end{tabular}
  9508. \end{center}
  9509. \fi}
  9510. The question is, how can we decide whether to create a basic block?
  9511. \emph{Lazy evaluation}\index{subject}{lazy
  9512. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9513. delaying the creation of a basic block until the point in time at which
  9514. we know that it will be used.
  9515. %
  9516. {\if\edition\racketEd
  9517. %
  9518. Racket provides support for
  9519. lazy evaluation with the
  9520. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9521. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9522. \index{subject}{delay} creates a
  9523. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9524. expressions is postponed. When \key{(force}
  9525. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9526. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9527. result of $e_n$ is cached in the promise and returned. If \code{force}
  9528. is applied again to the same promise, then the cached result is
  9529. returned. If \code{force} is applied to an argument that is not a
  9530. promise, \code{force} simply returns the argument.
  9531. %
  9532. \fi}
  9533. %
  9534. {\if\edition\pythonEd\pythonColor
  9535. %
  9536. While Python does not provide direct support for lazy evaluation, it
  9537. is easy to mimic. We can \emph{delay} the evaluation of a computation
  9538. by wrapping it inside a function with no parameters. We can
  9539. \emph{force} its evaluation by calling the function. However, in some
  9540. cases of \code{explicate\_pred}, etc., we will return a list of
  9541. statements and in other cases we will return a function that computes
  9542. a list of statements. We use the term \emph{promise} to refer to a
  9543. value that may be delayed. To uniformly deal with
  9544. promises, we define the following \code{force} function that checks
  9545. whether its input is delayed (i.e., whether it is a function) and then
  9546. either 1) calls the function, or 2) returns the input.
  9547. \begin{lstlisting}
  9548. def force(promise):
  9549. if isinstance(promise, types.FunctionType):
  9550. return promise()
  9551. else:
  9552. return promise
  9553. \end{lstlisting}
  9554. %
  9555. \fi}
  9556. We use promises for the input and output of the functions
  9557. \code{explicate\_pred}, \code{explicate\_assign},
  9558. %
  9559. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9560. %
  9561. So, instead of taking and returning \racket{$\Tail$
  9562. expressions}\python{lists of statements}, they take and return
  9563. promises. Furthermore, when we come to a situation in which a
  9564. continuation might be used more than once, as in the case for
  9565. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9566. that creates a basic block for each continuation (if there is not
  9567. already one) and then returns a \code{goto} statement to that basic
  9568. block. When we come to a situation in which we have a promise but need an
  9569. actual piece of code, for example, to create a larger piece of code with a
  9570. constructor such as \code{Seq}, then insert a call to \code{force}.
  9571. %
  9572. {\if\edition\racketEd
  9573. %
  9574. Also, we must modify the \code{create\_block} function to begin with
  9575. \code{delay} to create a promise. When forced, this promise forces the
  9576. original promise. If that returns a \code{Goto} (because the block was
  9577. already added to \code{basic-blocks}), then we return the
  9578. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9579. return a \code{Goto} to the new label.
  9580. \begin{center}
  9581. \begin{minipage}{\textwidth}
  9582. \begin{lstlisting}
  9583. (define (create_block tail)
  9584. (delay
  9585. (define t (force tail))
  9586. (match t
  9587. [(Goto label) (Goto label)]
  9588. [else
  9589. (let ([label (gensym 'block)])
  9590. (set! basic-blocks (cons (cons label t) basic-blocks))
  9591. (Goto label))])))
  9592. \end{lstlisting}
  9593. \end{minipage}
  9594. \end{center}
  9595. \fi}
  9596. {\if\edition\pythonEd\pythonColor
  9597. %
  9598. Here is the new version of the \code{create\_block} auxiliary function
  9599. that works on promises and that checks whether the block consists of a
  9600. solitary \code{goto} statement.\\
  9601. \begin{minipage}{\textwidth}
  9602. \begin{lstlisting}
  9603. def create_block(promise, basic_blocks):
  9604. stmts = force(promise)
  9605. match stmts:
  9606. case [Goto(l)]:
  9607. return Goto(l)
  9608. case _:
  9609. label = label_name(generate_name('block'))
  9610. basic_blocks[label] = stmts
  9611. return Goto(label)
  9612. \end{lstlisting}
  9613. \end{minipage}
  9614. \fi}
  9615. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9616. improved \code{explicate\_control} on this example. As you can
  9617. see, the number of basic blocks has been reduced from four blocks (see
  9618. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9619. \begin{figure}[tbp]
  9620. \begin{tcolorbox}[colback=white]
  9621. {\if\edition\racketEd
  9622. \begin{tabular}{lll}
  9623. \begin{minipage}{0.4\textwidth}
  9624. % cond_test_82.rkt
  9625. \begin{lstlisting}
  9626. (let ([y (if #t
  9627. (read)
  9628. (if (eq? (read) 0)
  9629. 777
  9630. (let ([x (read)])
  9631. (+ 1 x))))])
  9632. (+ y 2))
  9633. \end{lstlisting}
  9634. \end{minipage}
  9635. &
  9636. $\Rightarrow$
  9637. &
  9638. \begin{minipage}{0.55\textwidth}
  9639. \begin{lstlisting}
  9640. start:
  9641. y = (read);
  9642. goto block_5;
  9643. block_5:
  9644. return (+ y 2);
  9645. \end{lstlisting}
  9646. \end{minipage}
  9647. \end{tabular}
  9648. \fi}
  9649. {\if\edition\pythonEd\pythonColor
  9650. \begin{tabular}{lll}
  9651. \begin{minipage}{0.4\textwidth}
  9652. % cond_test_41.rkt
  9653. \begin{lstlisting}
  9654. x = input_int()
  9655. y = input_int()
  9656. print(y + 2 \
  9657. if (x == 0 \
  9658. if x < 1 \
  9659. else x == 2) \
  9660. else y + 10)
  9661. \end{lstlisting}
  9662. \end{minipage}
  9663. &
  9664. $\Rightarrow$
  9665. &
  9666. \begin{minipage}{0.55\textwidth}
  9667. \begin{lstlisting}
  9668. start:
  9669. x = input_int()
  9670. y = input_int()
  9671. if x < 1:
  9672. goto block_4
  9673. else:
  9674. goto block_5
  9675. block_4:
  9676. if x == 0:
  9677. goto block_2
  9678. else:
  9679. goto block_3
  9680. block_5:
  9681. if x == 2:
  9682. goto block_2
  9683. else:
  9684. goto block_3
  9685. block_2:
  9686. tmp_0 = y + 2
  9687. goto block_1
  9688. block_3:
  9689. tmp_0 = y + 10
  9690. goto block_1
  9691. block_1:
  9692. print(tmp_0)
  9693. return 0
  9694. \end{lstlisting}
  9695. \end{minipage}
  9696. \end{tabular}
  9697. \fi}
  9698. \end{tcolorbox}
  9699. \caption{Translation from \LangIf{} to \LangCIf{}
  9700. via the improved \code{explicate\_control}.}
  9701. \label{fig:explicate-control-challenge}
  9702. \end{figure}
  9703. %% Recall that in the example output of \code{explicate\_control} in
  9704. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9705. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9706. %% block. The first goal of this challenge assignment is to remove those
  9707. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9708. %% \code{explicate\_control} on the left and shows the result of bypassing
  9709. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9710. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9711. %% \code{block55}. The optimized code on the right of
  9712. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9713. %% \code{then} branch jumping directly to \code{block55}. The story is
  9714. %% similar for the \code{else} branch, as well as for the two branches in
  9715. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9716. %% have been optimized in this way, there are no longer any jumps to
  9717. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9718. %% \begin{figure}[tbp]
  9719. %% \begin{tabular}{lll}
  9720. %% \begin{minipage}{0.4\textwidth}
  9721. %% \begin{lstlisting}
  9722. %% block62:
  9723. %% tmp54 = (read);
  9724. %% if (eq? tmp54 2) then
  9725. %% goto block59;
  9726. %% else
  9727. %% goto block60;
  9728. %% block61:
  9729. %% tmp53 = (read);
  9730. %% if (eq? tmp53 0) then
  9731. %% goto block57;
  9732. %% else
  9733. %% goto block58;
  9734. %% block60:
  9735. %% goto block56;
  9736. %% block59:
  9737. %% goto block55;
  9738. %% block58:
  9739. %% goto block56;
  9740. %% block57:
  9741. %% goto block55;
  9742. %% block56:
  9743. %% return (+ 700 77);
  9744. %% block55:
  9745. %% return (+ 10 32);
  9746. %% start:
  9747. %% tmp52 = (read);
  9748. %% if (eq? tmp52 1) then
  9749. %% goto block61;
  9750. %% else
  9751. %% goto block62;
  9752. %% \end{lstlisting}
  9753. %% \end{minipage}
  9754. %% &
  9755. %% $\Rightarrow$
  9756. %% &
  9757. %% \begin{minipage}{0.55\textwidth}
  9758. %% \begin{lstlisting}
  9759. %% block62:
  9760. %% tmp54 = (read);
  9761. %% if (eq? tmp54 2) then
  9762. %% goto block55;
  9763. %% else
  9764. %% goto block56;
  9765. %% block61:
  9766. %% tmp53 = (read);
  9767. %% if (eq? tmp53 0) then
  9768. %% goto block55;
  9769. %% else
  9770. %% goto block56;
  9771. %% block56:
  9772. %% return (+ 700 77);
  9773. %% block55:
  9774. %% return (+ 10 32);
  9775. %% start:
  9776. %% tmp52 = (read);
  9777. %% if (eq? tmp52 1) then
  9778. %% goto block61;
  9779. %% else
  9780. %% goto block62;
  9781. %% \end{lstlisting}
  9782. %% \end{minipage}
  9783. %% \end{tabular}
  9784. %% \caption{Optimize jumps by removing trivial blocks.}
  9785. %% \label{fig:optimize-jumps}
  9786. %% \end{figure}
  9787. %% The name of this pass is \code{optimize-jumps}. We recommend
  9788. %% implementing this pass in two phases. The first phrase builds a hash
  9789. %% table that maps labels to possibly improved labels. The second phase
  9790. %% changes the target of each \code{goto} to use the improved label. If
  9791. %% the label is for a trivial block, then the hash table should map the
  9792. %% label to the first non-trivial block that can be reached from this
  9793. %% label by jumping through trivial blocks. If the label is for a
  9794. %% non-trivial block, then the hash table should map the label to itself;
  9795. %% we do not want to change jumps to non-trivial blocks.
  9796. %% The first phase can be accomplished by constructing an empty hash
  9797. %% table, call it \code{short-cut}, and then iterating over the control
  9798. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9799. %% then update the hash table, mapping the block's source to the target
  9800. %% of the \code{goto}. Also, the hash table may already have mapped some
  9801. %% labels to the block's source, to you must iterate through the hash
  9802. %% table and update all of those so that they instead map to the target
  9803. %% of the \code{goto}.
  9804. %% For the second phase, we recommend iterating through the $\Tail$ of
  9805. %% each block in the program, updating the target of every \code{goto}
  9806. %% according to the mapping in \code{short-cut}.
  9807. \begin{exercise}\normalfont\normalsize
  9808. Implement the improvements to the \code{explicate\_control} pass.
  9809. Check that it removes trivial blocks in a few example programs. Then
  9810. check that your compiler still passes all your tests.
  9811. \end{exercise}
  9812. \subsection{Remove Jumps}
  9813. There is an opportunity for removing jumps that is apparent in the
  9814. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9815. ends with a jump to \code{block\_5}, and there are no other jumps to
  9816. \code{block\_5} in the rest of the program. In this situation we can
  9817. avoid the runtime overhead of this jump by merging \code{block\_5}
  9818. into the preceding block, which in this case is the \code{start} block.
  9819. Figure~\ref{fig:remove-jumps} shows the output of
  9820. \code{allocate\_registers} on the left and the result of this
  9821. optimization on the right.
  9822. \begin{figure}[tbp]
  9823. \begin{tcolorbox}[colback=white]
  9824. {\if\edition\racketEd
  9825. \begin{tabular}{lll}
  9826. \begin{minipage}{0.5\textwidth}
  9827. % cond_test_82.rkt
  9828. \begin{lstlisting}
  9829. start:
  9830. callq read_int
  9831. movq %rax, %rcx
  9832. jmp block_5
  9833. block_5:
  9834. movq %rcx, %rax
  9835. addq $2, %rax
  9836. jmp conclusion
  9837. \end{lstlisting}
  9838. \end{minipage}
  9839. &
  9840. $\Rightarrow\qquad$
  9841. \begin{minipage}{0.4\textwidth}
  9842. \begin{lstlisting}
  9843. start:
  9844. callq read_int
  9845. movq %rax, %rcx
  9846. movq %rcx, %rax
  9847. addq $2, %rax
  9848. jmp conclusion
  9849. \end{lstlisting}
  9850. \end{minipage}
  9851. \end{tabular}
  9852. \fi}
  9853. {\if\edition\pythonEd\pythonColor
  9854. \begin{tabular}{lll}
  9855. \begin{minipage}{0.5\textwidth}
  9856. % cond_test_20.rkt
  9857. \begin{lstlisting}
  9858. start:
  9859. callq read_int
  9860. movq %rax, tmp_0
  9861. cmpq 1, tmp_0
  9862. je block_3
  9863. jmp block_4
  9864. block_3:
  9865. movq 42, tmp_1
  9866. jmp block_2
  9867. block_4:
  9868. movq 0, tmp_1
  9869. jmp block_2
  9870. block_2:
  9871. movq tmp_1, %rdi
  9872. callq print_int
  9873. movq 0, %rax
  9874. jmp conclusion
  9875. \end{lstlisting}
  9876. \end{minipage}
  9877. &
  9878. $\Rightarrow\qquad$
  9879. \begin{minipage}{0.4\textwidth}
  9880. \begin{lstlisting}
  9881. start:
  9882. callq read_int
  9883. movq %rax, tmp_0
  9884. cmpq 1, tmp_0
  9885. je block_3
  9886. movq 0, tmp_1
  9887. jmp block_2
  9888. block_3:
  9889. movq 42, tmp_1
  9890. jmp block_2
  9891. block_2:
  9892. movq tmp_1, %rdi
  9893. callq print_int
  9894. movq 0, %rax
  9895. jmp conclusion
  9896. \end{lstlisting}
  9897. \end{minipage}
  9898. \end{tabular}
  9899. \fi}
  9900. \end{tcolorbox}
  9901. \caption{Merging basic blocks by removing unnecessary jumps.}
  9902. \label{fig:remove-jumps}
  9903. \end{figure}
  9904. \begin{exercise}\normalfont\normalsize
  9905. %
  9906. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9907. into their preceding basic block, when there is only one preceding
  9908. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9909. %
  9910. {\if\edition\racketEd
  9911. In the \code{run-tests.rkt} script, add the following entry to the
  9912. list of \code{passes} between \code{allocate\_registers}
  9913. and \code{patch\_instructions}:
  9914. \begin{lstlisting}
  9915. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9916. \end{lstlisting}
  9917. \fi}
  9918. %
  9919. Run the script to test your compiler.
  9920. %
  9921. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9922. blocks on several test programs.
  9923. \end{exercise}
  9924. \section{Further Reading}
  9925. \label{sec:cond-further-reading}
  9926. The algorithm for the \code{explicate\_control} pass is based on the
  9927. \code{expose-basic-blocks} pass in the course notes of
  9928. \citet{Dybvig:2010aa}.
  9929. %
  9930. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9931. \citet{Appel:2003fk}, and is related to translations into continuation
  9932. passing
  9933. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9934. %
  9935. The treatment of conditionals in the \code{explicate\_control} pass is
  9936. similar to short-cut Boolean
  9937. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9938. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9939. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9940. \chapter{Loops and Dataflow Analysis}
  9941. \label{ch:Lwhile}
  9942. \setcounter{footnote}{0}
  9943. % TODO: define R'_8
  9944. % TODO: multi-graph
  9945. {\if\edition\racketEd
  9946. %
  9947. In this chapter we study two features that are the hallmarks of
  9948. imperative programming languages: loops and assignments to local
  9949. variables. The following example demonstrates these new features by
  9950. computing the sum of the first five positive integers:
  9951. % similar to loop_test_1.rkt
  9952. \begin{lstlisting}
  9953. (let ([sum 0])
  9954. (let ([i 5])
  9955. (begin
  9956. (while (> i 0)
  9957. (begin
  9958. (set! sum (+ sum i))
  9959. (set! i (- i 1))))
  9960. sum)))
  9961. \end{lstlisting}
  9962. The \code{while} loop consists of a condition and a
  9963. body.\footnote{The \code{while} loop is not a built-in
  9964. feature of the Racket language, but Racket includes many looping
  9965. constructs and it is straightforward to define \code{while} as a
  9966. macro.} The body is evaluated repeatedly so long as the condition
  9967. remains true.
  9968. %
  9969. The \code{set!} consists of a variable and a right-hand side
  9970. expression. The \code{set!} updates value of the variable to the
  9971. value of the right-hand side.
  9972. %
  9973. The primary purpose of both the \code{while} loop and \code{set!} is
  9974. to cause side effects, so they do not give a meaningful result
  9975. value. Instead, their result is the \code{\#<void>} value. The
  9976. expression \code{(void)} is an explicit way to create the
  9977. \code{\#<void>} value, and it has type \code{Void}. The
  9978. \code{\#<void>} value can be passed around just like other values
  9979. inside an \LangLoop{} program, and it can be compared for equality with
  9980. another \code{\#<void>} value. However, there are no other operations
  9981. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  9982. Racket defines the \code{void?} predicate that returns \code{\#t}
  9983. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9984. %
  9985. \footnote{Racket's \code{Void} type corresponds to what is often
  9986. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9987. by a single value \code{\#<void>}, which corresponds to \code{unit}
  9988. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  9989. %
  9990. With the addition of side effect-producing features such as
  9991. \code{while} loop and \code{set!}, it is helpful to include a language
  9992. feature for sequencing side effects: the \code{begin} expression. It
  9993. consists of one or more subexpressions that are evaluated
  9994. left to right.
  9995. %
  9996. \fi}
  9997. {\if\edition\pythonEd\pythonColor
  9998. %
  9999. In this chapter we study loops, one of the hallmarks of imperative
  10000. programming languages. The following example demonstrates the
  10001. \code{while} loop by computing the sum of the first five positive
  10002. integers.
  10003. \begin{lstlisting}
  10004. sum = 0
  10005. i = 5
  10006. while i > 0:
  10007. sum = sum + i
  10008. i = i - 1
  10009. print(sum)
  10010. \end{lstlisting}
  10011. The \code{while} loop consists of a condition expression and a body (a
  10012. sequence of statements). The body is evaluated repeatedly so long as
  10013. the condition remains true.
  10014. %
  10015. \fi}
  10016. \section{The \LangLoop{} Language}
  10017. \newcommand{\LwhileGrammarRacket}{
  10018. \begin{array}{lcl}
  10019. \Type &::=& \key{Void}\\
  10020. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10021. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10022. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10023. \end{array}
  10024. }
  10025. \newcommand{\LwhileASTRacket}{
  10026. \begin{array}{lcl}
  10027. \Type &::=& \key{Void}\\
  10028. \Exp &::=& \SETBANG{\Var}{\Exp}
  10029. \MID \BEGIN{\Exp^{*}}{\Exp}
  10030. \MID \WHILE{\Exp}{\Exp}
  10031. \MID \VOID{}
  10032. \end{array}
  10033. }
  10034. \newcommand{\LwhileGrammarPython}{
  10035. \begin{array}{rcl}
  10036. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10037. \end{array}
  10038. }
  10039. \newcommand{\LwhileASTPython}{
  10040. \begin{array}{lcl}
  10041. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10042. \end{array}
  10043. }
  10044. \begin{figure}[tp]
  10045. \centering
  10046. \begin{tcolorbox}[colback=white]
  10047. \small
  10048. {\if\edition\racketEd
  10049. \[
  10050. \begin{array}{l}
  10051. \gray{\LintGrammarRacket{}} \\ \hline
  10052. \gray{\LvarGrammarRacket{}} \\ \hline
  10053. \gray{\LifGrammarRacket{}} \\ \hline
  10054. \LwhileGrammarRacket \\
  10055. \begin{array}{lcl}
  10056. \LangLoopM{} &::=& \Exp
  10057. \end{array}
  10058. \end{array}
  10059. \]
  10060. \fi}
  10061. {\if\edition\pythonEd\pythonColor
  10062. \[
  10063. \begin{array}{l}
  10064. \gray{\LintGrammarPython} \\ \hline
  10065. \gray{\LvarGrammarPython} \\ \hline
  10066. \gray{\LifGrammarPython} \\ \hline
  10067. \LwhileGrammarPython \\
  10068. \begin{array}{rcl}
  10069. \LangLoopM{} &::=& \Stmt^{*}
  10070. \end{array}
  10071. \end{array}
  10072. \]
  10073. \fi}
  10074. \end{tcolorbox}
  10075. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10076. \label{fig:Lwhile-concrete-syntax}
  10077. \end{figure}
  10078. \begin{figure}[tp]
  10079. \centering
  10080. \begin{tcolorbox}[colback=white]
  10081. \small
  10082. {\if\edition\racketEd
  10083. \[
  10084. \begin{array}{l}
  10085. \gray{\LintOpAST} \\ \hline
  10086. \gray{\LvarASTRacket{}} \\ \hline
  10087. \gray{\LifASTRacket{}} \\ \hline
  10088. \LwhileASTRacket{} \\
  10089. \begin{array}{lcl}
  10090. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10091. \end{array}
  10092. \end{array}
  10093. \]
  10094. \fi}
  10095. {\if\edition\pythonEd\pythonColor
  10096. \[
  10097. \begin{array}{l}
  10098. \gray{\LintASTPython} \\ \hline
  10099. \gray{\LvarASTPython} \\ \hline
  10100. \gray{\LifASTPython} \\ \hline
  10101. \LwhileASTPython \\
  10102. \begin{array}{lcl}
  10103. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10104. \end{array}
  10105. \end{array}
  10106. \]
  10107. \fi}
  10108. \end{tcolorbox}
  10109. \python{
  10110. \index{subject}{While@\texttt{While}}
  10111. }
  10112. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10113. \label{fig:Lwhile-syntax}
  10114. \end{figure}
  10115. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10116. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10117. shows the definition of its abstract syntax.
  10118. %
  10119. The definitional interpreter for \LangLoop{} is shown in
  10120. figure~\ref{fig:interp-Lwhile}.
  10121. %
  10122. {\if\edition\racketEd
  10123. %
  10124. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10125. and \code{Void}, and we make changes to the cases for \code{Var} and
  10126. \code{Let} regarding variables. To support assignment to variables and
  10127. to make their lifetimes indefinite (see the second example in
  10128. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10129. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10130. value.
  10131. %
  10132. Now we discuss the new cases. For \code{SetBang}, we find the
  10133. variable in the environment to obtain a boxed value, and then we change
  10134. it using \code{set-box!} to the result of evaluating the right-hand
  10135. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10136. %
  10137. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10138. if the result is true, (2) evaluate the body.
  10139. The result value of a \code{while} loop is also \code{\#<void>}.
  10140. %
  10141. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10142. subexpressions \itm{es} for their effects and then evaluates
  10143. and returns the result from \itm{body}.
  10144. %
  10145. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10146. %
  10147. \fi}
  10148. {\if\edition\pythonEd\pythonColor
  10149. %
  10150. We add a new case for \code{While} in the \code{interp\_stmts}
  10151. function, where we repeatedly interpret the \code{body} so long as the
  10152. \code{test} expression remains true.
  10153. %
  10154. \fi}
  10155. \begin{figure}[tbp]
  10156. \begin{tcolorbox}[colback=white]
  10157. {\if\edition\racketEd
  10158. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10159. (define interp-Lwhile-class
  10160. (class interp-Lif-class
  10161. (super-new)
  10162. (define/override ((interp-exp env) e)
  10163. (define recur (interp-exp env))
  10164. (match e
  10165. [(Let x e body)
  10166. (define new-env (dict-set env x (box (recur e))))
  10167. ((interp-exp new-env) body)]
  10168. [(Var x) (unbox (dict-ref env x))]
  10169. [(SetBang x rhs)
  10170. (set-box! (dict-ref env x) (recur rhs))]
  10171. [(WhileLoop cnd body)
  10172. (define (loop)
  10173. (cond [(recur cnd) (recur body) (loop)]
  10174. [else (void)]))
  10175. (loop)]
  10176. [(Begin es body)
  10177. (for ([e es]) (recur e))
  10178. (recur body)]
  10179. [(Void) (void)]
  10180. [else ((super interp-exp env) e)]))
  10181. ))
  10182. (define (interp-Lwhile p)
  10183. (send (new interp-Lwhile-class) interp-program p))
  10184. \end{lstlisting}
  10185. \fi}
  10186. {\if\edition\pythonEd\pythonColor
  10187. \begin{lstlisting}
  10188. class InterpLwhile(InterpLif):
  10189. def interp_stmt(self, s, env, cont):
  10190. match s:
  10191. case While(test, body, []):
  10192. if self.interp_exp(test, env):
  10193. self.interp_stmts(body + [s] + cont, env)
  10194. else:
  10195. return self.interp_stmts(cont, env)
  10196. case _:
  10197. return super().interp_stmt(s, env, cont)
  10198. \end{lstlisting}
  10199. \fi}
  10200. \end{tcolorbox}
  10201. \caption{Interpreter for \LangLoop{}.}
  10202. \label{fig:interp-Lwhile}
  10203. \end{figure}
  10204. The definition of the type checker for \LangLoop{} is shown in
  10205. figure~\ref{fig:type-check-Lwhile}.
  10206. %
  10207. {\if\edition\racketEd
  10208. %
  10209. The type checking of the \code{SetBang} expression requires the type
  10210. of the variable and the right-hand side to agree. The result type is
  10211. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10212. and the result type is \code{Void}. For \code{Begin}, the result type
  10213. is the type of its last subexpression.
  10214. %
  10215. \fi}
  10216. %
  10217. {\if\edition\pythonEd\pythonColor
  10218. %
  10219. A \code{while} loop is well typed if the type of the \code{test}
  10220. expression is \code{bool} and the statements in the \code{body} are
  10221. well typed.
  10222. %
  10223. \fi}
  10224. \begin{figure}[tbp]
  10225. \begin{tcolorbox}[colback=white]
  10226. {\if\edition\racketEd
  10227. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10228. (define type-check-Lwhile-class
  10229. (class type-check-Lif-class
  10230. (super-new)
  10231. (inherit check-type-equal?)
  10232. (define/override (type-check-exp env)
  10233. (lambda (e)
  10234. (define recur (type-check-exp env))
  10235. (match e
  10236. [(SetBang x rhs)
  10237. (define-values (rhs^ rhsT) (recur rhs))
  10238. (define varT (dict-ref env x))
  10239. (check-type-equal? rhsT varT e)
  10240. (values (SetBang x rhs^) 'Void)]
  10241. [(WhileLoop cnd body)
  10242. (define-values (cnd^ Tc) (recur cnd))
  10243. (check-type-equal? Tc 'Boolean e)
  10244. (define-values (body^ Tbody) ((type-check-exp env) body))
  10245. (values (WhileLoop cnd^ body^) 'Void)]
  10246. [(Begin es body)
  10247. (define-values (es^ ts)
  10248. (for/lists (l1 l2) ([e es]) (recur e)))
  10249. (define-values (body^ Tbody) (recur body))
  10250. (values (Begin es^ body^) Tbody)]
  10251. [else ((super type-check-exp env) e)])))
  10252. ))
  10253. (define (type-check-Lwhile p)
  10254. (send (new type-check-Lwhile-class) type-check-program p))
  10255. \end{lstlisting}
  10256. \fi}
  10257. {\if\edition\pythonEd\pythonColor
  10258. \begin{lstlisting}
  10259. class TypeCheckLwhile(TypeCheckLif):
  10260. def type_check_stmts(self, ss, env):
  10261. if len(ss) == 0:
  10262. return
  10263. match ss[0]:
  10264. case While(test, body, []):
  10265. test_t = self.type_check_exp(test, env)
  10266. check_type_equal(bool, test_t, test)
  10267. body_t = self.type_check_stmts(body, env)
  10268. return self.type_check_stmts(ss[1:], env)
  10269. case _:
  10270. return super().type_check_stmts(ss, env)
  10271. \end{lstlisting}
  10272. \fi}
  10273. \end{tcolorbox}
  10274. \caption{Type checker for the \LangLoop{} language.}
  10275. \label{fig:type-check-Lwhile}
  10276. \end{figure}
  10277. {\if\edition\racketEd
  10278. %
  10279. At first glance, the translation of these language features to x86
  10280. seems straightforward because the \LangCIf{} intermediate language
  10281. already supports all the ingredients that we need: assignment,
  10282. \code{goto}, conditional branching, and sequencing. However, there are
  10283. complications that arise, which we discuss in the next section. After
  10284. that we introduce the changes necessary to the existing passes.
  10285. %
  10286. \fi}
  10287. {\if\edition\pythonEd\pythonColor
  10288. %
  10289. At first glance, the translation of \code{while} loops to x86 seems
  10290. straightforward because the \LangCIf{} intermediate language already
  10291. supports \code{goto} and conditional branching. However, there are
  10292. complications that arise which we discuss in the next section. After
  10293. that we introduce the changes necessary to the existing passes.
  10294. %
  10295. \fi}
  10296. \section{Cyclic Control Flow and Dataflow Analysis}
  10297. \label{sec:dataflow-analysis}
  10298. Up until this point, the programs generated in
  10299. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10300. \code{while} loop introduces a cycle. Does that matter?
  10301. %
  10302. Indeed, it does. Recall that for register allocation, the compiler
  10303. performs liveness analysis to determine which variables can share the
  10304. same register. To accomplish this, we analyzed the control-flow graph
  10305. in reverse topological order
  10306. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10307. well defined only for acyclic graphs.
  10308. Let us return to the example of computing the sum of the first five
  10309. positive integers. Here is the program after instruction
  10310. selection\index{subject}{instruction selection} but before register
  10311. allocation.
  10312. \begin{center}
  10313. {\if\edition\racketEd
  10314. \begin{minipage}{0.45\textwidth}
  10315. \begin{lstlisting}
  10316. (define (main) : Integer
  10317. mainstart:
  10318. movq $0, sum
  10319. movq $5, i
  10320. jmp block5
  10321. block5:
  10322. movq i, tmp3
  10323. cmpq tmp3, $0
  10324. jl block7
  10325. jmp block8
  10326. \end{lstlisting}
  10327. \end{minipage}
  10328. \begin{minipage}{0.45\textwidth}
  10329. \begin{lstlisting}
  10330. block7:
  10331. addq i, sum
  10332. movq $1, tmp4
  10333. negq tmp4
  10334. addq tmp4, i
  10335. jmp block5
  10336. block8:
  10337. movq $27, %rax
  10338. addq sum, %rax
  10339. jmp mainconclusion)
  10340. \end{lstlisting}
  10341. \end{minipage}
  10342. \fi}
  10343. {\if\edition\pythonEd\pythonColor
  10344. \begin{minipage}{0.45\textwidth}
  10345. \begin{lstlisting}
  10346. mainstart:
  10347. movq $0, sum
  10348. movq $5, i
  10349. jmp block5
  10350. block5:
  10351. cmpq $0, i
  10352. jg block7
  10353. jmp block8
  10354. \end{lstlisting}
  10355. \end{minipage}
  10356. \begin{minipage}{0.45\textwidth}
  10357. \begin{lstlisting}
  10358. block7:
  10359. addq i, sum
  10360. subq $1, i
  10361. jmp block5
  10362. block8:
  10363. movq sum, %rdi
  10364. callq print_int
  10365. movq $0, %rax
  10366. jmp mainconclusion
  10367. \end{lstlisting}
  10368. \end{minipage}
  10369. \fi}
  10370. \end{center}
  10371. Recall that liveness analysis works backward, starting at the end
  10372. of each function. For this example we could start with \code{block8}
  10373. because we know what is live at the beginning of the conclusion:
  10374. only \code{rax} and \code{rsp}. So the live-before set
  10375. for \code{block8} is \code{\{rsp,sum\}}.
  10376. %
  10377. Next we might try to analyze \code{block5} or \code{block7}, but
  10378. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10379. we are stuck.
  10380. The way out of this impasse is to realize that we can compute an
  10381. underapproximation of each live-before set by starting with empty
  10382. live-after sets. By \emph{underapproximation}, we mean that the set
  10383. contains only variables that are live for some execution of the
  10384. program, but the set may be missing some variables that are live.
  10385. Next, the underapproximations for each block can be improved by (1)
  10386. updating the live-after set for each block using the approximate
  10387. live-before sets from the other blocks, and (2) performing liveness
  10388. analysis again on each block. In fact, by iterating this process, the
  10389. underapproximations eventually become the correct solutions!
  10390. %
  10391. This approach of iteratively analyzing a control-flow graph is
  10392. applicable to many static analysis problems and goes by the name
  10393. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10394. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10395. Washington.
  10396. Let us apply this approach to the previously presented example. We use
  10397. the empty set for the initial live-before set for each block. Let
  10398. $m_0$ be the following mapping from label names to sets of locations
  10399. (variables and registers):
  10400. \begin{center}
  10401. \begin{lstlisting}
  10402. mainstart: {}, block5: {}, block7: {}, block8: {}
  10403. \end{lstlisting}
  10404. \end{center}
  10405. Using the above live-before approximations, we determine the
  10406. live-after for each block and then apply liveness analysis to each
  10407. block. This produces our next approximation $m_1$ of the live-before
  10408. sets.
  10409. \begin{center}
  10410. \begin{lstlisting}
  10411. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10412. \end{lstlisting}
  10413. \end{center}
  10414. For the second round, the live-after for \code{mainstart} is the
  10415. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10416. the liveness analysis for \code{mainstart} computes the empty set. The
  10417. live-after for \code{block5} is the union of the live-before sets for
  10418. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10419. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10420. sum\}}. The live-after for \code{block7} is the live-before for
  10421. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10422. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10423. Together these yield the following approximation $m_2$ of
  10424. the live-before sets:
  10425. \begin{center}
  10426. \begin{lstlisting}
  10427. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10428. \end{lstlisting}
  10429. \end{center}
  10430. In the preceding iteration, only \code{block5} changed, so we can
  10431. limit our attention to \code{mainstart} and \code{block7}, the two
  10432. blocks that jump to \code{block5}. As a result, the live-before sets
  10433. for \code{mainstart} and \code{block7} are updated to include
  10434. \code{rsp}, yielding the following approximation $m_3$:
  10435. \begin{center}
  10436. \begin{lstlisting}
  10437. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10438. \end{lstlisting}
  10439. \end{center}
  10440. Because \code{block7} changed, we analyze \code{block5} once more, but
  10441. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10442. our approximations have converged, so $m_3$ is the solution.
  10443. This iteration process is guaranteed to converge to a solution by the
  10444. Kleene fixed-point theorem, a general theorem about functions on
  10445. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10446. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10447. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10448. join operator
  10449. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10450. will be working with join semilattices.} When two elements are
  10451. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10452. as much information as $m_i$, so we can think of $m_j$ as a
  10453. better-than-or-equal-to approximation in relation to $m_i$. The
  10454. bottom element $\bot$ represents the complete lack of information,
  10455. that is, the worst approximation. The join operator takes two lattice
  10456. elements and combines their information; that is, it produces the
  10457. least upper bound of the two.\index{subject}{least upper bound}
  10458. A dataflow analysis typically involves two lattices: one lattice to
  10459. represent abstract states and another lattice that aggregates the
  10460. abstract states of all the blocks in the control-flow graph. For
  10461. liveness analysis, an abstract state is a set of locations. We form
  10462. the lattice $L$ by taking its elements to be sets of locations, the
  10463. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10464. set, and the join operator to be set union.
  10465. %
  10466. We form a second lattice $M$ by taking its elements to be mappings
  10467. from the block labels to sets of locations (elements of $L$). We
  10468. order the mappings point-wise, using the ordering of $L$. So, given any
  10469. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10470. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10471. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10472. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10473. We can think of one iteration of liveness analysis applied to the
  10474. whole program as being a function $f$ on the lattice $M$. It takes a
  10475. mapping as input and computes a new mapping.
  10476. \[
  10477. f(m_i) = m_{i+1}
  10478. \]
  10479. Next let us think for a moment about what a final solution $m_s$
  10480. should look like. If we perform liveness analysis using the solution
  10481. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10482. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10483. \[
  10484. f(m_s) = m_s
  10485. \]
  10486. Furthermore, the solution should include only locations that are
  10487. forced to be there by performing liveness analysis on the program, so
  10488. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10489. The Kleene fixed-point theorem states that if a function $f$ is
  10490. monotone (better inputs produce better outputs), then the least fixed
  10491. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10492. chain} obtained by starting at $\bot$ and iterating $f$, as
  10493. follows:\index{subject}{Kleene fixed-point theorem}
  10494. \[
  10495. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10496. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10497. \]
  10498. When a lattice contains only finitely long ascending chains, then
  10499. every Kleene chain tops out at some fixed point after some number of
  10500. iterations of $f$.
  10501. \[
  10502. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10503. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10504. \]
  10505. The liveness analysis is indeed a monotone function and the lattice
  10506. $M$ has finitely long ascending chains because there are only a
  10507. finite number of variables and blocks in the program. Thus we are
  10508. guaranteed that iteratively applying liveness analysis to all blocks
  10509. in the program will eventually produce the least fixed point solution.
  10510. Next let us consider dataflow analysis in general and discuss the
  10511. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10512. %
  10513. The algorithm has four parameters: the control-flow graph \code{G}, a
  10514. function \code{transfer} that applies the analysis to one block, and the
  10515. \code{bottom} and \code{join} operators for the lattice of abstract
  10516. states. The \code{analyze\_dataflow} function is formulated as a
  10517. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10518. function come from the predecessor nodes in the control-flow
  10519. graph. However, liveness analysis is a \emph{backward} dataflow
  10520. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10521. function with the transpose of the control-flow graph.
  10522. The algorithm begins by creating the bottom mapping, represented by a
  10523. hash table. It then pushes all the nodes in the control-flow graph
  10524. onto the work list (a queue). The algorithm repeats the \code{while}
  10525. loop as long as there are items in the work list. In each iteration, a
  10526. node is popped from the work list and processed. The \code{input} for
  10527. the node is computed by taking the join of the abstract states of all
  10528. the predecessor nodes. The \code{transfer} function is then applied to
  10529. obtain the \code{output} abstract state. If the output differs from
  10530. the previous state for this block, the mapping for this block is
  10531. updated and its successor nodes are pushed onto the work list.
  10532. \begin{figure}[tb]
  10533. \begin{tcolorbox}[colback=white]
  10534. {\if\edition\racketEd
  10535. \begin{lstlisting}
  10536. (define (analyze_dataflow G transfer bottom join)
  10537. (define mapping (make-hash))
  10538. (for ([v (in-vertices G)])
  10539. (dict-set! mapping v bottom))
  10540. (define worklist (make-queue))
  10541. (for ([v (in-vertices G)])
  10542. (enqueue! worklist v))
  10543. (define trans-G (transpose G))
  10544. (while (not (queue-empty? worklist))
  10545. (define node (dequeue! worklist))
  10546. (define input (for/fold ([state bottom])
  10547. ([pred (in-neighbors trans-G node)])
  10548. (join state (dict-ref mapping pred))))
  10549. (define output (transfer node input))
  10550. (cond [(not (equal? output (dict-ref mapping node)))
  10551. (dict-set! mapping node output)
  10552. (for ([v (in-neighbors G node)])
  10553. (enqueue! worklist v))]))
  10554. mapping)
  10555. \end{lstlisting}
  10556. \fi}
  10557. {\if\edition\pythonEd\pythonColor
  10558. \begin{lstlisting}
  10559. def analyze_dataflow(G, transfer, bottom, join):
  10560. trans_G = transpose(G)
  10561. mapping = dict((v, bottom) for v in G.vertices())
  10562. worklist = deque(G.vertices)
  10563. while worklist:
  10564. node = worklist.pop()
  10565. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10566. input = reduce(join, inputs, bottom)
  10567. output = transfer(node, input)
  10568. if output != mapping[node]:
  10569. mapping[node] = output
  10570. worklist.extend(G.adjacent(node))
  10571. \end{lstlisting}
  10572. \fi}
  10573. \end{tcolorbox}
  10574. \caption{Generic work list algorithm for dataflow analysis.}
  10575. \label{fig:generic-dataflow}
  10576. \end{figure}
  10577. {\if\edition\racketEd
  10578. \section{Mutable Variables and Remove Complex Operands}
  10579. There is a subtle interaction between the
  10580. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10581. and the left-to-right order of evaluation of Racket. Consider the
  10582. following example:
  10583. \begin{lstlisting}
  10584. (let ([x 2])
  10585. (+ x (begin (set! x 40) x)))
  10586. \end{lstlisting}
  10587. The result of this program is \code{42} because the first read from
  10588. \code{x} produces \code{2} and the second produces \code{40}. However,
  10589. if we naively apply the \code{remove\_complex\_operands} pass to this
  10590. example we obtain the following program whose result is \code{80}!
  10591. \begin{lstlisting}
  10592. (let ([x 2])
  10593. (let ([tmp (begin (set! x 40) x)])
  10594. (+ x tmp)))
  10595. \end{lstlisting}
  10596. The problem is that with mutable variables, the ordering between
  10597. reads and writes is important, and the
  10598. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10599. before the first read of \code{x}.
  10600. We recommend solving this problem by giving special treatment to reads
  10601. from mutable variables, that is, variables that occur on the left-hand
  10602. side of a \code{set!}. We mark each read from a mutable variable with
  10603. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10604. that the read operation is effectful in that it can produce different
  10605. results at different points in time. Let's apply this idea to the
  10606. following variation that also involves a variable that is not mutated:
  10607. % loop_test_24.rkt
  10608. \begin{lstlisting}
  10609. (let ([x 2])
  10610. (let ([y 0])
  10611. (+ y (+ x (begin (set! x 40) x)))))
  10612. \end{lstlisting}
  10613. We first analyze this program to discover that variable \code{x}
  10614. is mutable but \code{y} is not. We then transform the program as
  10615. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10616. \begin{lstlisting}
  10617. (let ([x 2])
  10618. (let ([y 0])
  10619. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10620. \end{lstlisting}
  10621. Now that we have a clear distinction between reads from mutable and
  10622. immutable variables, we can apply the \code{remove\_complex\_operands}
  10623. pass, where reads from immutable variables are still classified as
  10624. atomic expressions but reads from mutable variables are classified as
  10625. complex. Thus, \code{remove\_complex\_operands} yields the following
  10626. program:\\
  10627. \begin{minipage}{\textwidth}
  10628. \begin{lstlisting}
  10629. (let ([x 2])
  10630. (let ([y 0])
  10631. (+ y (let ([t1 (get! x)])
  10632. (let ([t2 (begin (set! x 40) (get! x))])
  10633. (+ t1 t2))))))
  10634. \end{lstlisting}
  10635. \end{minipage}
  10636. The temporary variable \code{t1} gets the value of \code{x} before the
  10637. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10638. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10639. do not generate a temporary variable for the occurrence of \code{y}
  10640. because it's an immutable variable. We want to avoid such unnecessary
  10641. extra temporaries because they would needlessly increase the number of
  10642. variables, making it more likely for some of them to be spilled. The
  10643. result of this program is \code{42}, the same as the result prior to
  10644. \code{remove\_complex\_operands}.
  10645. The approach that we've sketched requires only a small
  10646. modification to \code{remove\_complex\_operands} to handle
  10647. \code{get!}. However, it requires a new pass, called
  10648. \code{uncover-get!}, that we discuss in
  10649. section~\ref{sec:uncover-get-bang}.
  10650. As an aside, this problematic interaction between \code{set!} and the
  10651. pass \code{remove\_complex\_operands} is particular to Racket and not
  10652. its predecessor, the Scheme language. The key difference is that
  10653. Scheme does not specify an order of evaluation for the arguments of an
  10654. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10655. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10656. would be correct results for the example program. Interestingly,
  10657. Racket is implemented on top of the Chez Scheme
  10658. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10659. presented in this section (using extra \code{let} bindings to control
  10660. the order of evaluation) is used in the translation from Racket to
  10661. Scheme~\citep{Flatt:2019tb}.
  10662. \fi} % racket
  10663. Having discussed the complications that arise from adding support for
  10664. assignment and loops, we turn to discussing the individual compilation
  10665. passes.
  10666. {\if\edition\racketEd
  10667. \section{Uncover \texttt{get!}}
  10668. \label{sec:uncover-get-bang}
  10669. The goal of this pass is to mark uses of mutable variables so that
  10670. \code{remove\_complex\_operands} can treat them as complex expressions
  10671. and thereby preserve their ordering relative to the side effects in
  10672. other operands. So, the first step is to collect all the mutable
  10673. variables. We recommend creating an auxiliary function for this,
  10674. named \code{collect-set!}, that recursively traverses expressions,
  10675. returning the set of all variables that occur on the left-hand side of a
  10676. \code{set!}. Here's an excerpt of its implementation.
  10677. \begin{center}
  10678. \begin{minipage}{\textwidth}
  10679. \begin{lstlisting}
  10680. (define (collect-set! e)
  10681. (match e
  10682. [(Var x) (set)]
  10683. [(Int n) (set)]
  10684. [(Let x rhs body)
  10685. (set-union (collect-set! rhs) (collect-set! body))]
  10686. [(SetBang var rhs)
  10687. (set-union (set var) (collect-set! rhs))]
  10688. ...))
  10689. \end{lstlisting}
  10690. \end{minipage}
  10691. \end{center}
  10692. By placing this pass after \code{uniquify}, we need not worry about
  10693. variable shadowing, and our logic for \code{Let} can remain simple, as
  10694. in this excerpt.
  10695. The second step is to mark the occurrences of the mutable variables
  10696. with the new \code{GetBang} AST node (\code{get!} in concrete
  10697. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10698. function, which takes two parameters: the set of mutable variables
  10699. \code{set!-vars} and the expression \code{e} to be processed. The
  10700. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10701. mutable variable or leaves it alone if not.
  10702. \begin{center}
  10703. \begin{minipage}{\textwidth}
  10704. \begin{lstlisting}
  10705. (define ((uncover-get!-exp set!-vars) e)
  10706. (match e
  10707. [(Var x)
  10708. (if (set-member? set!-vars x)
  10709. (GetBang x)
  10710. (Var x))]
  10711. ...))
  10712. \end{lstlisting}
  10713. \end{minipage}
  10714. \end{center}
  10715. To wrap things up, define the \code{uncover-get!} function for
  10716. processing a whole program, using \code{collect-set!} to obtain the
  10717. set of mutable variables and then \code{uncover-get!-exp} to replace
  10718. their occurrences with \code{GetBang}.
  10719. \fi}
  10720. \section{Remove Complex Operands}
  10721. \label{sec:rco-loop}
  10722. {\if\edition\racketEd
  10723. %
  10724. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10725. \code{while} are all complex expressions. The subexpressions of
  10726. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10727. %
  10728. \fi}
  10729. {\if\edition\pythonEd\pythonColor
  10730. %
  10731. The change needed for this pass is to add a case for the \code{while}
  10732. statement. The condition of a \code{while} loop is allowed to be a
  10733. complex expression, just like the condition of the \code{if}
  10734. statement.
  10735. %
  10736. \fi}
  10737. %
  10738. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10739. \LangLoopANF{} of this pass.
  10740. \newcommand{\LwhileMonadASTRacket}{
  10741. \begin{array}{rcl}
  10742. \Atm &::=& \VOID{} \\
  10743. \Exp &::=& \GETBANG{\Var}
  10744. \MID \SETBANG{\Var}{\Exp}
  10745. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10746. &\MID& \WHILE{\Exp}{\Exp}
  10747. \end{array}
  10748. }
  10749. \newcommand{\LwhileMonadASTPython}{
  10750. \begin{array}{rcl}
  10751. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10752. \end{array}
  10753. }
  10754. \begin{figure}[tp]
  10755. \centering
  10756. \begin{tcolorbox}[colback=white]
  10757. \small
  10758. {\if\edition\racketEd
  10759. \[
  10760. \begin{array}{l}
  10761. \gray{\LvarMonadASTRacket} \\ \hline
  10762. \gray{\LifMonadASTRacket} \\ \hline
  10763. \LwhileMonadASTRacket \\
  10764. \begin{array}{rcl}
  10765. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10766. \end{array}
  10767. \end{array}
  10768. \]
  10769. \fi}
  10770. {\if\edition\pythonEd\pythonColor
  10771. \[
  10772. \begin{array}{l}
  10773. \gray{\LvarMonadASTPython} \\ \hline
  10774. \gray{\LifMonadASTPython} \\ \hline
  10775. \LwhileMonadASTPython \\
  10776. \begin{array}{rcl}
  10777. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10778. \end{array}
  10779. \end{array}
  10780. %% \begin{array}{rcl}
  10781. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10782. %% \Exp &::=& \Atm \MID \READ{} \\
  10783. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10784. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10785. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10786. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10787. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10788. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10789. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10790. %% \end{array}
  10791. \]
  10792. \fi}
  10793. \end{tcolorbox}
  10794. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10795. \label{fig:Lwhile-anf-syntax}
  10796. \end{figure}
  10797. {\if\edition\racketEd
  10798. %
  10799. As usual, when a complex expression appears in a grammar position that
  10800. needs to be atomic, such as the argument of a primitive operator, we
  10801. must introduce a temporary variable and bind it to the complex
  10802. expression. This approach applies, unchanged, to handle the new
  10803. language forms. For example, in the following code there are two
  10804. \code{begin} expressions appearing as arguments to the \code{+}
  10805. operator. The output of \code{rco\_exp} is then shown, in which the
  10806. \code{begin} expressions have been bound to temporary
  10807. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10808. allowed to have arbitrary expressions in their right-hand side
  10809. expression, so it is fine to place \code{begin} there.
  10810. %
  10811. \begin{center}
  10812. \begin{tabular}{lcl}
  10813. \begin{minipage}{0.4\textwidth}
  10814. \begin{lstlisting}
  10815. (let ([x2 10])
  10816. (let ([y3 0])
  10817. (+ (+ (begin
  10818. (set! y3 (read))
  10819. (get! x2))
  10820. (begin
  10821. (set! x2 (read))
  10822. (get! y3)))
  10823. (get! x2))))
  10824. \end{lstlisting}
  10825. \end{minipage}
  10826. &
  10827. $\Rightarrow$
  10828. &
  10829. \begin{minipage}{0.4\textwidth}
  10830. \begin{lstlisting}
  10831. (let ([x2 10])
  10832. (let ([y3 0])
  10833. (let ([tmp4 (begin
  10834. (set! y3 (read))
  10835. x2)])
  10836. (let ([tmp5 (begin
  10837. (set! x2 (read))
  10838. y3)])
  10839. (let ([tmp6 (+ tmp4 tmp5)])
  10840. (let ([tmp7 x2])
  10841. (+ tmp6 tmp7)))))))
  10842. \end{lstlisting}
  10843. \end{minipage}
  10844. \end{tabular}
  10845. \end{center}
  10846. \fi}
  10847. \section{Explicate Control \racket{and \LangCLoop{}}}
  10848. \label{sec:explicate-loop}
  10849. \newcommand{\CloopASTRacket}{
  10850. \begin{array}{lcl}
  10851. \Atm &::=& \VOID \\
  10852. \Stmt &::=& \READ{}
  10853. \end{array}
  10854. }
  10855. {\if\edition\racketEd
  10856. Recall that in the \code{explicate\_control} pass we define one helper
  10857. function for each kind of position in the program. For the \LangVar{}
  10858. language of integers and variables, we needed assignment and tail
  10859. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10860. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10861. another kind of position: effect position. Except for the last
  10862. subexpression, the subexpressions inside a \code{begin} are evaluated
  10863. only for their effect. Their result values are discarded. We can
  10864. generate better code by taking this fact into account.
  10865. The output language of \code{explicate\_control} is \LangCLoop{}
  10866. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10867. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10868. and that \code{read} may appear as a statement. The most significant
  10869. difference between the programs generated by \code{explicate\_control}
  10870. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10871. chapter is that the control-flow graphs of the latter may contain
  10872. cycles.
  10873. \begin{figure}[tp]
  10874. \begin{tcolorbox}[colback=white]
  10875. \small
  10876. \[
  10877. \begin{array}{l}
  10878. \gray{\CvarASTRacket} \\ \hline
  10879. \gray{\CifASTRacket} \\ \hline
  10880. \CloopASTRacket \\
  10881. \begin{array}{lcl}
  10882. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10883. \end{array}
  10884. \end{array}
  10885. \]
  10886. \end{tcolorbox}
  10887. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10888. \label{fig:c7-syntax}
  10889. \end{figure}
  10890. The new auxiliary function \code{explicate\_effect} takes an
  10891. expression (in an effect position) and the code for its
  10892. continuation. The function returns a $\Tail$ that includes the
  10893. generated code for the input expression followed by the
  10894. continuation. If the expression is obviously pure, that is, never
  10895. causes side effects, then the expression can be removed, so the result
  10896. is just the continuation.
  10897. %
  10898. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10899. interesting; the generated code is depicted in the following diagram:
  10900. \begin{center}
  10901. \begin{minipage}{0.3\textwidth}
  10902. \xymatrix{
  10903. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10904. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10905. & *+[F]{\txt{\itm{cont}}} \\
  10906. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10907. }
  10908. \end{minipage}
  10909. \end{center}
  10910. We start by creating a fresh label $\itm{loop}$ for the top of the
  10911. loop. Next, recursively process the \itm{body} (in effect position)
  10912. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10913. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10914. \itm{body'} as the \emph{then} branch and the continuation block as the
  10915. \emph{else} branch. The result should be added to the dictionary of
  10916. \code{basic-blocks} with the label \itm{loop}. The result for the
  10917. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10918. The auxiliary functions for tail, assignment, and predicate positions
  10919. need to be updated. The three new language forms, \code{while},
  10920. \code{set!}, and \code{begin}, can appear in assignment and tail
  10921. positions. Only \code{begin} may appear in predicate positions; the
  10922. other two have result type \code{Void}.
  10923. \fi}
  10924. %
  10925. {\if\edition\pythonEd\pythonColor
  10926. %
  10927. The output of this pass is the language \LangCIf{}. No new language
  10928. features are needed in the output because a \code{while} loop can be
  10929. expressed in terms of \code{goto} and \code{if} statements, which are
  10930. already in \LangCIf{}.
  10931. %
  10932. Add a case for the \code{while} statement to the
  10933. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10934. the condition expression.
  10935. %
  10936. \fi}
  10937. {\if\edition\racketEd
  10938. \section{Select Instructions}
  10939. \label{sec:select-instructions-loop}
  10940. \index{subject}{select instructions}
  10941. Only two small additions are needed in the \code{select\_instructions}
  10942. pass to handle the changes to \LangCLoop{}. First, to handle the
  10943. addition of \VOID{} we simply translate it to \code{0}. Second,
  10944. \code{read} may appear as a stand-alone statement instead of
  10945. appearing only on the right-hand side of an assignment statement. The code
  10946. generation is nearly identical to the one for assignment; just leave
  10947. off the instruction for moving the result into the left-hand side.
  10948. \fi}
  10949. \section{Register Allocation}
  10950. \label{sec:register-allocation-loop}
  10951. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10952. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10953. which complicates the liveness analysis needed for register
  10954. allocation.
  10955. %
  10956. We recommend using the generic \code{analyze\_dataflow} function that
  10957. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10958. perform liveness analysis, replacing the code in
  10959. \code{uncover\_live} that processed the basic blocks in topological
  10960. order (section~\ref{sec:liveness-analysis-Lif}).
  10961. The \code{analyze\_dataflow} function has the following four parameters.
  10962. \begin{enumerate}
  10963. \item The first parameter \code{G} should be passed the transpose
  10964. of the control-flow graph.
  10965. \item The second parameter \code{transfer} should be passed a function
  10966. that applies liveness analysis to a basic block. It takes two
  10967. parameters: the label for the block to analyze and the live-after
  10968. set for that block. The transfer function should return the
  10969. live-before set for the block.
  10970. %
  10971. \racket{Also, as a side effect, it should update the block's
  10972. $\itm{info}$ with the liveness information for each instruction.}
  10973. %
  10974. \python{Also, as a side-effect, it should update the live-before and
  10975. live-after sets for each instruction.}
  10976. %
  10977. To implement the \code{transfer} function, you should be able to
  10978. reuse the code you already have for analyzing basic blocks.
  10979. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10980. \code{bottom} and \code{join} for the lattice of abstract states,
  10981. that is, sets of locations. For liveness analysis, the bottom of the
  10982. lattice is the empty set, and the join operator is set union.
  10983. \end{enumerate}
  10984. \begin{figure}[p]
  10985. \begin{tcolorbox}[colback=white]
  10986. {\if\edition\racketEd
  10987. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10988. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10989. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10990. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10991. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10992. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10993. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10994. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10995. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  10996. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  10997. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10998. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10999. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11000. \path[->,bend left=15] (Lfun) edge [above] node
  11001. {\ttfamily\footnotesize shrink} (Lfun-2);
  11002. \path[->,bend left=15] (Lfun-2) edge [above] node
  11003. {\ttfamily\footnotesize uniquify} (F1-4);
  11004. \path[->,bend left=15] (F1-4) edge [above] node
  11005. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11006. \path[->,bend left=15] (F1-5) edge [left] node
  11007. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11008. \path[->,bend left=10] (F1-6) edge [above] node
  11009. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11010. \path[->,bend left=15] (C3-2) edge [right] node
  11011. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11012. \path[->,bend right=15] (x86-2) edge [right] node
  11013. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11014. \path[->,bend right=15] (x86-2-1) edge [below] node
  11015. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11016. \path[->,bend right=15] (x86-2-2) edge [right] node
  11017. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11018. \path[->,bend left=15] (x86-3) edge [above] node
  11019. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11020. \path[->,bend left=15] (x86-4) edge [right] node
  11021. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11022. \end{tikzpicture}
  11023. \fi}
  11024. {\if\edition\pythonEd\pythonColor
  11025. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11026. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11027. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11028. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11029. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11030. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11031. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11032. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11033. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11034. \path[->,bend left=15] (Lfun) edge [above] node
  11035. {\ttfamily\footnotesize shrink} (Lfun-2);
  11036. \path[->,bend left=15] (Lfun-2) edge [above] node
  11037. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11038. \path[->,bend left=10] (F1-6) edge [right] node
  11039. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11040. \path[->,bend right=15] (C3-2) edge [right] node
  11041. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11042. \path[->,bend right=15] (x86-2) edge [below] node
  11043. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11044. \path[->,bend left=15] (x86-3) edge [above] node
  11045. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11046. \path[->,bend right=15] (x86-4) edge [below] node
  11047. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11048. \end{tikzpicture}
  11049. \fi}
  11050. \end{tcolorbox}
  11051. \caption{Diagram of the passes for \LangLoop{}.}
  11052. \label{fig:Lwhile-passes}
  11053. \end{figure}
  11054. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11055. for the compilation of \LangLoop{}.
  11056. % Further Reading: dataflow analysis
  11057. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11058. \chapter{Tuples and Garbage Collection}
  11059. \label{ch:Lvec}
  11060. \index{subject}{tuple}
  11061. \index{subject}{vector}
  11062. \setcounter{footnote}{0}
  11063. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11064. %% all the IR grammars are spelled out! \\ --Jeremy}
  11065. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11066. %% the root stack. \\ --Jeremy}
  11067. In this chapter we study the implementation of tuples\racket{, called
  11068. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11069. in which each element may have a different type.
  11070. %
  11071. This language feature is the first to use the computer's
  11072. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11073. indefinite; that is, a tuple lives forever from the programmer's
  11074. viewpoint. Of course, from an implementer's viewpoint, it is important
  11075. to reclaim the space associated with a tuple when it is no longer
  11076. needed, which is why we also study \emph{garbage collection}
  11077. \index{subject}{garbage collection} techniques in this chapter.
  11078. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11079. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11080. language (chapter~\ref{ch:Lwhile}) with tuples.
  11081. %
  11082. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11083. copying live tuples back and forth between two halves of the heap. The
  11084. garbage collector requires coordination with the compiler so that it
  11085. can find all the live tuples.
  11086. %
  11087. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11088. discuss the necessary changes and additions to the compiler passes,
  11089. including a new compiler pass named \code{expose\_allocation}.
  11090. \section{The \LangVec{} Language}
  11091. \label{sec:r3}
  11092. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11093. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11094. the definition of the abstract syntax.
  11095. %
  11096. \racket{The \LangVec{} language includes the forms \code{vector} for
  11097. creating a tuple, \code{vector-ref} for reading an element of a
  11098. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11099. \code{vector-length} for obtaining the number of elements of a
  11100. tuple.}
  11101. %
  11102. \python{The \LangVec{} language adds 1) tuple creation via a
  11103. comma-separated list of expressions, 2) accessing an element of a
  11104. tuple with the square bracket notation, i.e., \code{t[n]} returns
  11105. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  11106. operator, and 4) obtaining the number of elements (the length) of a
  11107. tuple. In this chapter, we restrict access indices to constant
  11108. integers.}
  11109. %
  11110. The following program shows an example use of tuples. It creates a tuple
  11111. \code{t} containing the elements \code{40},
  11112. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11113. contains just \code{2}. The element at index $1$ of \code{t} is
  11114. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11115. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11116. to which we add \code{2}, the element at index $0$ of the tuple.
  11117. The result of the program is \code{42}.
  11118. %
  11119. {\if\edition\racketEd
  11120. \begin{lstlisting}
  11121. (let ([t (vector 40 #t (vector 2))])
  11122. (if (vector-ref t 1)
  11123. (+ (vector-ref t 0)
  11124. (vector-ref (vector-ref t 2) 0))
  11125. 44))
  11126. \end{lstlisting}
  11127. \fi}
  11128. {\if\edition\pythonEd\pythonColor
  11129. \begin{lstlisting}
  11130. t = 40, True, (2,)
  11131. print( t[0] + t[2][0] if t[1] else 44 )
  11132. \end{lstlisting}
  11133. \fi}
  11134. \newcommand{\LtupGrammarRacket}{
  11135. \begin{array}{lcl}
  11136. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11137. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11138. \MID \LP\key{vector-length}\;\Exp\RP \\
  11139. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11140. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11141. \end{array}
  11142. }
  11143. \newcommand{\LtupASTRacket}{
  11144. \begin{array}{lcl}
  11145. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11146. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11147. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11148. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11149. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11150. \end{array}
  11151. }
  11152. \newcommand{\LtupGrammarPython}{
  11153. \begin{array}{rcl}
  11154. \itm{cmp} &::= & \key{is} \\
  11155. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11156. \end{array}
  11157. }
  11158. \newcommand{\LtupASTPython}{
  11159. \begin{array}{lcl}
  11160. \itm{cmp} &::= & \code{Is()} \\
  11161. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11162. &\MID& \LEN{\Exp}
  11163. \end{array}
  11164. }
  11165. \begin{figure}[tbp]
  11166. \centering
  11167. \begin{tcolorbox}[colback=white]
  11168. \small
  11169. {\if\edition\racketEd
  11170. \[
  11171. \begin{array}{l}
  11172. \gray{\LintGrammarRacket{}} \\ \hline
  11173. \gray{\LvarGrammarRacket{}} \\ \hline
  11174. \gray{\LifGrammarRacket{}} \\ \hline
  11175. \gray{\LwhileGrammarRacket} \\ \hline
  11176. \LtupGrammarRacket \\
  11177. \begin{array}{lcl}
  11178. \LangVecM{} &::=& \Exp
  11179. \end{array}
  11180. \end{array}
  11181. \]
  11182. \fi}
  11183. {\if\edition\pythonEd\pythonColor
  11184. \[
  11185. \begin{array}{l}
  11186. \gray{\LintGrammarPython{}} \\ \hline
  11187. \gray{\LvarGrammarPython{}} \\ \hline
  11188. \gray{\LifGrammarPython{}} \\ \hline
  11189. \gray{\LwhileGrammarPython} \\ \hline
  11190. \LtupGrammarPython \\
  11191. \begin{array}{rcl}
  11192. \LangVecM{} &::=& \Stmt^{*}
  11193. \end{array}
  11194. \end{array}
  11195. \]
  11196. \fi}
  11197. \end{tcolorbox}
  11198. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11199. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11200. \label{fig:Lvec-concrete-syntax}
  11201. \end{figure}
  11202. \begin{figure}[tp]
  11203. \centering
  11204. \begin{tcolorbox}[colback=white]
  11205. \small
  11206. {\if\edition\racketEd
  11207. \[
  11208. \begin{array}{l}
  11209. \gray{\LintOpAST} \\ \hline
  11210. \gray{\LvarASTRacket{}} \\ \hline
  11211. \gray{\LifASTRacket{}} \\ \hline
  11212. \gray{\LwhileASTRacket{}} \\ \hline
  11213. \LtupASTRacket{} \\
  11214. \begin{array}{lcl}
  11215. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11216. \end{array}
  11217. \end{array}
  11218. \]
  11219. \fi}
  11220. {\if\edition\pythonEd\pythonColor
  11221. \[
  11222. \begin{array}{l}
  11223. \gray{\LintASTPython} \\ \hline
  11224. \gray{\LvarASTPython} \\ \hline
  11225. \gray{\LifASTPython} \\ \hline
  11226. \gray{\LwhileASTPython} \\ \hline
  11227. \LtupASTPython \\
  11228. \begin{array}{lcl}
  11229. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11230. \end{array}
  11231. \end{array}
  11232. \]
  11233. \fi}
  11234. \end{tcolorbox}
  11235. \caption{The abstract syntax of \LangVec{}.}
  11236. \label{fig:Lvec-syntax}
  11237. \end{figure}
  11238. Tuples raise several interesting new issues. First, variable binding
  11239. performs a shallow copy in dealing with tuples, which means that
  11240. different variables can refer to the same tuple; that is, two
  11241. variables can be \emph{aliases}\index{subject}{alias} for the same
  11242. entity. Consider the following example, in which \code{t1} and
  11243. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11244. different tuple value with equal elements. The result of the
  11245. program is \code{42}.
  11246. \begin{center}
  11247. \begin{minipage}{0.96\textwidth}
  11248. {\if\edition\racketEd
  11249. \begin{lstlisting}
  11250. (let ([t1 (vector 3 7)])
  11251. (let ([t2 t1])
  11252. (let ([t3 (vector 3 7)])
  11253. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11254. 42
  11255. 0))))
  11256. \end{lstlisting}
  11257. \fi}
  11258. {\if\edition\pythonEd\pythonColor
  11259. \begin{lstlisting}
  11260. t1 = 3, 7
  11261. t2 = t1
  11262. t3 = 3, 7
  11263. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  11264. \end{lstlisting}
  11265. \fi}
  11266. \end{minipage}
  11267. \end{center}
  11268. {\if\edition\racketEd
  11269. Whether two variables are aliased or not affects what happens
  11270. when the underlying tuple is mutated\index{subject}{mutation}.
  11271. Consider the following example in which \code{t1} and \code{t2}
  11272. again refer to the same tuple value.
  11273. \begin{center}
  11274. \begin{minipage}{0.96\textwidth}
  11275. \begin{lstlisting}
  11276. (let ([t1 (vector 3 7)])
  11277. (let ([t2 t1])
  11278. (let ([_ (vector-set! t2 0 42)])
  11279. (vector-ref t1 0))))
  11280. \end{lstlisting}
  11281. \end{minipage}
  11282. \end{center}
  11283. The mutation through \code{t2} is visible in referencing the tuple
  11284. from \code{t1}, so the result of this program is \code{42}.
  11285. \fi}
  11286. The next issue concerns the lifetime of tuples. When does a tuple's
  11287. lifetime end? Notice that \LangVec{} does not include an operation
  11288. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11289. to any notion of static scoping.
  11290. %
  11291. {\if\edition\racketEd
  11292. %
  11293. For example, the following program returns \code{42} even though the
  11294. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11295. that reads from the vector to which it was bound.
  11296. \begin{center}
  11297. \begin{minipage}{0.96\textwidth}
  11298. \begin{lstlisting}
  11299. (let ([v (vector (vector 44))])
  11300. (let ([x (let ([w (vector 42)])
  11301. (let ([_ (vector-set! v 0 w)])
  11302. 0))])
  11303. (+ x (vector-ref (vector-ref v 0) 0))))
  11304. \end{lstlisting}
  11305. \end{minipage}
  11306. \end{center}
  11307. \fi}
  11308. %
  11309. {\if\edition\pythonEd\pythonColor
  11310. %
  11311. For example, the following program returns \code{42} even though the
  11312. variable \code{x} goes out of scope when the function returns, prior
  11313. to reading the tuple element at index zero. (We study the compilation
  11314. of functions in chapter~\ref{ch:Lfun}.)
  11315. %
  11316. \begin{center}
  11317. \begin{minipage}{0.96\textwidth}
  11318. \begin{lstlisting}
  11319. def f():
  11320. x = 42, 43
  11321. return x
  11322. t = f()
  11323. print( t[0] )
  11324. \end{lstlisting}
  11325. \end{minipage}
  11326. \end{center}
  11327. \fi}
  11328. %
  11329. From the perspective of programmer-observable behavior, tuples live
  11330. forever. However, if they really lived forever then many long-running
  11331. programs would run out of memory. To solve this problem, the
  11332. language's runtime system performs automatic garbage collection.
  11333. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11334. \LangVec{} language.
  11335. %
  11336. \racket{We define the \code{vector}, \code{vector-ref},
  11337. \code{vector-set!}, and \code{vector-length} operations for
  11338. \LangVec{} in terms of the corresponding operations in Racket. One
  11339. subtle point is that the \code{vector-set!} operation returns the
  11340. \code{\#<void>} value.}
  11341. %
  11342. \python{We represent tuples with Python lists in the interpreter
  11343. because we need to write to them
  11344. (section~\ref{sec:expose-allocation}). (Python tuples are
  11345. immutable.) We define element access, the \code{is} operator, and
  11346. the \code{len} operator for \LangVec{} in terms of the corresponding
  11347. operations in Python.}
  11348. \begin{figure}[tbp]
  11349. \begin{tcolorbox}[colback=white]
  11350. {\if\edition\racketEd
  11351. \begin{lstlisting}
  11352. (define interp-Lvec-class
  11353. (class interp-Lwhile-class
  11354. (super-new)
  11355. (define/override (interp-op op)
  11356. (match op
  11357. ['eq? (lambda (v1 v2)
  11358. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11359. (and (boolean? v1) (boolean? v2))
  11360. (and (vector? v1) (vector? v2))
  11361. (and (void? v1) (void? v2)))
  11362. (eq? v1 v2)]))]
  11363. ['vector vector]
  11364. ['vector-length vector-length]
  11365. ['vector-ref vector-ref]
  11366. ['vector-set! vector-set!]
  11367. [else (super interp-op op)]
  11368. ))
  11369. (define/override ((interp-exp env) e)
  11370. (match e
  11371. [(HasType e t) ((interp-exp env) e)]
  11372. [else ((super interp-exp env) e)]
  11373. ))
  11374. ))
  11375. (define (interp-Lvec p)
  11376. (send (new interp-Lvec-class) interp-program p))
  11377. \end{lstlisting}
  11378. \fi}
  11379. %
  11380. {\if\edition\pythonEd\pythonColor
  11381. \begin{lstlisting}
  11382. class InterpLtup(InterpLwhile):
  11383. def interp_cmp(self, cmp):
  11384. match cmp:
  11385. case Is():
  11386. return lambda x, y: x is y
  11387. case _:
  11388. return super().interp_cmp(cmp)
  11389. def interp_exp(self, e, env):
  11390. match e:
  11391. case Tuple(es, Load()):
  11392. return tuple([self.interp_exp(e, env) for e in es])
  11393. case Subscript(tup, index, Load()):
  11394. t = self.interp_exp(tup, env)
  11395. n = self.interp_exp(index, env)
  11396. return t[n]
  11397. case _:
  11398. return super().interp_exp(e, env)
  11399. \end{lstlisting}
  11400. \fi}
  11401. \end{tcolorbox}
  11402. \caption{Interpreter for the \LangVec{} language.}
  11403. \label{fig:interp-Lvec}
  11404. \end{figure}
  11405. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11406. \LangVec{}.
  11407. %
  11408. The type of a tuple is a
  11409. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11410. type for each of its elements.
  11411. %
  11412. \racket{To create the s-expression for the \code{Vector} type, we use the
  11413. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11414. operator} \code{,@} to insert the list \code{t*} without its usual
  11415. start and end parentheses. \index{subject}{unquote-splicing}}
  11416. %
  11417. The type of accessing the ith element of a tuple is the ith element
  11418. type of the tuple's type, if there is one. If not, an error is
  11419. signaled. Note that the index \code{i} is required to be a constant
  11420. integer (and not, for example, a call to
  11421. \racket{\code{read}}\python{input\_int}) so that the type checker
  11422. can determine the element's type given the tuple type.
  11423. %
  11424. \racket{
  11425. Regarding writing an element to a tuple, the element's type must
  11426. be equal to the ith element type of the tuple's type.
  11427. The result type is \code{Void}.}
  11428. %% When allocating a tuple,
  11429. %% we need to know which elements of the tuple are themselves tuples for
  11430. %% the purposes of garbage collection. We can obtain this information
  11431. %% during type checking. The type checker shown in
  11432. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11433. %% expression; it also
  11434. %% %
  11435. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11436. %% where $T$ is the tuple's type.
  11437. %
  11438. %records the type of each tuple expression in a new field named \code{has\_type}.
  11439. \begin{figure}[tp]
  11440. \begin{tcolorbox}[colback=white]
  11441. {\if\edition\racketEd
  11442. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11443. (define type-check-Lvec-class
  11444. (class type-check-Lif-class
  11445. (super-new)
  11446. (inherit check-type-equal?)
  11447. (define/override (type-check-exp env)
  11448. (lambda (e)
  11449. (define recur (type-check-exp env))
  11450. (match e
  11451. [(Prim 'vector es)
  11452. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11453. (define t `(Vector ,@t*))
  11454. (values (Prim 'vector e*) t)]
  11455. [(Prim 'vector-ref (list e1 (Int i)))
  11456. (define-values (e1^ t) (recur e1))
  11457. (match t
  11458. [`(Vector ,ts ...)
  11459. (unless (and (0 . <= . i) (i . < . (length ts)))
  11460. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11461. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11462. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11463. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11464. (define-values (e-vec t-vec) (recur e1))
  11465. (define-values (e-elt^ t-elt) (recur elt))
  11466. (match t-vec
  11467. [`(Vector ,ts ...)
  11468. (unless (and (0 . <= . i) (i . < . (length ts)))
  11469. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11470. (check-type-equal? (list-ref ts i) t-elt e)
  11471. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11472. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11473. [(Prim 'vector-length (list e))
  11474. (define-values (e^ t) (recur e))
  11475. (match t
  11476. [`(Vector ,ts ...)
  11477. (values (Prim 'vector-length (list e^)) 'Integer)]
  11478. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11479. [(Prim 'eq? (list arg1 arg2))
  11480. (define-values (e1 t1) (recur arg1))
  11481. (define-values (e2 t2) (recur arg2))
  11482. (match* (t1 t2)
  11483. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11484. [(other wise) (check-type-equal? t1 t2 e)])
  11485. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11486. [else ((super type-check-exp env) e)]
  11487. )))
  11488. ))
  11489. (define (type-check-Lvec p)
  11490. (send (new type-check-Lvec-class) type-check-program p))
  11491. \end{lstlisting}
  11492. \fi}
  11493. {\if\edition\pythonEd\pythonColor
  11494. \begin{lstlisting}
  11495. class TypeCheckLtup(TypeCheckLwhile):
  11496. def type_check_exp(self, e, env):
  11497. match e:
  11498. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11499. l = self.type_check_exp(left, env)
  11500. r = self.type_check_exp(right, env)
  11501. check_type_equal(l, r, e)
  11502. return bool
  11503. case Tuple(es, Load()):
  11504. ts = [self.type_check_exp(e, env) for e in es]
  11505. e.has_type = TupleType(ts)
  11506. return e.has_type
  11507. case Subscript(tup, Constant(i), Load()):
  11508. tup_ty = self.type_check_exp(tup, env)
  11509. i_ty = self.type_check_exp(Constant(i), env)
  11510. check_type_equal(i_ty, int, i)
  11511. match tup_ty:
  11512. case TupleType(ts):
  11513. return ts[i]
  11514. case _:
  11515. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11516. case _:
  11517. return super().type_check_exp(e, env)
  11518. \end{lstlisting}
  11519. \fi}
  11520. \end{tcolorbox}
  11521. \caption{Type checker for the \LangVec{} language.}
  11522. \label{fig:type-check-Lvec}
  11523. \end{figure}
  11524. \section{Garbage Collection}
  11525. \label{sec:GC}
  11526. Garbage collection is a runtime technique for reclaiming space on the
  11527. heap that will not be used in the future of the running program. We
  11528. use the term \emph{object}\index{subject}{object} to refer to any
  11529. value that is stored in the heap, which for now includes only
  11530. tuples.%
  11531. %
  11532. \footnote{The term \emph{object} as it is used in the context of
  11533. object-oriented programming has a more specific meaning than the
  11534. way in which we use the term here.}
  11535. %
  11536. Unfortunately, it is impossible to know precisely which objects will
  11537. be accessed in the future and which will not. Instead, garbage
  11538. collectors overapproximate the set of objects that will be accessed by
  11539. identifying which objects can possibly be accessed. The running
  11540. program can directly access objects that are in registers and on the
  11541. procedure call stack. It can also transitively access the elements of
  11542. tuples, starting with a tuple whose address is in a register or on the
  11543. procedure call stack. We define the \emph{root
  11544. set}\index{subject}{root set} to be all the tuple addresses that are
  11545. in registers or on the procedure call stack. We define the \emph{live
  11546. objects}\index{subject}{live objects} to be the objects that are
  11547. reachable from the root set. Garbage collectors reclaim the space that
  11548. is allocated to objects that are no longer live. \index{subject}{allocate}
  11549. That means that some objects may not get reclaimed as soon as they could be,
  11550. but at least
  11551. garbage collectors do not reclaim the space dedicated to objects that
  11552. will be accessed in the future! The programmer can influence which
  11553. objects get reclaimed by causing them to become unreachable.
  11554. So the goal of the garbage collector is twofold:
  11555. \begin{enumerate}
  11556. \item to preserve all the live objects, and
  11557. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11558. \end{enumerate}
  11559. \subsection{Two-Space Copying Collector}
  11560. Here we study a relatively simple algorithm for garbage collection
  11561. that is the basis of many state-of-the-art garbage
  11562. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11563. particular, we describe a two-space copying
  11564. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11565. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11566. collector} \index{subject}{two-space copying collector}
  11567. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11568. what happens in a two-space collector, showing two time steps, prior
  11569. to garbage collection (on the top) and after garbage collection (on
  11570. the bottom). In a two-space collector, the heap is divided into two
  11571. parts named the FromSpace\index{subject}{FromSpace} and the
  11572. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11573. FromSpace until there is not enough room for the next allocation
  11574. request. At that point, the garbage collector goes to work to make
  11575. room for the next allocation.
  11576. A copying collector makes more room by copying all the live objects
  11577. from the FromSpace into the ToSpace and then performs a sleight of
  11578. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11579. as the new ToSpace. In the example shown in
  11580. figure~\ref{fig:copying-collector}, the root set consists of three
  11581. pointers, one in a register and two on the stack. All the live
  11582. objects have been copied to the ToSpace (the right-hand side of
  11583. figure~\ref{fig:copying-collector}) in a way that preserves the
  11584. pointer relationships. For example, the pointer in the register still
  11585. points to a tuple that in turn points to two other tuples. There are
  11586. four tuples that are not reachable from the root set and therefore do
  11587. not get copied into the ToSpace.
  11588. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11589. created by a well-typed program in \LangVec{} because it contains a
  11590. cycle. However, creating cycles will be possible once we get to
  11591. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11592. to deal with cycles to begin with, so we will not need to revisit this
  11593. issue.
  11594. \begin{figure}[tbp]
  11595. \centering
  11596. \begin{tcolorbox}[colback=white]
  11597. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11598. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11599. \\[5ex]
  11600. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11601. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11602. \end{tcolorbox}
  11603. \caption{A copying collector in action.}
  11604. \label{fig:copying-collector}
  11605. \end{figure}
  11606. \subsection{Graph Copying via Cheney's Algorithm}
  11607. \label{sec:cheney}
  11608. \index{subject}{Cheney's algorithm}
  11609. Let us take a closer look at the copying of the live objects. The
  11610. allocated\index{subject}{allocate} objects and pointers can be viewed
  11611. as a graph, and we need to copy the part of the graph that is
  11612. reachable from the root set. To make sure that we copy all the
  11613. reachable vertices in the graph, we need an exhaustive graph traversal
  11614. algorithm, such as depth-first search or breadth-first
  11615. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11616. take into account the possibility of cycles by marking which vertices
  11617. have already been visited, so to ensure termination of the
  11618. algorithm. These search algorithms also use a data structure such as a
  11619. stack or queue as a to-do list to keep track of the vertices that need
  11620. to be visited. We use breadth-first search and a trick due to
  11621. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11622. copying tuples into the ToSpace.
  11623. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11624. copy progresses. The queue is represented by a chunk of contiguous
  11625. memory at the beginning of the ToSpace, using two pointers to track
  11626. the front and the back of the queue, called the \emph{free pointer}
  11627. and the \emph{scan pointer}, respectively. The algorithm starts by
  11628. copying all tuples that are immediately reachable from the root set
  11629. into the ToSpace to form the initial queue. When we copy a tuple, we
  11630. mark the old tuple to indicate that it has been visited. We discuss
  11631. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11632. that any pointers inside the copied tuples in the queue still point
  11633. back to the FromSpace. Once the initial queue has been created, the
  11634. algorithm enters a loop in which it repeatedly processes the tuple at
  11635. the front of the queue and pops it off the queue. To process a tuple,
  11636. the algorithm copies all the objects that are directly reachable from it
  11637. to the ToSpace, placing them at the back of the queue. The algorithm
  11638. then updates the pointers in the popped tuple so that they point to the
  11639. newly copied objects.
  11640. \begin{figure}[tbp]
  11641. \centering
  11642. \begin{tcolorbox}[colback=white]
  11643. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  11644. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  11645. \end{tcolorbox}
  11646. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11647. \label{fig:cheney}
  11648. \end{figure}
  11649. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11650. tuple whose second element is $42$ to the back of the queue. The other
  11651. pointer goes to a tuple that has already been copied, so we do not
  11652. need to copy it again, but we do need to update the pointer to the new
  11653. location. This can be accomplished by storing a \emph{forwarding
  11654. pointer}\index{subject}{forwarding pointer} to the new location in the
  11655. old tuple, when we initially copied the tuple into the
  11656. ToSpace. This completes one step of the algorithm. The algorithm
  11657. continues in this way until the queue is empty; that is, when the scan
  11658. pointer catches up with the free pointer.
  11659. \subsection{Data Representation}
  11660. \label{sec:data-rep-gc}
  11661. The garbage collector places some requirements on the data
  11662. representations used by our compiler. First, the garbage collector
  11663. needs to distinguish between pointers and other kinds of data such as
  11664. integers. The following are several ways to accomplish this:
  11665. \begin{enumerate}
  11666. \item Attach a tag to each object that identifies what type of
  11667. object it is~\citep{McCarthy:1960dz}.
  11668. \item Store different types of objects in different
  11669. regions~\citep{Steele:1977ab}.
  11670. \item Use type information from the program to either (a) generate
  11671. type-specific code for collecting, or (b) generate tables that
  11672. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11673. \end{enumerate}
  11674. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11675. need to tag objects in any case, so option 1 is a natural choice for those
  11676. languages. However, \LangVec{} is a statically typed language, so it
  11677. would be unfortunate to require tags on every object, especially small
  11678. and pervasive objects like integers and Booleans. Option 3 is the
  11679. best-performing choice for statically typed languages, but it comes with
  11680. a relatively high implementation complexity. To keep this chapter
  11681. within a reasonable scope of complexity, we recommend a combination of options
  11682. 1 and 2, using separate strategies for the stack and the heap.
  11683. Regarding the stack, we recommend using a separate stack for pointers,
  11684. which we call the \emph{root stack}\index{subject}{root stack}
  11685. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11686. That is, when a local variable needs to be spilled and is of type
  11687. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11688. root stack instead of putting it on the procedure call
  11689. stack. Furthermore, we always spill tuple-typed variables if they are
  11690. live during a call to the collector, thereby ensuring that no pointers
  11691. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11692. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11693. contrasts it with the data layout using a root stack. The root stack
  11694. contains the two pointers from the regular stack and also the pointer
  11695. in the second register.
  11696. \begin{figure}[tbp]
  11697. \centering
  11698. \begin{tcolorbox}[colback=white]
  11699. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11700. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11701. \end{tcolorbox}
  11702. \caption{Maintaining a root stack to facilitate garbage collection.}
  11703. \label{fig:shadow-stack}
  11704. \end{figure}
  11705. The problem of distinguishing between pointers and other kinds of data
  11706. also arises inside each tuple on the heap. We solve this problem by
  11707. attaching a tag, an extra 64 bits, to each
  11708. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11709. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11710. Note that we have drawn the bits in a big-endian way, from right to left,
  11711. with bit location 0 (the least significant bit) on the far right,
  11712. which corresponds to the direction of the x86 shifting instructions
  11713. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11714. is dedicated to specifying which elements of the tuple are pointers,
  11715. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11716. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11717. data. The pointer mask starts at bit location 7. We limit tuples to a
  11718. maximum size of fifty elements, so we need 50 bits for the pointer
  11719. mask.%
  11720. %
  11721. \footnote{A production-quality compiler would handle
  11722. arbitrarily sized tuples and use a more complex approach.}
  11723. %
  11724. The tag also contains two other pieces of information. The length of
  11725. the tuple (number of elements) is stored in bits at locations 1 through
  11726. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11727. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11728. has not yet been copied. If the bit has value 0, then the entire tag
  11729. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11730. zero in any case, because our tuples are 8-byte aligned.)
  11731. \begin{figure}[tbp]
  11732. \centering
  11733. \begin{tcolorbox}[colback=white]
  11734. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11735. \end{tcolorbox}
  11736. \caption{Representation of tuples in the heap.}
  11737. \label{fig:tuple-rep}
  11738. \end{figure}
  11739. \subsection{Implementation of the Garbage Collector}
  11740. \label{sec:organize-gz}
  11741. \index{subject}{prelude}
  11742. An implementation of the copying collector is provided in the
  11743. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11744. interface to the garbage collector that is used by the compiler. The
  11745. \code{initialize} function creates the FromSpace, ToSpace, and root
  11746. stack and should be called in the prelude of the \code{main}
  11747. function. The arguments of \code{initialize} are the root stack size
  11748. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11749. good choice for both. The \code{initialize} function puts the address
  11750. of the beginning of the FromSpace into the global variable
  11751. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11752. the address that is one past the last element of the FromSpace. We use
  11753. half-open intervals to represent chunks of
  11754. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11755. points to the first element of the root stack.
  11756. As long as there is room left in the FromSpace, your generated code
  11757. can allocate\index{subject}{allocate} tuples simply by moving the
  11758. \code{free\_ptr} forward.
  11759. %
  11760. The amount of room left in the FromSpace is the difference between the
  11761. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11762. function should be called when there is not enough room left in the
  11763. FromSpace for the next allocation. The \code{collect} function takes
  11764. a pointer to the current top of the root stack (one past the last item
  11765. that was pushed) and the number of bytes that need to be
  11766. allocated. The \code{collect} function performs the copying collection
  11767. and leaves the heap in a state such that there is enough room for the
  11768. next allocation.
  11769. \begin{figure}[tbp]
  11770. \begin{tcolorbox}[colback=white]
  11771. \begin{lstlisting}
  11772. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11773. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11774. int64_t* free_ptr;
  11775. int64_t* fromspace_begin;
  11776. int64_t* fromspace_end;
  11777. int64_t** rootstack_begin;
  11778. \end{lstlisting}
  11779. \end{tcolorbox}
  11780. \caption{The compiler's interface to the garbage collector.}
  11781. \label{fig:gc-header}
  11782. \end{figure}
  11783. %% \begin{exercise}
  11784. %% In the file \code{runtime.c} you will find the implementation of
  11785. %% \code{initialize} and a partial implementation of \code{collect}.
  11786. %% The \code{collect} function calls another function, \code{cheney},
  11787. %% to perform the actual copy, and that function is left to the reader
  11788. %% to implement. The following is the prototype for \code{cheney}.
  11789. %% \begin{lstlisting}
  11790. %% static void cheney(int64_t** rootstack_ptr);
  11791. %% \end{lstlisting}
  11792. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11793. %% rootstack (which is an array of pointers). The \code{cheney} function
  11794. %% also communicates with \code{collect} through the global
  11795. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11796. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11797. %% the ToSpace:
  11798. %% \begin{lstlisting}
  11799. %% static int64_t* tospace_begin;
  11800. %% static int64_t* tospace_end;
  11801. %% \end{lstlisting}
  11802. %% The job of the \code{cheney} function is to copy all the live
  11803. %% objects (reachable from the root stack) into the ToSpace, update
  11804. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11805. %% update the root stack so that it points to the objects in the
  11806. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11807. %% and ToSpace.
  11808. %% \end{exercise}
  11809. The introduction of garbage collection has a nontrivial impact on our
  11810. compiler passes. We introduce a new compiler pass named
  11811. \code{expose\_allocation} that elaborates the code for allocating
  11812. tuples. We also make significant changes to
  11813. \code{select\_instructions}, \code{build\_interference},
  11814. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11815. make minor changes in several more passes.
  11816. The following program serves as our running example. It creates
  11817. two tuples, one nested inside the other. Both tuples have length
  11818. one. The program accesses the element in the inner tuple.
  11819. % tests/vectors_test_17.rkt
  11820. {\if\edition\racketEd
  11821. \begin{lstlisting}
  11822. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11823. \end{lstlisting}
  11824. \fi}
  11825. {\if\edition\pythonEd\pythonColor
  11826. \begin{lstlisting}
  11827. print( ((42,),)[0][0] )
  11828. \end{lstlisting}
  11829. \fi}
  11830. %% {\if\edition\racketEd
  11831. %% \section{Shrink}
  11832. %% \label{sec:shrink-Lvec}
  11833. %% Recall that the \code{shrink} pass translates the primitives operators
  11834. %% into a smaller set of primitives.
  11835. %% %
  11836. %% This pass comes after type checking, and the type checker adds a
  11837. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11838. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11839. %% \fi}
  11840. \section{Expose Allocation}
  11841. \label{sec:expose-allocation}
  11842. The pass \code{expose\_allocation} lowers tuple creation into making a
  11843. conditional call to the collector followed by allocating the
  11844. appropriate amount of memory and initializing it. We choose to place
  11845. the \code{expose\_allocation} pass before
  11846. \code{remove\_complex\_operands} because it generates
  11847. code that contains complex operands.
  11848. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11849. that replaces tuple creation with new lower-level forms that we use in the
  11850. translation of tuple creation.
  11851. %
  11852. {\if\edition\racketEd
  11853. \[
  11854. \begin{array}{lcl}
  11855. \Exp &::=& \cdots
  11856. \MID (\key{collect} \,\itm{int})
  11857. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11858. \MID (\key{global-value} \,\itm{name})
  11859. \end{array}
  11860. \]
  11861. \fi}
  11862. {\if\edition\pythonEd\pythonColor
  11863. \[
  11864. \begin{array}{lcl}
  11865. \Exp &::=& \cdots\\
  11866. &\MID& \key{collect}(\itm{int})
  11867. \MID \key{allocate}(\itm{int},\itm{type})
  11868. \MID \key{global\_value}(\itm{name}) \\
  11869. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  11870. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11871. \end{array}
  11872. \]
  11873. \fi}
  11874. %
  11875. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11876. make sure that there are $n$ bytes ready to be allocated. During
  11877. instruction selection\index{subject}{instruction selection},
  11878. the \CCOLLECT{$n$} form will become a call to
  11879. the \code{collect} function in \code{runtime.c}.
  11880. %
  11881. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11882. space at the front for the 64-bit tag), but the elements are not
  11883. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11884. of the tuple:
  11885. %
  11886. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11887. %
  11888. where $\Type_i$ is the type of the $i$th element.
  11889. %
  11890. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11891. variable, such as \code{free\_ptr}.
  11892. %
  11893. \python{The \code{begin} form is an expression that executes a
  11894. sequence of statements and then produces the value of the expression
  11895. at the end.}
  11896. \racket{
  11897. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11898. can be obtained by running the
  11899. \code{type-check-Lvec-has-type} type checker immediately before the
  11900. \code{expose\_allocation} pass. This version of the type checker
  11901. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11902. around each tuple creation. The concrete syntax
  11903. for \code{HasType} is \code{has-type}.}
  11904. The following shows the transformation of tuple creation into (1) a
  11905. sequence of temporary variable bindings for the initializing
  11906. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11907. \code{allocate}, and (4) the initialization of the tuple. The
  11908. \itm{len} placeholder refers to the length of the tuple, and
  11909. \itm{bytes} is the total number of bytes that need to be allocated for
  11910. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11911. %
  11912. \python{The \itm{type} needed for the second argument of the
  11913. \code{allocate} form can be obtained from the \code{has\_type} field
  11914. of the tuple AST node, which is stored there by running the type
  11915. checker for \LangVec{} immediately before this pass.}
  11916. %
  11917. \begin{center}
  11918. \begin{minipage}{\textwidth}
  11919. {\if\edition\racketEd
  11920. \begin{lstlisting}
  11921. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11922. |$\Longrightarrow$|
  11923. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11924. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11925. (global-value fromspace_end))
  11926. (void)
  11927. (collect |\itm{bytes}|))])
  11928. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11929. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11930. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11931. |$v$|) ... )))) ...)
  11932. \end{lstlisting}
  11933. \fi}
  11934. {\if\edition\pythonEd\pythonColor
  11935. \begin{lstlisting}
  11936. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11937. |$\Longrightarrow$|
  11938. begin:
  11939. |$x_0$| = |$e_0$|
  11940. |$\vdots$|
  11941. |$x_{n-1}$| = |$e_{n-1}$|
  11942. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11943. 0
  11944. else:
  11945. collect(|\itm{bytes}|)
  11946. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11947. |$v$|[0] = |$x_0$|
  11948. |$\vdots$|
  11949. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11950. |$v$|
  11951. \end{lstlisting}
  11952. \fi}
  11953. \end{minipage}
  11954. \end{center}
  11955. %
  11956. \noindent The sequencing of the initializing expressions
  11957. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  11958. they may trigger garbage collection and we cannot have an allocated
  11959. but uninitialized tuple on the heap during a collection.
  11960. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11961. \code{expose\_allocation} pass on our running example.
  11962. \begin{figure}[tbp]
  11963. \begin{tcolorbox}[colback=white]
  11964. % tests/s2_17.rkt
  11965. {\if\edition\racketEd
  11966. \begin{lstlisting}
  11967. (vector-ref
  11968. (vector-ref
  11969. (let ([vecinit6
  11970. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11971. (global-value fromspace_end))
  11972. (void)
  11973. (collect 16))])
  11974. (let ([alloc2 (allocate 1 (Vector Integer))])
  11975. (let ([_3 (vector-set! alloc2 0 42)])
  11976. alloc2)))])
  11977. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11978. (global-value fromspace_end))
  11979. (void)
  11980. (collect 16))])
  11981. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11982. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11983. alloc5))))
  11984. 0)
  11985. 0)
  11986. \end{lstlisting}
  11987. \fi}
  11988. {\if\edition\pythonEd\pythonColor
  11989. \begin{lstlisting}
  11990. print( |$T_1$|[0][0] )
  11991. \end{lstlisting}
  11992. where $T_1$ is
  11993. \begin{lstlisting}
  11994. begin:
  11995. tmp.1 = |$T_2$|
  11996. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11997. 0
  11998. else:
  11999. collect(16)
  12000. tmp.2 = allocate(1, TupleType(TupleType([int])))
  12001. tmp.2[0] = tmp.1
  12002. tmp.2
  12003. \end{lstlisting}
  12004. and $T_2$ is
  12005. \begin{lstlisting}
  12006. begin:
  12007. tmp.3 = 42
  12008. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  12009. 0
  12010. else:
  12011. collect(16)
  12012. tmp.4 = allocate(1, TupleType([int]))
  12013. tmp.4[0] = tmp.3
  12014. tmp.4
  12015. \end{lstlisting}
  12016. \fi}
  12017. \end{tcolorbox}
  12018. \caption{Output of the \code{expose\_allocation} pass.}
  12019. \label{fig:expose-alloc-output}
  12020. \end{figure}
  12021. \section{Remove Complex Operands}
  12022. \label{sec:remove-complex-opera-Lvec}
  12023. {\if\edition\racketEd
  12024. %
  12025. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12026. should be treated as complex operands.
  12027. %
  12028. \fi}
  12029. %
  12030. {\if\edition\pythonEd\pythonColor
  12031. %
  12032. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  12033. and tuple access should be treated as complex operands. The
  12034. sub-expressions of tuple access must be atomic.
  12035. %
  12036. \fi}
  12037. %% A new case for
  12038. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12039. %% handled carefully to prevent the \code{Prim} node from being separated
  12040. %% from its enclosing \code{HasType}.
  12041. Figure~\ref{fig:Lvec-anf-syntax}
  12042. shows the grammar for the output language \LangAllocANF{} of this
  12043. pass, which is \LangAlloc{} in monadic normal form.
  12044. \newcommand{\LtupMonadASTRacket}{
  12045. \begin{array}{rcl}
  12046. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12047. \MID \GLOBALVALUE{\Var}
  12048. \end{array}
  12049. }
  12050. \newcommand{\LtupMonadASTPython}{
  12051. \begin{array}{rcl}
  12052. \Exp &::=& \GET{\Atm}{\Atm} \\
  12053. &\MID& \LEN{\Atm}\\
  12054. &\MID& \ALLOCATE{\Int}{\Type}
  12055. \MID \GLOBALVALUE{\Var} \\
  12056. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12057. &\MID& \COLLECT{\Int}
  12058. \end{array}
  12059. }
  12060. \begin{figure}[tp]
  12061. \centering
  12062. \begin{tcolorbox}[colback=white]
  12063. \small
  12064. {\if\edition\racketEd
  12065. \[
  12066. \begin{array}{l}
  12067. \gray{\LvarMonadASTRacket} \\ \hline
  12068. \gray{\LifMonadASTRacket} \\ \hline
  12069. \gray{\LwhileMonadASTRacket} \\ \hline
  12070. \LtupMonadASTRacket \\
  12071. \begin{array}{rcl}
  12072. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12073. \end{array}
  12074. \end{array}
  12075. \]
  12076. \fi}
  12077. {\if\edition\pythonEd\pythonColor
  12078. \[
  12079. \begin{array}{l}
  12080. \gray{\LvarMonadASTPython} \\ \hline
  12081. \gray{\LifMonadASTPython} \\ \hline
  12082. \gray{\LwhileMonadASTPython} \\ \hline
  12083. \LtupMonadASTPython \\
  12084. \begin{array}{rcl}
  12085. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12086. \end{array}
  12087. \end{array}
  12088. \]
  12089. \fi}
  12090. \end{tcolorbox}
  12091. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12092. \label{fig:Lvec-anf-syntax}
  12093. \end{figure}
  12094. \section{Explicate Control and the \LangCVec{} Language}
  12095. \label{sec:explicate-control-r3}
  12096. \newcommand{\CtupASTRacket}{
  12097. \begin{array}{lcl}
  12098. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12099. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12100. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12101. &\MID& \VECLEN{\Atm} \\
  12102. &\MID& \GLOBALVALUE{\Var} \\
  12103. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12104. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12105. \end{array}
  12106. }
  12107. \newcommand{\CtupASTPython}{
  12108. \begin{array}{lcl}
  12109. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12110. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12111. \Stmt &::=& \COLLECT{\Int} \\
  12112. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12113. \end{array}
  12114. }
  12115. \begin{figure}[tp]
  12116. \begin{tcolorbox}[colback=white]
  12117. \small
  12118. {\if\edition\racketEd
  12119. \[
  12120. \begin{array}{l}
  12121. \gray{\CvarASTRacket} \\ \hline
  12122. \gray{\CifASTRacket} \\ \hline
  12123. \gray{\CloopASTRacket} \\ \hline
  12124. \CtupASTRacket \\
  12125. \begin{array}{lcl}
  12126. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12127. \end{array}
  12128. \end{array}
  12129. \]
  12130. \fi}
  12131. {\if\edition\pythonEd\pythonColor
  12132. \[
  12133. \begin{array}{l}
  12134. \gray{\CifASTPython} \\ \hline
  12135. \CtupASTPython \\
  12136. \begin{array}{lcl}
  12137. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  12138. \end{array}
  12139. \end{array}
  12140. \]
  12141. \fi}
  12142. \end{tcolorbox}
  12143. \caption{The abstract syntax of \LangCVec{}, extending
  12144. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12145. (figure~\ref{fig:c1-syntax})}.}
  12146. \label{fig:c2-syntax}
  12147. \end{figure}
  12148. The output of \code{explicate\_control} is a program in the
  12149. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12150. shows the definition of the abstract syntax.
  12151. %
  12152. %% \racket{(The concrete syntax is defined in
  12153. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12154. %
  12155. The new expressions of \LangCVec{} include \key{allocate},
  12156. %
  12157. \racket{\key{vector-ref}, and \key{vector-set!},}
  12158. %
  12159. \python{accessing tuple elements,}
  12160. %
  12161. and \key{global\_value}.
  12162. %
  12163. \python{\LangCVec{} also includes the \code{collect} statement and
  12164. assignment to a tuple element.}
  12165. %
  12166. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12167. %
  12168. The \code{explicate\_control} pass can treat these new forms much like
  12169. the other forms that we've already encountered. The output of the
  12170. \code{explicate\_control} pass on the running example is shown on the
  12171. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12172. section.
  12173. \section{Select Instructions and the \LangXGlobal{} Language}
  12174. \label{sec:select-instructions-gc}
  12175. \index{subject}{select instructions}
  12176. %% void (rep as zero)
  12177. %% allocate
  12178. %% collect (callq collect)
  12179. %% vector-ref
  12180. %% vector-set!
  12181. %% vector-length
  12182. %% global (postpone)
  12183. In this pass we generate x86 code for most of the new operations that
  12184. are needed to compile tuples, including \code{Allocate},
  12185. \code{Collect}, and accessing tuple elements.
  12186. %
  12187. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12188. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12189. \ref{fig:x86-2}). \index{subject}{x86}
  12190. The tuple read and write forms translate into \code{movq}
  12191. instructions. (The $+1$ in the offset serves to move past the tag at the
  12192. beginning of the tuple representation.)
  12193. %
  12194. \begin{center}
  12195. \begin{minipage}{\textwidth}
  12196. {\if\edition\racketEd
  12197. \begin{lstlisting}
  12198. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12199. |$\Longrightarrow$|
  12200. movq |$\itm{tup}'$|, %r11
  12201. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12202. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12203. |$\Longrightarrow$|
  12204. movq |$\itm{tup}'$|, %r11
  12205. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12206. movq $0, |$\itm{lhs'}$|
  12207. \end{lstlisting}
  12208. \fi}
  12209. {\if\edition\pythonEd\pythonColor
  12210. \begin{lstlisting}
  12211. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12212. |$\Longrightarrow$|
  12213. movq |$\itm{tup}'$|, %r11
  12214. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12215. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12216. |$\Longrightarrow$|
  12217. movq |$\itm{tup}'$|, %r11
  12218. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12219. \end{lstlisting}
  12220. \fi}
  12221. \end{minipage}
  12222. \end{center}
  12223. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12224. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12225. are obtained by translating from \LangCVec{} to x86.
  12226. %
  12227. The move of $\itm{tup}'$ to
  12228. register \code{r11} ensures that the offset expression
  12229. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12230. removing \code{r11} from consideration by the register allocating.
  12231. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12232. \code{rax}. Then the generated code for tuple assignment would be
  12233. \begin{lstlisting}
  12234. movq |$\itm{tup}'$|, %rax
  12235. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12236. \end{lstlisting}
  12237. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12238. \code{patch\_instructions} would insert a move through \code{rax}
  12239. as follows:
  12240. \begin{lstlisting}
  12241. movq |$\itm{tup}'$|, %rax
  12242. movq |$\itm{rhs}'$|, %rax
  12243. movq %rax, |$8(n+1)$|(%rax)
  12244. \end{lstlisting}
  12245. However, this sequence of instructions does not work because we're
  12246. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12247. $\itm{rhs}'$) at the same time!
  12248. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12249. be translated into a sequence of instructions that read the tag of the
  12250. tuple and extract the 6 bits that represent the tuple length, which
  12251. are the bits starting at index 1 and going up to and including bit 6.
  12252. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12253. (shift right) can be used to accomplish this.
  12254. We compile the \code{allocate} form to operations on the
  12255. \code{free\_ptr}, as shown next. This approach is called
  12256. \emph{inline allocation} because it implements allocation without a
  12257. function call by simply incrementing the allocation pointer. It is much
  12258. more efficient than calling a function for each allocation. The
  12259. address in the \code{free\_ptr} is the next free address in the
  12260. FromSpace, so we copy it into \code{r11} and then move it forward by
  12261. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12262. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12263. the tag. We then initialize the \itm{tag} and finally copy the
  12264. address in \code{r11} to the left-hand side. Refer to
  12265. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12266. %
  12267. \racket{We recommend using the Racket operations
  12268. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12269. during compilation.}
  12270. %
  12271. \python{We recommend using the bitwise-or operator \code{|} and the
  12272. shift-left operator \code{<<} to compute the tag during
  12273. compilation.}
  12274. %
  12275. The type annotation in the \code{allocate} form is used to determine
  12276. the pointer mask region of the tag.
  12277. %
  12278. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12279. address of the \code{free\_ptr} global variable using a special
  12280. instruction-pointer-relative addressing mode of the x86-64 processor.
  12281. In particular, the assembler computes the distance $d$ between the
  12282. address of \code{free\_ptr} and where the \code{rip} would be at that
  12283. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12284. \code{$d$(\%rip)}, which at runtime will compute the address of
  12285. \code{free\_ptr}.
  12286. %
  12287. {\if\edition\racketEd
  12288. \begin{lstlisting}
  12289. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12290. |$\Longrightarrow$|
  12291. movq free_ptr(%rip), %r11
  12292. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12293. movq $|$\itm{tag}$|, 0(%r11)
  12294. movq %r11, |$\itm{lhs}'$|
  12295. \end{lstlisting}
  12296. \fi}
  12297. {\if\edition\pythonEd\pythonColor
  12298. \begin{lstlisting}
  12299. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12300. |$\Longrightarrow$|
  12301. movq free_ptr(%rip), %r11
  12302. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12303. movq $|$\itm{tag}$|, 0(%r11)
  12304. movq %r11, |$\itm{lhs}'$|
  12305. \end{lstlisting}
  12306. \fi}
  12307. %
  12308. The \code{collect} form is compiled to a call to the \code{collect}
  12309. function in the runtime. The arguments to \code{collect} are (1) the
  12310. top of the root stack, and (2) the number of bytes that need to be
  12311. allocated. We use another dedicated register, \code{r15}, to store
  12312. the pointer to the top of the root stack. Therefore \code{r15} is not
  12313. available for use by the register allocator.
  12314. %
  12315. {\if\edition\racketEd
  12316. \begin{lstlisting}
  12317. (collect |$\itm{bytes}$|)
  12318. |$\Longrightarrow$|
  12319. movq %r15, %rdi
  12320. movq $|\itm{bytes}|, %rsi
  12321. callq collect
  12322. \end{lstlisting}
  12323. \fi}
  12324. {\if\edition\pythonEd\pythonColor
  12325. \begin{lstlisting}
  12326. collect(|$\itm{bytes}$|)
  12327. |$\Longrightarrow$|
  12328. movq %r15, %rdi
  12329. movq $|\itm{bytes}|, %rsi
  12330. callq collect
  12331. \end{lstlisting}
  12332. \fi}
  12333. \newcommand{\GrammarXGlobal}{
  12334. \begin{array}{lcl}
  12335. \Arg &::=& \itm{label} \key{(\%rip)}
  12336. \end{array}
  12337. }
  12338. \newcommand{\ASTXGlobalRacket}{
  12339. \begin{array}{lcl}
  12340. \Arg &::=& \GLOBAL{\itm{label}}
  12341. \end{array}
  12342. }
  12343. \begin{figure}[tp]
  12344. \begin{tcolorbox}[colback=white]
  12345. \[
  12346. \begin{array}{l}
  12347. \gray{\GrammarXInt} \\ \hline
  12348. \gray{\GrammarXIf} \\ \hline
  12349. \GrammarXGlobal \\
  12350. \begin{array}{lcl}
  12351. \LangXGlobalM{} &::= & \key{.globl main} \\
  12352. & & \key{main:} \; \Instr^{*}
  12353. \end{array}
  12354. \end{array}
  12355. \]
  12356. \end{tcolorbox}
  12357. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12358. \label{fig:x86-2-concrete}
  12359. \end{figure}
  12360. \begin{figure}[tp]
  12361. \begin{tcolorbox}[colback=white]
  12362. \small
  12363. \[
  12364. \begin{array}{l}
  12365. \gray{\ASTXIntRacket} \\ \hline
  12366. \gray{\ASTXIfRacket} \\ \hline
  12367. \ASTXGlobalRacket \\
  12368. \begin{array}{lcl}
  12369. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12370. \end{array}
  12371. \end{array}
  12372. \]
  12373. \end{tcolorbox}
  12374. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12375. \label{fig:x86-2}
  12376. \end{figure}
  12377. The definitions of the concrete and abstract syntax of the
  12378. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12379. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12380. of global variables.
  12381. %
  12382. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12383. \code{select\_instructions} pass on the running example.
  12384. \begin{figure}[tbp]
  12385. \centering
  12386. \begin{tcolorbox}[colback=white]
  12387. % tests/s2_17.rkt
  12388. \begin{tabular}{lll}
  12389. \begin{minipage}{0.5\textwidth}
  12390. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12391. start:
  12392. tmp9 = (global-value free_ptr);
  12393. tmp0 = (+ tmp9 16);
  12394. tmp1 = (global-value fromspace_end);
  12395. if (< tmp0 tmp1)
  12396. goto block0;
  12397. else
  12398. goto block1;
  12399. block0:
  12400. _4 = (void);
  12401. goto block9;
  12402. block1:
  12403. (collect 16)
  12404. goto block9;
  12405. block9:
  12406. alloc2 = (allocate 1 (Vector Integer));
  12407. _3 = (vector-set! alloc2 0 42);
  12408. vecinit6 = alloc2;
  12409. tmp2 = (global-value free_ptr);
  12410. tmp3 = (+ tmp2 16);
  12411. tmp4 = (global-value fromspace_end);
  12412. if (< tmp3 tmp4)
  12413. goto block7;
  12414. else
  12415. goto block8;
  12416. block7:
  12417. _8 = (void);
  12418. goto block6;
  12419. block8:
  12420. (collect 16)
  12421. goto block6;
  12422. block6:
  12423. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12424. _7 = (vector-set! alloc5 0 vecinit6);
  12425. tmp5 = (vector-ref alloc5 0);
  12426. return (vector-ref tmp5 0);
  12427. \end{lstlisting}
  12428. \end{minipage}
  12429. &$\Rightarrow$&
  12430. \begin{minipage}{0.4\textwidth}
  12431. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12432. start:
  12433. movq free_ptr(%rip), tmp9
  12434. movq tmp9, tmp0
  12435. addq $16, tmp0
  12436. movq fromspace_end(%rip), tmp1
  12437. cmpq tmp1, tmp0
  12438. jl block0
  12439. jmp block1
  12440. block0:
  12441. movq $0, _4
  12442. jmp block9
  12443. block1:
  12444. movq %r15, %rdi
  12445. movq $16, %rsi
  12446. callq collect
  12447. jmp block9
  12448. block9:
  12449. movq free_ptr(%rip), %r11
  12450. addq $16, free_ptr(%rip)
  12451. movq $3, 0(%r11)
  12452. movq %r11, alloc2
  12453. movq alloc2, %r11
  12454. movq $42, 8(%r11)
  12455. movq $0, _3
  12456. movq alloc2, vecinit6
  12457. movq free_ptr(%rip), tmp2
  12458. movq tmp2, tmp3
  12459. addq $16, tmp3
  12460. movq fromspace_end(%rip), tmp4
  12461. cmpq tmp4, tmp3
  12462. jl block7
  12463. jmp block8
  12464. block7:
  12465. movq $0, _8
  12466. jmp block6
  12467. block8:
  12468. movq %r15, %rdi
  12469. movq $16, %rsi
  12470. callq collect
  12471. jmp block6
  12472. block6:
  12473. movq free_ptr(%rip), %r11
  12474. addq $16, free_ptr(%rip)
  12475. movq $131, 0(%r11)
  12476. movq %r11, alloc5
  12477. movq alloc5, %r11
  12478. movq vecinit6, 8(%r11)
  12479. movq $0, _7
  12480. movq alloc5, %r11
  12481. movq 8(%r11), tmp5
  12482. movq tmp5, %r11
  12483. movq 8(%r11), %rax
  12484. jmp conclusion
  12485. \end{lstlisting}
  12486. \end{minipage}
  12487. \end{tabular}
  12488. \end{tcolorbox}
  12489. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  12490. \code{select\_instructions} (\emph{right}) passes on the running
  12491. example.}
  12492. \label{fig:select-instr-output-gc}
  12493. \end{figure}
  12494. \clearpage
  12495. \section{Register Allocation}
  12496. \label{sec:reg-alloc-gc}
  12497. \index{subject}{register allocation}
  12498. As discussed previously in this chapter, the garbage collector needs to
  12499. access all the pointers in the root set, that is, all variables that
  12500. are tuples. It will be the responsibility of the register allocator
  12501. to make sure that
  12502. \begin{enumerate}
  12503. \item the root stack is used for spilling tuple-typed variables, and
  12504. \item if a tuple-typed variable is live during a call to the
  12505. collector, it must be spilled to ensure that it is visible to the
  12506. collector.
  12507. \end{enumerate}
  12508. The latter responsibility can be handled during construction of the
  12509. interference graph, by adding interference edges between the call-live
  12510. tuple-typed variables and all the callee-saved registers. (They
  12511. already interfere with the caller-saved registers.)
  12512. %
  12513. \racket{The type information for variables is in the \code{Program}
  12514. form, so we recommend adding another parameter to the
  12515. \code{build\_interference} function to communicate this alist.}
  12516. %
  12517. \python{The type information for variables is generated by the type
  12518. checker for \LangCVec{}, stored a field named \code{var\_types} in
  12519. the \code{CProgram} AST mode. You'll need to propagate that
  12520. information so that it is available in this pass.}
  12521. The spilling of tuple-typed variables to the root stack can be handled
  12522. after graph coloring, in choosing how to assign the colors
  12523. (integers) to registers and stack locations. The
  12524. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12525. changes to also record the number of spills to the root stack.
  12526. % build-interference
  12527. %
  12528. % callq
  12529. % extra parameter for var->type assoc. list
  12530. % update 'program' and 'if'
  12531. % allocate-registers
  12532. % allocate spilled vectors to the rootstack
  12533. % don't change color-graph
  12534. % TODO:
  12535. %\section{Patch Instructions}
  12536. %[mention that global variables are memory references]
  12537. \section{Prelude and Conclusion}
  12538. \label{sec:print-x86-gc}
  12539. \label{sec:prelude-conclusion-x86-gc}
  12540. \index{subject}{prelude}\index{subject}{conclusion}
  12541. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12542. \code{prelude\_and\_conclusion} pass on the running example. In the
  12543. prelude of the \code{main} function, we allocate space
  12544. on the root stack to make room for the spills of tuple-typed
  12545. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12546. taking care that the root stack grows up instead of down. For the
  12547. running example, there was just one spill, so we increment \code{r15}
  12548. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12549. One issue that deserves special care is that there may be a call to
  12550. \code{collect} prior to the initializing assignments for all the
  12551. variables in the root stack. We do not want the garbage collector to
  12552. mistakenly determine that some uninitialized variable is a pointer that
  12553. needs to be followed. Thus, we zero out all locations on the root
  12554. stack in the prelude of \code{main}. In
  12555. figure~\ref{fig:print-x86-output-gc}, the instruction
  12556. %
  12557. \lstinline{movq $0, 0(%r15)}
  12558. %
  12559. is sufficient to accomplish this task because there is only one spill.
  12560. In general, we have to clear as many words as there are spills of
  12561. tuple-typed variables. The garbage collector tests each root to see
  12562. if it is null prior to dereferencing it.
  12563. \begin{figure}[htbp]
  12564. % TODO: Python Version -Jeremy
  12565. \begin{tcolorbox}[colback=white]
  12566. \begin{minipage}[t]{0.5\textwidth}
  12567. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12568. .globl main
  12569. main:
  12570. pushq %rbp
  12571. movq %rsp, %rbp
  12572. subq $0, %rsp
  12573. movq $65536, %rdi
  12574. movq $65536, %rsi
  12575. callq initialize
  12576. movq rootstack_begin(%rip), %r15
  12577. movq $0, 0(%r15)
  12578. addq $8, %r15
  12579. jmp start
  12580. conclusion:
  12581. subq $8, %r15
  12582. addq $0, %rsp
  12583. popq %rbp
  12584. retq
  12585. \end{lstlisting}
  12586. \end{minipage}
  12587. \end{tcolorbox}
  12588. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  12589. \label{fig:print-x86-output-gc}
  12590. \end{figure}
  12591. \begin{figure}[tbp]
  12592. \begin{tcolorbox}[colback=white]
  12593. {\if\edition\racketEd
  12594. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12595. \node (Lvec) at (0,2) {\large \LangVec{}};
  12596. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12597. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12598. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12599. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12600. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12601. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12602. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12603. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12604. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12605. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12606. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12607. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12608. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12609. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12610. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12611. \path[->,bend left=15] (Lvec-4) edge [right] node
  12612. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12613. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12614. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12615. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12616. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12617. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12618. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12619. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12620. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12621. \end{tikzpicture}
  12622. \fi}
  12623. {\if\edition\pythonEd\pythonColor
  12624. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12625. \node (Lvec) at (0,2) {\large \LangVec{}};
  12626. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12627. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12628. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12629. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12630. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12631. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12632. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12633. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12634. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12635. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12636. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12637. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12638. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12639. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12640. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12641. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12642. \end{tikzpicture}
  12643. \fi}
  12644. \end{tcolorbox}
  12645. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12646. \label{fig:Lvec-passes}
  12647. \end{figure}
  12648. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12649. for the compilation of \LangVec{}.
  12650. \clearpage
  12651. {\if\edition\racketEd
  12652. \section{Challenge: Simple Structures}
  12653. \label{sec:simple-structures}
  12654. \index{subject}{struct}
  12655. \index{subject}{structure}
  12656. The language \LangStruct{} extends \LangVec{} with support for simple
  12657. structures. The definition of its concrete syntax is shown in
  12658. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12659. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12660. in Typed Racket is a user-defined data type that contains named fields
  12661. and that is heap allocated\index{subject}{heap allocated},
  12662. similarly to a vector. The following is an
  12663. example of a structure definition, in this case the definition of a
  12664. \code{point} type:
  12665. \begin{lstlisting}
  12666. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12667. \end{lstlisting}
  12668. \newcommand{\LstructGrammarRacket}{
  12669. \begin{array}{lcl}
  12670. \Type &::=& \Var \\
  12671. \Exp &::=& (\Var\;\Exp \ldots)\\
  12672. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12673. \end{array}
  12674. }
  12675. \newcommand{\LstructASTRacket}{
  12676. \begin{array}{lcl}
  12677. \Type &::=& \VAR{\Var} \\
  12678. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12679. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12680. \end{array}
  12681. }
  12682. \begin{figure}[tbp]
  12683. \centering
  12684. \begin{tcolorbox}[colback=white]
  12685. \[
  12686. \begin{array}{l}
  12687. \gray{\LintGrammarRacket{}} \\ \hline
  12688. \gray{\LvarGrammarRacket{}} \\ \hline
  12689. \gray{\LifGrammarRacket{}} \\ \hline
  12690. \gray{\LwhileGrammarRacket} \\ \hline
  12691. \gray{\LtupGrammarRacket} \\ \hline
  12692. \LstructGrammarRacket \\
  12693. \begin{array}{lcl}
  12694. \LangStruct{} &::=& \Def \ldots \; \Exp
  12695. \end{array}
  12696. \end{array}
  12697. \]
  12698. \end{tcolorbox}
  12699. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12700. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12701. \label{fig:Lstruct-concrete-syntax}
  12702. \end{figure}
  12703. \begin{figure}[tbp]
  12704. \centering
  12705. \begin{tcolorbox}[colback=white]
  12706. \small
  12707. \[
  12708. \begin{array}{l}
  12709. \gray{\LintASTRacket{}} \\ \hline
  12710. \gray{\LvarASTRacket{}} \\ \hline
  12711. \gray{\LifASTRacket{}} \\ \hline
  12712. \gray{\LwhileASTRacket} \\ \hline
  12713. \gray{\LtupASTRacket} \\ \hline
  12714. \LstructASTRacket \\
  12715. \begin{array}{lcl}
  12716. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12717. \end{array}
  12718. \end{array}
  12719. \]
  12720. \end{tcolorbox}
  12721. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12722. (figure~\ref{fig:Lvec-syntax}).}
  12723. \label{fig:Lstruct-syntax}
  12724. \end{figure}
  12725. An instance of a structure is created using function-call syntax, with
  12726. the name of the structure in the function position, as follows:
  12727. \begin{lstlisting}
  12728. (point 7 12)
  12729. \end{lstlisting}
  12730. Function-call syntax is also used to read a field of a structure. The
  12731. function name is formed by the structure name, a dash, and the field
  12732. name. The following example uses \code{point-x} and \code{point-y} to
  12733. access the \code{x} and \code{y} fields of two point instances:
  12734. \begin{center}
  12735. \begin{lstlisting}
  12736. (let ([pt1 (point 7 12)])
  12737. (let ([pt2 (point 4 3)])
  12738. (+ (- (point-x pt1) (point-x pt2))
  12739. (- (point-y pt1) (point-y pt2)))))
  12740. \end{lstlisting}
  12741. \end{center}
  12742. Similarly, to write to a field of a structure, use its set function,
  12743. whose name starts with \code{set-}, followed by the structure name,
  12744. then a dash, then the field name, and finally with an exclamation
  12745. mark. The following example uses \code{set-point-x!} to change the
  12746. \code{x} field from \code{7} to \code{42}:
  12747. \begin{center}
  12748. \begin{lstlisting}
  12749. (let ([pt (point 7 12)])
  12750. (let ([_ (set-point-x! pt 42)])
  12751. (point-x pt)))
  12752. \end{lstlisting}
  12753. \end{center}
  12754. \begin{exercise}\normalfont\normalsize
  12755. Create a type checker for \LangStruct{} by extending the type
  12756. checker for \LangVec{}. Extend your compiler with support for simple
  12757. structures, compiling \LangStruct{} to x86 assembly code. Create
  12758. five new test cases that use structures, and test your compiler.
  12759. \end{exercise}
  12760. % TODO: create an interpreter for L_struct
  12761. \clearpage
  12762. \fi}
  12763. \section{Challenge: Arrays}
  12764. \label{sec:arrays}
  12765. % TODO mention trapped-error
  12766. In this chapter we have studied tuples, that is, heterogeneous
  12767. sequences of elements whose length is determined at compile time. This
  12768. challenge is also about sequences, but this time the length is
  12769. determined at runtime and all the elements have the same type (they
  12770. are homogeneous). We use the term \emph{array} for this latter kind of
  12771. sequence.
  12772. %
  12773. \racket{
  12774. The Racket language does not distinguish between tuples and arrays;
  12775. they are both represented by vectors. However, Typed Racket
  12776. distinguishes between tuples and arrays: the \code{Vector} type is for
  12777. tuples, and the \code{Vectorof} type is for arrays.}%
  12778. \python{Arrays correspond to the \code{list} type in Python language.}
  12779. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  12780. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  12781. presents the definition of the abstract syntax, extending \LangVec{}
  12782. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  12783. %
  12784. \racket{\code{make-vector} primitive operator for creating an array,
  12785. whose arguments are the length of the array and an initial value for
  12786. all the elements in the array.}
  12787. \python{bracket notation for creating an array literal.}
  12788. \racket{The \code{vector-length},
  12789. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12790. for tuples become overloaded for use with arrays.}
  12791. \python{
  12792. The subscript operator becomes overloaded for use with arrays and tuples
  12793. and now may appear on the left-hand side of an assignment.
  12794. Note that the index of the subscript, when applied to an array, may be an
  12795. arbitrary expression and not just a constant integer.
  12796. The \code{len} function is also applicable to arrays.
  12797. }
  12798. %
  12799. We include integer multiplication in \LangArray{} because it is
  12800. useful in many examples involving arrays such as computing the
  12801. inner product of two arrays (figure~\ref{fig:inner_product}).
  12802. \newcommand{\LarrayGrammarRacket}{
  12803. \begin{array}{lcl}
  12804. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12805. \Exp &::=& \CMUL{\Exp}{\Exp}
  12806. \MID \CMAKEVEC{\Exp}{\Exp}
  12807. \end{array}
  12808. }
  12809. \newcommand{\LarrayASTRacket}{
  12810. \begin{array}{lcl}
  12811. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12812. \Exp &::=& \MUL{\Exp}{\Exp}
  12813. \MID \MAKEVEC{\Exp}{\Exp}
  12814. \end{array}
  12815. }
  12816. \newcommand{\LarrayGrammarPython}{
  12817. \begin{array}{lcl}
  12818. \Type &::=& \key{list}\LS\Type\RS \\
  12819. \Exp &::=& \CMUL{\Exp}{\Exp}
  12820. \MID \CGET{\Exp}{\Exp}
  12821. \MID \LS \Exp \code{,} \ldots \RS \\
  12822. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  12823. \end{array}
  12824. }
  12825. \newcommand{\LarrayASTPython}{
  12826. \begin{array}{lcl}
  12827. \Type &::=& \key{ListType}\LP\Type\RP \\
  12828. \Exp &::=& \MUL{\Exp}{\Exp}
  12829. \MID \GET{\Exp}{\Exp} \\
  12830. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  12831. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  12832. \end{array}
  12833. }
  12834. \begin{figure}[tp]
  12835. \centering
  12836. \begin{tcolorbox}[colback=white]
  12837. \small
  12838. {\if\edition\racketEd
  12839. \[
  12840. \begin{array}{l}
  12841. \gray{\LintGrammarRacket{}} \\ \hline
  12842. \gray{\LvarGrammarRacket{}} \\ \hline
  12843. \gray{\LifGrammarRacket{}} \\ \hline
  12844. \gray{\LwhileGrammarRacket} \\ \hline
  12845. \gray{\LtupGrammarRacket} \\ \hline
  12846. \LarrayGrammarRacket \\
  12847. \begin{array}{lcl}
  12848. \LangArray{} &::=& \Exp
  12849. \end{array}
  12850. \end{array}
  12851. \]
  12852. \fi}
  12853. {\if\edition\pythonEd\pythonColor
  12854. \[
  12855. \begin{array}{l}
  12856. \gray{\LintGrammarPython{}} \\ \hline
  12857. \gray{\LvarGrammarPython{}} \\ \hline
  12858. \gray{\LifGrammarPython{}} \\ \hline
  12859. \gray{\LwhileGrammarPython} \\ \hline
  12860. \gray{\LtupGrammarPython} \\ \hline
  12861. \LarrayGrammarPython \\
  12862. \begin{array}{rcl}
  12863. \LangArrayM{} &::=& \Stmt^{*}
  12864. \end{array}
  12865. \end{array}
  12866. \]
  12867. \fi}
  12868. \end{tcolorbox}
  12869. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12870. \label{fig:Lvecof-concrete-syntax}
  12871. \end{figure}
  12872. \begin{figure}[tp]
  12873. \centering
  12874. \begin{tcolorbox}[colback=white]
  12875. \small
  12876. {\if\edition\racketEd
  12877. \[
  12878. \begin{array}{l}
  12879. \gray{\LintASTRacket{}} \\ \hline
  12880. \gray{\LvarASTRacket{}} \\ \hline
  12881. \gray{\LifASTRacket{}} \\ \hline
  12882. \gray{\LwhileASTRacket} \\ \hline
  12883. \gray{\LtupASTRacket} \\ \hline
  12884. \LarrayASTRacket \\
  12885. \begin{array}{lcl}
  12886. \LangArray{} &::=& \Exp
  12887. \end{array}
  12888. \end{array}
  12889. \]
  12890. \fi}
  12891. {\if\edition\pythonEd\pythonColor
  12892. \[
  12893. \begin{array}{l}
  12894. \gray{\LintASTPython{}} \\ \hline
  12895. \gray{\LvarASTPython{}} \\ \hline
  12896. \gray{\LifASTPython{}} \\ \hline
  12897. \gray{\LwhileASTPython} \\ \hline
  12898. \gray{\LtupASTPython} \\ \hline
  12899. \LarrayASTPython \\
  12900. \begin{array}{rcl}
  12901. \LangArrayM{} &::=& \Stmt^{*}
  12902. \end{array}
  12903. \end{array}
  12904. \]
  12905. \fi}
  12906. \end{tcolorbox}
  12907. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12908. \label{fig:Lvecof-syntax}
  12909. \end{figure}
  12910. \begin{figure}[tp]
  12911. \begin{tcolorbox}[colback=white]
  12912. {\if\edition\racketEd
  12913. % TODO: remove the function from the following example, like the python version -Jeremy
  12914. \begin{lstlisting}
  12915. (let ([A (make-vector 2 2)])
  12916. (let ([B (make-vector 2 3)])
  12917. (let ([i 0])
  12918. (let ([prod 0])
  12919. (begin
  12920. (while (< i n)
  12921. (begin
  12922. (set! prod (+ prod (* (vector-ref A i)
  12923. (vector-ref B i))))
  12924. (set! i (+ i 1))))
  12925. prod)))))
  12926. \end{lstlisting}
  12927. \fi}
  12928. {\if\edition\pythonEd\pythonColor
  12929. \begin{lstlisting}
  12930. A = [2, 2]
  12931. B = [3, 3]
  12932. i = 0
  12933. prod = 0
  12934. while i != len(A):
  12935. prod = prod + A[i] * B[i]
  12936. i = i + 1
  12937. print( prod )
  12938. \end{lstlisting}
  12939. \fi}
  12940. \end{tcolorbox}
  12941. \caption{Example program that computes the inner product.}
  12942. \label{fig:inner_product}
  12943. \end{figure}
  12944. {\if\edition\racketEd
  12945. %
  12946. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12947. checker for \LangArray{}. The result type of
  12948. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12949. of the initializing expression. The length expression is required to
  12950. have type \code{Integer}. The type checking of the operators
  12951. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12952. updated to handle the situation in which the vector has type
  12953. \code{Vectorof}. In these cases we translate the operators to their
  12954. \code{vectorof} form so that later passes can easily distinguish
  12955. between operations on tuples versus arrays. We override the
  12956. \code{operator-types} method to provide the type signature for
  12957. multiplication: it takes two integers and returns an integer. \fi}
  12958. {\if\edition\pythonEd\pythonColor
  12959. %
  12960. The type checker for \LangArray{} is defined in
  12961. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12962. is \code{list[T]} where \code{T} is the type of the initializing
  12963. expressions. The type checking of the \code{len} function and the
  12964. subscript operator is updated to handle lists. The type checker now
  12965. also handles a subscript on the left-hand side of an assignment.
  12966. Regarding multiplication, it takes two integers and returns an
  12967. integer.
  12968. %
  12969. \fi}
  12970. \begin{figure}[tbp]
  12971. \begin{tcolorbox}[colback=white]
  12972. {\if\edition\racketEd
  12973. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12974. (define type-check-Lvecof-class
  12975. (class type-check-Lvec-class
  12976. (super-new)
  12977. (inherit check-type-equal?)
  12978. (define/override (operator-types)
  12979. (append '((* . ((Integer Integer) . Integer)))
  12980. (super operator-types)))
  12981. (define/override (type-check-exp env)
  12982. (lambda (e)
  12983. (define recur (type-check-exp env))
  12984. (match e
  12985. [(Prim 'make-vector (list e1 e2))
  12986. (define-values (e1^ t1) (recur e1))
  12987. (define-values (e2^ elt-type) (recur e2))
  12988. (define vec-type `(Vectorof ,elt-type))
  12989. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  12990. [(Prim 'vector-ref (list e1 e2))
  12991. (define-values (e1^ t1) (recur e1))
  12992. (define-values (e2^ t2) (recur e2))
  12993. (match* (t1 t2)
  12994. [(`(Vectorof ,elt-type) 'Integer)
  12995. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12996. [(other wise) ((super type-check-exp env) e)])]
  12997. [(Prim 'vector-set! (list e1 e2 e3) )
  12998. (define-values (e-vec t-vec) (recur e1))
  12999. (define-values (e2^ t2) (recur e2))
  13000. (define-values (e-arg^ t-arg) (recur e3))
  13001. (match t-vec
  13002. [`(Vectorof ,elt-type)
  13003. (check-type-equal? elt-type t-arg e)
  13004. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13005. [else ((super type-check-exp env) e)])]
  13006. [(Prim 'vector-length (list e1))
  13007. (define-values (e1^ t1) (recur e1))
  13008. (match t1
  13009. [`(Vectorof ,t)
  13010. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13011. [else ((super type-check-exp env) e)])]
  13012. [else ((super type-check-exp env) e)])))
  13013. ))
  13014. (define (type-check-Lvecof p)
  13015. (send (new type-check-Lvecof-class) type-check-program p))
  13016. \end{lstlisting}
  13017. \fi}
  13018. {\if\edition\pythonEd\pythonColor
  13019. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13020. class TypeCheckLarray(TypeCheckLtup):
  13021. def type_check_exp(self, e, env):
  13022. match e:
  13023. case ast.List(es, Load()):
  13024. ts = [self.type_check_exp(e, env) for e in es]
  13025. elt_ty = ts[0]
  13026. for (ty, elt) in zip(ts, es):
  13027. self.check_type_equal(elt_ty, ty, elt)
  13028. e.has_type = ListType(elt_ty)
  13029. return e.has_type
  13030. case Call(Name('len'), [tup]):
  13031. tup_t = self.type_check_exp(tup, env)
  13032. tup.has_type = tup_t
  13033. match tup_t:
  13034. case TupleType(ts):
  13035. return IntType()
  13036. case ListType(ty):
  13037. return IntType()
  13038. case _:
  13039. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13040. case Subscript(tup, index, Load()):
  13041. tup_ty = self.type_check_exp(tup, env)
  13042. index_ty = self.type_check_exp(index, env)
  13043. self.check_type_equal(index_ty, IntType(), index)
  13044. match tup_ty:
  13045. case TupleType(ts):
  13046. match index:
  13047. case Constant(i):
  13048. return ts[i]
  13049. case _:
  13050. raise Exception('subscript required constant integer index')
  13051. case ListType(ty):
  13052. return ty
  13053. case _:
  13054. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13055. case BinOp(left, Mult(), right):
  13056. l = self.type_check_exp(left, env)
  13057. self.check_type_equal(l, IntType(), left)
  13058. r = self.type_check_exp(right, env)
  13059. self.check_type_equal(r, IntType(), right)
  13060. return IntType()
  13061. case _:
  13062. return super().type_check_exp(e, env)
  13063. def type_check_stmts(self, ss, env):
  13064. if len(ss) == 0:
  13065. return VoidType()
  13066. match ss[0]:
  13067. case Assign([Subscript(tup, index, Store())], value):
  13068. tup_t = self.type_check_exp(tup, env)
  13069. value_t = self.type_check_exp(value, env)
  13070. index_ty = self.type_check_exp(index, env)
  13071. self.check_type_equal(index_ty, IntType(), index)
  13072. match tup_t:
  13073. case ListType(ty):
  13074. self.check_type_equal(ty, value_t, ss[0])
  13075. case TupleType(ts):
  13076. return self.type_check_stmts(ss, env)
  13077. case _:
  13078. raise Exception('type_check_stmts: '
  13079. 'expected tuple or list, not ' + repr(tup_t))
  13080. return self.type_check_stmts(ss[1:], env)
  13081. case _:
  13082. return super().type_check_stmts(ss, env)
  13083. \end{lstlisting}
  13084. \fi}
  13085. \end{tcolorbox}
  13086. \caption{Type checker for the \LangArray{} language.}
  13087. \label{fig:type-check-Lvecof}
  13088. \end{figure}
  13089. The definition of the interpreter for \LangArray{} is shown in
  13090. figure~\ref{fig:interp-Lvecof}.
  13091. \racket{The \code{make-vector} operator is
  13092. interpreted using Racket's \code{make-vector} function,
  13093. and multiplication is interpreted using \code{fx*},
  13094. which is multiplication for \code{fixnum} integers.
  13095. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13096. we translate array access operations
  13097. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13098. which we interpret using \code{vector} operations with additional
  13099. bounds checks that signal a \code{trapped-error}.
  13100. }
  13101. %
  13102. \python{We implement list creation with a Python list comprehension
  13103. and multiplication is implemented with Python multiplication. We
  13104. add a case to handle a subscript on the left-hand side of
  13105. assignment. Other uses of subscript can be handled by the existing
  13106. code for tuples.}
  13107. \begin{figure}[tbp]
  13108. \begin{tcolorbox}[colback=white]
  13109. {\if\edition\racketEd
  13110. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13111. (define interp-Lvecof-class
  13112. (class interp-Lvec-class
  13113. (super-new)
  13114. (define/override (interp-op op)
  13115. (match op
  13116. ['make-vector make-vector]
  13117. ['vectorof-length vector-length]
  13118. ['vectorof-ref
  13119. (lambda (v i)
  13120. (if (< i (vector-length v))
  13121. (vector-ref v i)
  13122. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13123. ['vectorof-set!
  13124. (lambda (v i e)
  13125. (if (< i (vector-length v))
  13126. (vector-set! v i e)
  13127. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13128. [else (super interp-op op)]))
  13129. ))
  13130. (define (interp-Lvecof p)
  13131. (send (new interp-Lvecof-class) interp-program p))
  13132. \end{lstlisting}
  13133. \fi}
  13134. {\if\edition\pythonEd\pythonColor
  13135. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13136. class InterpLarray(InterpLtup):
  13137. def interp_exp(self, e, env):
  13138. match e:
  13139. case ast.List(es, Load()):
  13140. return [self.interp_exp(e, env) for e in es]
  13141. case BinOp(left, Mult(), right):
  13142. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  13143. return l * r
  13144. case Subscript(tup, index, Load()):
  13145. t = self.interp_exp(tup, env)
  13146. n = self.interp_exp(index, env)
  13147. if n < len(t):
  13148. return t[n]
  13149. else:
  13150. raise TrappedError('array index out of bounds')
  13151. case _:
  13152. return super().interp_exp(e, env)
  13153. def interp_stmt(self, s, env, cont):
  13154. match s:
  13155. case Assign([Subscript(tup, index)], value):
  13156. t = self.interp_exp(tup, env)
  13157. n = self.interp_exp(index, env)
  13158. if n < len(t):
  13159. t[n] = self.interp_exp(value, env)
  13160. else:
  13161. raise TrappedError('array index out of bounds')
  13162. return self.interp_stmts(cont, env)
  13163. case _:
  13164. return super().interp_stmt(s, env, cont)
  13165. \end{lstlisting}
  13166. \fi}
  13167. \end{tcolorbox}
  13168. \caption{Interpreter for \LangArray{}.}
  13169. \label{fig:interp-Lvecof}
  13170. \end{figure}
  13171. \subsection{Data Representation}
  13172. \label{sec:array-rep}
  13173. Just as with tuples, we store arrays on the heap, which means that the
  13174. garbage collector will need to inspect arrays. An immediate thought is
  13175. to use the same representation for arrays that we use for tuples.
  13176. However, we limit tuples to a length of fifty so that their length and
  13177. pointer mask can fit into the 64-bit tag at the beginning of each
  13178. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13179. millions of elements, so we need more bits to store the length.
  13180. However, because arrays are homogeneous, we need only 1 bit for the
  13181. pointer mask instead of 1 bit per array element. Finally, the
  13182. garbage collector must be able to distinguish between tuples
  13183. and arrays, so we need to reserve one bit for that purpose. We
  13184. arrive at the following layout for the 64-bit tag at the beginning of
  13185. an array:
  13186. \begin{itemize}
  13187. \item The right-most bit is the forwarding bit, just as in a tuple.
  13188. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13189. that it is not.
  13190. \item The next bit to the left is the pointer mask. A $0$ indicates
  13191. that none of the elements are pointers to the heap, and a $1$
  13192. indicates that all the elements are pointers.
  13193. \item The next $60$ bits store the length of the array.
  13194. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13195. and an array ($1$).
  13196. \item The left-most bit is reserved as explained in
  13197. chapter~\ref{ch:Lgrad}.
  13198. \end{itemize}
  13199. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13200. %% differentiate the kinds of values that have been injected into the
  13201. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13202. %% to indicate that the value is an array.
  13203. In the following subsections we provide hints regarding how to update
  13204. the passes to handle arrays.
  13205. \subsection{Overload Resolution}
  13206. \label{sec:array-resolution}
  13207. As noted previously, with the addition of arrays, several operators
  13208. have become \emph{overloaded}; that is, they can be applied to values
  13209. of more than one type. In this case, the element access and length
  13210. operators can be applied to both tuples and arrays. This kind of
  13211. overloading is quite common in programming languages, so many
  13212. compilers perform \emph{overload resolution}\index{subject}{overload
  13213. resolution} to handle it. The idea is to translate each overloaded
  13214. operator into different operators for the different types.
  13215. Implement a new pass named \code{resolve}.
  13216. Translate the reading of an array element
  13217. into a call to
  13218. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13219. and the writing of an array element to
  13220. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13221. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13222. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13223. When these operators are applied to tuples, leave them as is.
  13224. %
  13225. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13226. field which can be inspected to determine whether the operator
  13227. is applied to a tuple or an array.}
  13228. \subsection{Bounds Checking}
  13229. Recall that the interpreter for \LangArray{} signals a
  13230. \code{trapped-error} when there is an array access that is out of
  13231. bounds. Therefore your compiler is obliged to also catch these errors
  13232. during execution and halt, signaling an error. We recommend inserting
  13233. a new pass named \code{check\_bounds} that inserts code around each
  13234. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13235. \python{subscript} operation to ensure that the index is greater than
  13236. or equal to zero and less than the array's length. If not, the program
  13237. should halt, for which we recommend using a new primitive operation
  13238. named \code{exit}.
  13239. %% \subsection{Reveal Casts}
  13240. %% The array-access operators \code{vectorof-ref} and
  13241. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13242. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13243. %% that the type checker cannot tell whether the index will be in bounds,
  13244. %% so the bounds check must be performed at run time. Recall that the
  13245. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13246. %% an \code{If} around a vector reference for update to check whether
  13247. %% the index is less than the length. You should do the same for
  13248. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13249. %% In addition, the handling of the \code{any-vector} operators in
  13250. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13251. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13252. %% generated code should test whether the tag is for tuples (\code{010})
  13253. %% or arrays (\code{110}) and then dispatch to either
  13254. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13255. %% we add a case in \code{select\_instructions} to generate the
  13256. %% appropriate instructions for accessing the array length from the
  13257. %% header of an array.
  13258. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13259. %% the generated code needs to check that the index is less than the
  13260. %% vector length, so like the code for \code{any-vector-length}, check
  13261. %% the tag to determine whether to use \code{any-vector-length} or
  13262. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13263. %% is complete, the generated code can use \code{any-vector-ref} and
  13264. %% \code{any-vector-set!} for both tuples and arrays because the
  13265. %% instructions used for those operators do not look at the tag at the
  13266. %% front of the tuple or array.
  13267. \subsection{Expose Allocation}
  13268. This pass should translate array creation into lower-level
  13269. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13270. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13271. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13272. array. The \code{AllocateArray} AST node allocates an array of the
  13273. length specified by the $\Exp$ (of type \INTTY), but does not
  13274. initialize the elements of the array. Generate code in this pass to
  13275. initialize the elements analogous to the case for tuples.
  13276. {\if\edition\racketEd
  13277. \section{Uncover \texttt{get!}}
  13278. \label{sec:uncover-get-bang-vecof}
  13279. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13280. \code{uncover-get!-exp}.
  13281. \fi}
  13282. \subsection{Remove Complex Operands}
  13283. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13284. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13285. complex, and its subexpression must be atomic.
  13286. \subsection{Explicate Control}
  13287. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13288. \code{explicate\_assign}.
  13289. \subsection{Select Instructions}
  13290. \index{subject}{select instructions}
  13291. Generate instructions for \code{AllocateArray} similar to those for
  13292. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13293. except that the tag at the front of the array should instead use the
  13294. representation discussed in section~\ref{sec:array-rep}.
  13295. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13296. extract the length from the tag.
  13297. The instructions generated for accessing an element of an array differ
  13298. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13299. that the index is not a constant so you need to generate instructions
  13300. that compute the offset at runtime.
  13301. Compile the \code{exit} primitive into a call to the \code{exit}
  13302. function of the C standard library, with an argument of $255$.
  13303. %% Also, note that assignment to an array element may appear in
  13304. %% as a stand-alone statement, so make sure to handle that situation in
  13305. %% this pass.
  13306. %% Finally, the instructions for \code{any-vectorof-length} should be
  13307. %% similar to those for \code{vectorof-length}, except that one must
  13308. %% first project the array by writing zeroes into the $3$-bit tag
  13309. \begin{exercise}\normalfont\normalsize
  13310. Implement a compiler for the \LangArray{} language by extending your
  13311. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13312. programs, including the one shown in figure~\ref{fig:inner_product}
  13313. and also a program that multiplies two matrices. Note that although
  13314. matrices are two-dimensional arrays, they can be encoded into
  13315. one-dimensional arrays by laying out each row in the array, one after
  13316. the next.
  13317. \end{exercise}
  13318. {\if\edition\racketEd
  13319. \section{Challenge: Generational Collection}
  13320. The copying collector described in section~\ref{sec:GC} can incur
  13321. significant runtime overhead because the call to \code{collect} takes
  13322. time proportional to all the live data. One way to reduce this
  13323. overhead is to reduce how much data is inspected in each call to
  13324. \code{collect}. In particular, researchers have observed that recently
  13325. allocated data is more likely to become garbage then data that has
  13326. survived one or more previous calls to \code{collect}. This insight
  13327. motivated the creation of \emph{generational garbage collectors}
  13328. \index{subject}{generational garbage collector} that
  13329. (1) segregate data according to its age into two or more generations;
  13330. (2) allocate less space for younger generations, so collecting them is
  13331. faster, and more space for the older generations; and (3) perform
  13332. collection on the younger generations more frequently than on older
  13333. generations~\citep{Wilson:1992fk}.
  13334. For this challenge assignment, the goal is to adapt the copying
  13335. collector implemented in \code{runtime.c} to use two generations, one
  13336. for young data and one for old data. Each generation consists of a
  13337. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13338. \code{collect} function to use the two generations:
  13339. \begin{enumerate}
  13340. \item Copy the young generation's FromSpace to its ToSpace and then
  13341. switch the role of the ToSpace and FromSpace.
  13342. \item If there is enough space for the requested number of bytes in
  13343. the young FromSpace, then return from \code{collect}.
  13344. \item If there is not enough space in the young FromSpace for the
  13345. requested bytes, then move the data from the young generation to the
  13346. old one with the following steps:
  13347. \begin{enumerate}
  13348. \item[a.] If there is enough room in the old FromSpace, copy the young
  13349. FromSpace to the old FromSpace and then return.
  13350. \item[b.] If there is not enough room in the old FromSpace, then collect
  13351. the old generation by copying the old FromSpace to the old ToSpace
  13352. and swap the roles of the old FromSpace and ToSpace.
  13353. \item[c.] If there is enough room now, copy the young FromSpace to the
  13354. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13355. and ToSpace for the old generation. Copy the young FromSpace and
  13356. the old FromSpace into the larger FromSpace for the old
  13357. generation and then return.
  13358. \end{enumerate}
  13359. \end{enumerate}
  13360. We recommend that you generalize the \code{cheney} function so that it
  13361. can be used for all the copies mentioned: between the young FromSpace
  13362. and ToSpace, between the old FromSpace and ToSpace, and between the
  13363. young FromSpace and old FromSpace. This can be accomplished by adding
  13364. parameters to \code{cheney} that replace its use of the global
  13365. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13366. \code{tospace\_begin}, and \code{tospace\_end}.
  13367. Note that the collection of the young generation does not traverse the
  13368. old generation. This introduces a potential problem: there may be
  13369. young data that is reachable only through pointers in the old
  13370. generation. If these pointers are not taken into account, the
  13371. collector could throw away young data that is live! One solution,
  13372. called \emph{pointer recording}, is to maintain a set of all the
  13373. pointers from the old generation into the new generation and consider
  13374. this set as part of the root set. To maintain this set, the compiler
  13375. must insert extra instructions around every \code{vector-set!}. If the
  13376. vector being modified is in the old generation, and if the value being
  13377. written is a pointer into the new generation, then that pointer must
  13378. be added to the set. Also, if the value being overwritten was a
  13379. pointer into the new generation, then that pointer should be removed
  13380. from the set.
  13381. \begin{exercise}\normalfont\normalsize
  13382. Adapt the \code{collect} function in \code{runtime.c} to implement
  13383. generational garbage collection, as outlined in this section.
  13384. Update the code generation for \code{vector-set!} to implement
  13385. pointer recording. Make sure that your new compiler and runtime
  13386. execute without error on your test suite.
  13387. \end{exercise}
  13388. \fi}
  13389. \section{Further Reading}
  13390. \citet{Appel90} describes many data representation approaches
  13391. including the ones used in the compilation of Standard ML.
  13392. There are many alternatives to copying collectors (and their bigger
  13393. siblings, the generational collectors) with regard to garbage
  13394. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13395. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13396. collectors are that allocation is fast (just a comparison and pointer
  13397. increment), there is no fragmentation, cyclic garbage is collected,
  13398. and the time complexity of collection depends only on the amount of
  13399. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13400. main disadvantages of a two-space copying collector is that it uses a
  13401. lot of extra space and takes a long time to perform the copy, though
  13402. these problems are ameliorated in generational collectors.
  13403. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13404. small objects and generate a lot of garbage, so copying and
  13405. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13406. Garbage collection is an active research topic, especially concurrent
  13407. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13408. developing new techniques and revisiting old
  13409. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13410. meet every year at the International Symposium on Memory Management to
  13411. present these findings.
  13412. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13413. \chapter{Functions}
  13414. \label{ch:Lfun}
  13415. \index{subject}{function}
  13416. \setcounter{footnote}{0}
  13417. This chapter studies the compilation of a subset of \racket{Typed
  13418. Racket}\python{Python} in which only top-level function definitions
  13419. are allowed. This kind of function appears in the C programming
  13420. language, and it serves as an important stepping-stone to implementing
  13421. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13422. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13423. \section{The \LangFun{} Language}
  13424. The concrete syntax and abstract syntax for function definitions and
  13425. function application are shown in
  13426. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13427. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13428. with zero or more function definitions. The function names from these
  13429. definitions are in scope for the entire program, including all the
  13430. function definitions, and therefore the ordering of function
  13431. definitions does not matter.
  13432. %
  13433. \python{The abstract syntax for function parameters in
  13434. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  13435. consists of a parameter name and its type. This design differs from
  13436. Python's \code{ast} module, which has a more complex structure for
  13437. function parameters to handle keyword parameters,
  13438. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13439. complex Python abstract syntax into the simpler syntax of
  13440. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13441. \code{FunctionDef} constructor are for decorators and a type
  13442. comment, neither of which are used by our compiler. We recommend
  13443. replacing them with \code{None} in the \code{shrink} pass.
  13444. }
  13445. %
  13446. The concrete syntax for function application
  13447. \index{subject}{function application}
  13448. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13449. where the first expression
  13450. must evaluate to a function and the remaining expressions are the arguments. The
  13451. abstract syntax for function application is
  13452. $\APPLY{\Exp}{\Exp^*}$.
  13453. %% The syntax for function application does not include an explicit
  13454. %% keyword, which is error prone when using \code{match}. To alleviate
  13455. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13456. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13457. Functions are first-class in the sense that a function pointer
  13458. \index{subject}{function pointer} is data and can be stored in memory or passed
  13459. as a parameter to another function. Thus, there is a function
  13460. type, written
  13461. {\if\edition\racketEd
  13462. \begin{lstlisting}
  13463. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13464. \end{lstlisting}
  13465. \fi}
  13466. {\if\edition\pythonEd\pythonColor
  13467. \begin{lstlisting}
  13468. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13469. \end{lstlisting}
  13470. \fi}
  13471. %
  13472. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13473. through $\Type_n$ and whose return type is $\Type_R$. The main
  13474. limitation of these functions (with respect to
  13475. \racket{Racket}\python{Python} functions) is that they are not
  13476. lexically scoped. That is, the only external entities that can be
  13477. referenced from inside a function body are other globally defined
  13478. functions. The syntax of \LangFun{} prevents function definitions from
  13479. being nested inside each other.
  13480. \newcommand{\LfunGrammarRacket}{
  13481. \begin{array}{lcl}
  13482. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13483. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13484. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13485. \end{array}
  13486. }
  13487. \newcommand{\LfunASTRacket}{
  13488. \begin{array}{lcl}
  13489. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13490. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13491. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13492. \end{array}
  13493. }
  13494. \newcommand{\LfunGrammarPython}{
  13495. \begin{array}{lcl}
  13496. \Type &::=& \key{int}
  13497. \MID \key{bool} \MID \key{void}
  13498. \MID \key{tuple}\LS \Type^+ \RS
  13499. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13500. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13501. \Stmt &::=& \CRETURN{\Exp} \\
  13502. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13503. \end{array}
  13504. }
  13505. \newcommand{\LfunASTPython}{
  13506. \begin{array}{lcl}
  13507. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13508. \MID \key{TupleType}\LS\Type^+\RS\\
  13509. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13510. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13511. \Stmt &::=& \RETURN{\Exp} \\
  13512. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13513. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13514. \end{array}
  13515. }
  13516. \begin{figure}[tp]
  13517. \centering
  13518. \begin{tcolorbox}[colback=white]
  13519. \small
  13520. {\if\edition\racketEd
  13521. \[
  13522. \begin{array}{l}
  13523. \gray{\LintGrammarRacket{}} \\ \hline
  13524. \gray{\LvarGrammarRacket{}} \\ \hline
  13525. \gray{\LifGrammarRacket{}} \\ \hline
  13526. \gray{\LwhileGrammarRacket} \\ \hline
  13527. \gray{\LtupGrammarRacket} \\ \hline
  13528. \LfunGrammarRacket \\
  13529. \begin{array}{lcl}
  13530. \LangFunM{} &::=& \Def \ldots \; \Exp
  13531. \end{array}
  13532. \end{array}
  13533. \]
  13534. \fi}
  13535. {\if\edition\pythonEd\pythonColor
  13536. \[
  13537. \begin{array}{l}
  13538. \gray{\LintGrammarPython{}} \\ \hline
  13539. \gray{\LvarGrammarPython{}} \\ \hline
  13540. \gray{\LifGrammarPython{}} \\ \hline
  13541. \gray{\LwhileGrammarPython} \\ \hline
  13542. \gray{\LtupGrammarPython} \\ \hline
  13543. \LfunGrammarPython \\
  13544. \begin{array}{rcl}
  13545. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13546. \end{array}
  13547. \end{array}
  13548. \]
  13549. \fi}
  13550. \end{tcolorbox}
  13551. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13552. \label{fig:Lfun-concrete-syntax}
  13553. \end{figure}
  13554. \begin{figure}[tp]
  13555. \centering
  13556. \begin{tcolorbox}[colback=white]
  13557. \small
  13558. {\if\edition\racketEd
  13559. \[
  13560. \begin{array}{l}
  13561. \gray{\LintOpAST} \\ \hline
  13562. \gray{\LvarASTRacket{}} \\ \hline
  13563. \gray{\LifASTRacket{}} \\ \hline
  13564. \gray{\LwhileASTRacket{}} \\ \hline
  13565. \gray{\LtupASTRacket{}} \\ \hline
  13566. \LfunASTRacket \\
  13567. \begin{array}{lcl}
  13568. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13569. \end{array}
  13570. \end{array}
  13571. \]
  13572. \fi}
  13573. {\if\edition\pythonEd\pythonColor
  13574. \[
  13575. \begin{array}{l}
  13576. \gray{\LintASTPython{}} \\ \hline
  13577. \gray{\LvarASTPython{}} \\ \hline
  13578. \gray{\LifASTPython{}} \\ \hline
  13579. \gray{\LwhileASTPython} \\ \hline
  13580. \gray{\LtupASTPython} \\ \hline
  13581. \LfunASTPython \\
  13582. \begin{array}{rcl}
  13583. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13584. \end{array}
  13585. \end{array}
  13586. \]
  13587. \fi}
  13588. \end{tcolorbox}
  13589. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13590. \label{fig:Lfun-syntax}
  13591. \end{figure}
  13592. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13593. representative example of defining and using functions in \LangFun{}.
  13594. We define a function \code{map} that applies some other function
  13595. \code{f} to both elements of a tuple and returns a new tuple
  13596. containing the results. We also define a function \code{inc}. The
  13597. program applies \code{map} to \code{inc} and
  13598. %
  13599. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13600. %
  13601. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13602. %
  13603. from which we return \code{42}.
  13604. \begin{figure}[tbp]
  13605. \begin{tcolorbox}[colback=white]
  13606. {\if\edition\racketEd
  13607. \begin{lstlisting}
  13608. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13609. : (Vector Integer Integer)
  13610. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13611. (define (inc [x : Integer]) : Integer
  13612. (+ x 1))
  13613. (vector-ref (map inc (vector 0 41)) 1)
  13614. \end{lstlisting}
  13615. \fi}
  13616. {\if\edition\pythonEd\pythonColor
  13617. \begin{lstlisting}
  13618. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13619. return f(v[0]), f(v[1])
  13620. def inc(x : int) -> int:
  13621. return x + 1
  13622. print( map(inc, (0, 41))[1] )
  13623. \end{lstlisting}
  13624. \fi}
  13625. \end{tcolorbox}
  13626. \caption{Example of using functions in \LangFun{}.}
  13627. \label{fig:Lfun-function-example}
  13628. \end{figure}
  13629. The definitional interpreter for \LangFun{} is shown in
  13630. figure~\ref{fig:interp-Lfun}. The case for the
  13631. %
  13632. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13633. %
  13634. AST is responsible for setting up the mutual recursion between the
  13635. top-level function definitions.
  13636. %
  13637. \racket{We use the classic back-patching
  13638. \index{subject}{back-patching} approach that uses mutable variables
  13639. and makes two passes over the function
  13640. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13641. top-level environment using a mutable cons cell for each function
  13642. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13643. for each function is incomplete; it does not yet include the environment.
  13644. Once the top-level environment has been constructed, we iterate over it and
  13645. update the \code{lambda} values to use the top-level environment.}
  13646. %
  13647. \python{We create a dictionary named \code{env} and fill it in
  13648. by mapping each function name to a new \code{Function} value,
  13649. each of which stores a reference to the \code{env}.
  13650. (We define the class \code{Function} for this purpose.)}
  13651. %
  13652. To interpret a function \racket{application}\python{call}, we match
  13653. the result of the function expression to obtain a function value. We
  13654. then extend the function's environment with the mapping of parameters to
  13655. argument values. Finally, we interpret the body of the function in
  13656. this extended environment.
  13657. \begin{figure}[tp]
  13658. \begin{tcolorbox}[colback=white]
  13659. {\if\edition\racketEd
  13660. \begin{lstlisting}
  13661. (define interp-Lfun-class
  13662. (class interp-Lvec-class
  13663. (super-new)
  13664. (define/override ((interp-exp env) e)
  13665. (define recur (interp-exp env))
  13666. (match e
  13667. [(Apply fun args)
  13668. (define fun-val (recur fun))
  13669. (define arg-vals (for/list ([e args]) (recur e)))
  13670. (match fun-val
  13671. [`(function (,xs ...) ,body ,fun-env)
  13672. (define params-args (for/list ([x xs] [arg arg-vals])
  13673. (cons x (box arg))))
  13674. (define new-env (append params-args fun-env))
  13675. ((interp-exp new-env) body)]
  13676. [else
  13677. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13678. [else ((super interp-exp env) e)]
  13679. ))
  13680. (define/public (interp-def d)
  13681. (match d
  13682. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13683. (cons f (box `(function ,xs ,body ())))]))
  13684. (define/override (interp-program p)
  13685. (match p
  13686. [(ProgramDefsExp info ds body)
  13687. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13688. (for/list ([f (in-dict-values top-level)])
  13689. (set-box! f (match (unbox f)
  13690. [`(function ,xs ,body ())
  13691. `(function ,xs ,body ,top-level)])))
  13692. ((interp-exp top-level) body))]))
  13693. ))
  13694. (define (interp-Lfun p)
  13695. (send (new interp-Lfun-class) interp-program p))
  13696. \end{lstlisting}
  13697. \fi}
  13698. {\if\edition\pythonEd\pythonColor
  13699. \begin{lstlisting}
  13700. class InterpLfun(InterpLtup):
  13701. def apply_fun(self, fun, args, e):
  13702. match fun:
  13703. case Function(name, xs, body, env):
  13704. new_env = env.copy().update(zip(xs, args))
  13705. return self.interp_stmts(body, new_env)
  13706. case _:
  13707. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13708. def interp_exp(self, e, env):
  13709. match e:
  13710. case Call(Name('input_int'), []):
  13711. return super().interp_exp(e, env)
  13712. case Call(func, args):
  13713. f = self.interp_exp(func, env)
  13714. vs = [self.interp_exp(arg, env) for arg in args]
  13715. return self.apply_fun(f, vs, e)
  13716. case _:
  13717. return super().interp_exp(e, env)
  13718. def interp_stmt(self, s, env, cont):
  13719. match s:
  13720. case Return(value):
  13721. return self.interp_exp(value, env)
  13722. case FunctionDef(name, params, bod, dl, returns, comment):
  13723. if isinstance(params, ast.arguments):
  13724. ps = [p.arg for p in params.args]
  13725. else:
  13726. ps = [x for (x,t) in params]
  13727. env[name] = Function(name, ps, bod, env)
  13728. return self.interp_stmts(cont, env)
  13729. case _:
  13730. return super().interp_stmt(s, env, cont)
  13731. def interp(self, p):
  13732. match p:
  13733. case Module(ss):
  13734. env = {}
  13735. self.interp_stmts(ss, env)
  13736. if 'main' in env.keys():
  13737. self.apply_fun(env['main'], [], None)
  13738. case _:
  13739. raise Exception('interp: unexpected ' + repr(p))
  13740. \end{lstlisting}
  13741. \fi}
  13742. \end{tcolorbox}
  13743. \caption{Interpreter for the \LangFun{} language.}
  13744. \label{fig:interp-Lfun}
  13745. \end{figure}
  13746. %\margincomment{TODO: explain type checker}
  13747. The type checker for \LangFun{} is shown in
  13748. figure~\ref{fig:type-check-Lfun}.
  13749. %
  13750. \python{(We omit the code that parses function parameters into the
  13751. simpler abstract syntax.)}
  13752. %
  13753. Similarly to the interpreter, the case for the
  13754. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13755. %
  13756. AST is responsible for setting up the mutual recursion between the
  13757. top-level function definitions. We begin by create a mapping
  13758. \code{env} from every function name to its type. We then type check
  13759. the program using this mapping.
  13760. %
  13761. In the case for function \racket{application}\python{call}, we match
  13762. the type of the function expression to a function type and check that
  13763. the types of the argument expressions are equal to the function's
  13764. parameter types. The type of the \racket{application}\python{call} as
  13765. a whole is the return type from the function type.
  13766. \begin{figure}[tp]
  13767. \begin{tcolorbox}[colback=white]
  13768. {\if\edition\racketEd
  13769. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13770. (define type-check-Lfun-class
  13771. (class type-check-Lvec-class
  13772. (super-new)
  13773. (inherit check-type-equal?)
  13774. (define/public (type-check-apply env e es)
  13775. (define-values (e^ ty) ((type-check-exp env) e))
  13776. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  13777. ((type-check-exp env) e)))
  13778. (match ty
  13779. [`(,ty^* ... -> ,rt)
  13780. (for ([arg-ty ty*] [param-ty ty^*])
  13781. (check-type-equal? arg-ty param-ty (Apply e es)))
  13782. (values e^ e* rt)]))
  13783. (define/override (type-check-exp env)
  13784. (lambda (e)
  13785. (match e
  13786. [(FunRef f n)
  13787. (values (FunRef f n) (dict-ref env f))]
  13788. [(Apply e es)
  13789. (define-values (e^ es^ rt) (type-check-apply env e es))
  13790. (values (Apply e^ es^) rt)]
  13791. [(Call e es)
  13792. (define-values (e^ es^ rt) (type-check-apply env e es))
  13793. (values (Call e^ es^) rt)]
  13794. [else ((super type-check-exp env) e)])))
  13795. (define/public (type-check-def env)
  13796. (lambda (e)
  13797. (match e
  13798. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  13799. (define new-env (append (map cons xs ps) env))
  13800. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13801. (check-type-equal? ty^ rt body)
  13802. (Def f p:t* rt info body^)])))
  13803. (define/public (fun-def-type d)
  13804. (match d
  13805. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  13806. (define/override (type-check-program e)
  13807. (match e
  13808. [(ProgramDefsExp info ds body)
  13809. (define env (for/list ([d ds])
  13810. (cons (Def-name d) (fun-def-type d))))
  13811. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  13812. (define-values (body^ ty) ((type-check-exp env) body))
  13813. (check-type-equal? ty 'Integer body)
  13814. (ProgramDefsExp info ds^ body^)]))))
  13815. (define (type-check-Lfun p)
  13816. (send (new type-check-Lfun-class) type-check-program p))
  13817. \end{lstlisting}
  13818. \fi}
  13819. {\if\edition\pythonEd\pythonColor
  13820. \begin{lstlisting}
  13821. class TypeCheckLfun(TypeCheckLtup):
  13822. def type_check_exp(self, e, env):
  13823. match e:
  13824. case Call(Name('input_int'), []):
  13825. return super().type_check_exp(e, env)
  13826. case Call(func, args):
  13827. func_t = self.type_check_exp(func, env)
  13828. args_t = [self.type_check_exp(arg, env) for arg in args]
  13829. match func_t:
  13830. case FunctionType(params_t, return_t):
  13831. for (arg_t, param_t) in zip(args_t, params_t):
  13832. check_type_equal(param_t, arg_t, e)
  13833. return return_t
  13834. case _:
  13835. raise Exception('type_check_exp: in call, unexpected ' +
  13836. repr(func_t))
  13837. case _:
  13838. return super().type_check_exp(e, env)
  13839. def type_check_stmts(self, ss, env):
  13840. if len(ss) == 0:
  13841. return
  13842. match ss[0]:
  13843. case FunctionDef(name, params, body, dl, returns, comment):
  13844. new_env = env.copy().update(params)
  13845. rt = self.type_check_stmts(body, new_env)
  13846. check_type_equal(returns, rt, ss[0])
  13847. return self.type_check_stmts(ss[1:], env)
  13848. case Return(value):
  13849. return self.type_check_exp(value, env)
  13850. case _:
  13851. return super().type_check_stmts(ss, env)
  13852. def type_check(self, p):
  13853. match p:
  13854. case Module(body):
  13855. env = {}
  13856. for s in body:
  13857. match s:
  13858. case FunctionDef(name, params, bod, dl, returns, comment):
  13859. if name in env:
  13860. raise Exception('type_check: function ' +
  13861. repr(name) + ' defined twice')
  13862. params_t = [t for (x,t) in params]
  13863. env[name] = FunctionType(params_t, returns)
  13864. self.type_check_stmts(body, env)
  13865. case _:
  13866. raise Exception('type_check: unexpected ' + repr(p))
  13867. \end{lstlisting}
  13868. \fi}
  13869. \end{tcolorbox}
  13870. \caption{Type checker for the \LangFun{} language.}
  13871. \label{fig:type-check-Lfun}
  13872. \end{figure}
  13873. \clearpage
  13874. \section{Functions in x86}
  13875. \label{sec:fun-x86}
  13876. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  13877. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  13878. %% \margincomment{\tiny Talk about the return address on the
  13879. %% stack and what callq and retq does.\\ --Jeremy }
  13880. The x86 architecture provides a few features to support the
  13881. implementation of functions. We have already seen that there are
  13882. labels in x86 so that one can refer to the location of an instruction,
  13883. as is needed for jump instructions. Labels can also be used to mark
  13884. the beginning of the instructions for a function. Going further, we
  13885. can obtain the address of a label by using the \key{leaq}
  13886. instruction. For example, the following puts the address of the
  13887. \code{inc} label into the \code{rbx} register:
  13888. \begin{lstlisting}
  13889. leaq inc(%rip), %rbx
  13890. \end{lstlisting}
  13891. Recall from section~\ref{sec:select-instructions-gc} that
  13892. \verb!inc(%rip)! is an example of instruction-pointer-relative
  13893. addressing.
  13894. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  13895. to functions whose locations were given by a label, such as
  13896. \code{read\_int}. To support function calls in this chapter we instead
  13897. jump to functions whose location are given by an address in
  13898. a register; that is, we use \emph{indirect function calls}. The
  13899. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  13900. before the register name.\index{subject}{indirect function call}
  13901. \begin{lstlisting}
  13902. callq *%rbx
  13903. \end{lstlisting}
  13904. \subsection{Calling Conventions}
  13905. \label{sec:calling-conventions-fun}
  13906. \index{subject}{calling conventions}
  13907. The \code{callq} instruction provides partial support for implementing
  13908. functions: it pushes the return address on the stack and it jumps to
  13909. the target. However, \code{callq} does not handle
  13910. \begin{enumerate}
  13911. \item parameter passing,
  13912. \item pushing frames on the procedure call stack and popping them off,
  13913. or
  13914. \item determining how registers are shared by different functions.
  13915. \end{enumerate}
  13916. Regarding parameter passing, recall that the x86-64 calling
  13917. convention for Unix-based systems uses the following six registers to
  13918. pass arguments to a function, in the given order:
  13919. \begin{lstlisting}
  13920. rdi rsi rdx rcx r8 r9
  13921. \end{lstlisting}
  13922. If there are more than six arguments, then the calling convention
  13923. mandates using space on the frame of the caller for the rest of the
  13924. arguments. However, to ease the implementation of efficient tail calls
  13925. (section~\ref{sec:tail-call}), we arrange never to need more than six
  13926. arguments.
  13927. %
  13928. The return value of the function is stored in register \code{rax}.
  13929. Regarding frames \index{subject}{frame} and the procedure call stack,
  13930. \index{subject}{procedure call stack} recall from
  13931. section~\ref{sec:x86} that the stack grows down and each function call
  13932. uses a chunk of space on the stack called a frame. The caller sets the
  13933. stack pointer, register \code{rsp}, to the last data item in its
  13934. frame. The callee must not change anything in the caller's frame, that
  13935. is, anything that is at or above the stack pointer. The callee is free
  13936. to use locations that are below the stack pointer.
  13937. Recall that we store variables of tuple type on the root stack. So,
  13938. the prelude\index{subject}{prelude} of a function needs to move the
  13939. root stack pointer \code{r15} up according to the number of variables
  13940. of tuple type and the conclusion\index{subject}{conclusion} needs to
  13941. move the root stack pointer back down. Also, the prelude must
  13942. initialize to \code{0} this frame's slots in the root stack to signal
  13943. to the garbage collector that those slots do not yet contain a valid
  13944. pointer. Otherwise the garbage collector will interpret the garbage
  13945. bits in those slots as memory addresses and try to traverse them,
  13946. causing serious mayhem!
  13947. Regarding the sharing of registers between different functions, recall
  13948. from section~\ref{sec:calling-conventions} that the registers are
  13949. divided into two groups, the caller-saved registers and the
  13950. callee-saved registers. The caller should assume that all the
  13951. caller-saved registers are overwritten with arbitrary values by the
  13952. callee. For that reason we recommend in
  13953. section~\ref{sec:calling-conventions} that variables that are live
  13954. during a function call should not be assigned to caller-saved
  13955. registers.
  13956. On the flip side, if the callee wants to use a callee-saved register,
  13957. the callee must save the contents of those registers on their stack
  13958. frame and then put them back prior to returning to the caller. For
  13959. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13960. the register allocator assigns a variable to a callee-saved register,
  13961. then the prelude of the \code{main} function must save that register
  13962. to the stack and the conclusion of \code{main} must restore it. This
  13963. recommendation now generalizes to all functions.
  13964. Recall that the base pointer, register \code{rbp}, is used as a
  13965. point of reference within a frame, so that each local variable can be
  13966. accessed at a fixed offset from the base pointer
  13967. (section~\ref{sec:x86}).
  13968. %
  13969. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13970. and callee frames.
  13971. \begin{figure}[tbp]
  13972. \centering
  13973. \begin{tcolorbox}[colback=white]
  13974. \begin{tabular}{r|r|l|l} \hline
  13975. Caller View & Callee View & Contents & Frame \\ \hline
  13976. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13977. 0(\key{\%rbp}) & & old \key{rbp} \\
  13978. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13979. \ldots & & \ldots \\
  13980. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13981. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13982. \ldots & & \ldots \\
  13983. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13984. %% & & \\
  13985. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13986. %% & \ldots & \ldots \\
  13987. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13988. \hline
  13989. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13990. & 0(\key{\%rbp}) & old \key{rbp} \\
  13991. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13992. & \ldots & \ldots \\
  13993. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13994. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13995. & \ldots & \ldots \\
  13996. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13997. \end{tabular}
  13998. \end{tcolorbox}
  13999. \caption{Memory layout of caller and callee frames.}
  14000. \label{fig:call-frames}
  14001. \end{figure}
  14002. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14003. %% local variables and for storing the values of callee-saved registers
  14004. %% (we shall refer to all of these collectively as ``locals''), and that
  14005. %% at the beginning of a function we move the stack pointer \code{rsp}
  14006. %% down to make room for them.
  14007. %% We recommend storing the local variables
  14008. %% first and then the callee-saved registers, so that the local variables
  14009. %% can be accessed using \code{rbp} the same as before the addition of
  14010. %% functions.
  14011. %% To make additional room for passing arguments, we shall
  14012. %% move the stack pointer even further down. We count how many stack
  14013. %% arguments are needed for each function call that occurs inside the
  14014. %% body of the function and find their maximum. Adding this number to the
  14015. %% number of locals gives us how much the \code{rsp} should be moved at
  14016. %% the beginning of the function. In preparation for a function call, we
  14017. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14018. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14019. %% so on.
  14020. %% Upon calling the function, the stack arguments are retrieved by the
  14021. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14022. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14023. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14024. %% the layout of the caller and callee frames. Notice how important it is
  14025. %% that we correctly compute the maximum number of arguments needed for
  14026. %% function calls; if that number is too small then the arguments and
  14027. %% local variables will smash into each other!
  14028. \subsection{Efficient Tail Calls}
  14029. \label{sec:tail-call}
  14030. In general, the amount of stack space used by a program is determined
  14031. by the longest chain of nested function calls. That is, if function
  14032. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14033. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14034. large if functions are recursive. However, in some cases we can
  14035. arrange to use only a constant amount of space for a long chain of
  14036. nested function calls.
  14037. A \emph{tail call}\index{subject}{tail call} is a function call that
  14038. happens as the last action in a function body. For example, in the
  14039. following program, the recursive call to \code{tail\_sum} is a tail
  14040. call:
  14041. \begin{center}
  14042. {\if\edition\racketEd
  14043. \begin{lstlisting}
  14044. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14045. (if (eq? n 0)
  14046. r
  14047. (tail_sum (- n 1) (+ n r))))
  14048. (+ (tail_sum 3 0) 36)
  14049. \end{lstlisting}
  14050. \fi}
  14051. {\if\edition\pythonEd\pythonColor
  14052. \begin{lstlisting}
  14053. def tail_sum(n : int, r : int) -> int:
  14054. if n == 0:
  14055. return r
  14056. else:
  14057. return tail_sum(n - 1, n + r)
  14058. print( tail_sum(3, 0) + 36)
  14059. \end{lstlisting}
  14060. \fi}
  14061. \end{center}
  14062. At a tail call, the frame of the caller is no longer needed, so we can
  14063. pop the caller's frame before making the tail call. With this
  14064. approach, a recursive function that makes only tail calls ends up
  14065. using a constant amount of stack space. Functional languages like
  14066. Racket rely heavily on recursive functions, so the definition of
  14067. Racket \emph{requires} that all tail calls be optimized in this way.
  14068. \index{subject}{frame}
  14069. Some care is needed with regard to argument passing in tail calls. As
  14070. mentioned, for arguments beyond the sixth, the convention is to use
  14071. space in the caller's frame for passing arguments. However, for a
  14072. tail call we pop the caller's frame and can no longer use it. An
  14073. alternative is to use space in the callee's frame for passing
  14074. arguments. However, this option is also problematic because the caller
  14075. and callee's frames overlap in memory. As we begin to copy the
  14076. arguments from their sources in the caller's frame, the target
  14077. locations in the callee's frame might collide with the sources for
  14078. later arguments! We solve this problem by using the heap instead of
  14079. the stack for passing more than six arguments
  14080. (section~\ref{sec:limit-functions-r4}).
  14081. As mentioned, for a tail call we pop the caller's frame prior to
  14082. making the tail call. The instructions for popping a frame are the
  14083. instructions that we usually place in the conclusion of a
  14084. function. Thus, we also need to place such code immediately before
  14085. each tail call. These instructions include restoring the callee-saved
  14086. registers, so it is fortunate that the argument passing registers are
  14087. all caller-saved registers.
  14088. One note remains regarding which instruction to use to make the tail
  14089. call. When the callee is finished, it should not return to the current
  14090. function but instead return to the function that called the current
  14091. one. Thus, the return address that is already on the stack is the
  14092. right one, and we should not use \key{callq} to make the tail call
  14093. because that would overwrite the return address. Instead we simply use
  14094. the \key{jmp} instruction. As with the indirect function call, we write
  14095. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14096. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14097. jump target because the conclusion can overwrite just about everything
  14098. else.
  14099. \begin{lstlisting}
  14100. jmp *%rax
  14101. \end{lstlisting}
  14102. \section{Shrink \LangFun{}}
  14103. \label{sec:shrink-r4}
  14104. The \code{shrink} pass performs a minor modification to ease the
  14105. later passes. This pass introduces an explicit \code{main} function
  14106. that gobbles up all the top-level statements of the module.
  14107. %
  14108. \racket{It also changes the top \code{ProgramDefsExp} form to
  14109. \code{ProgramDefs}.}
  14110. {\if\edition\racketEd
  14111. \begin{lstlisting}
  14112. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14113. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14114. \end{lstlisting}
  14115. where $\itm{mainDef}$ is
  14116. \begin{lstlisting}
  14117. (Def 'main '() 'Integer '() |$\Exp'$|)
  14118. \end{lstlisting}
  14119. \fi}
  14120. {\if\edition\pythonEd\pythonColor
  14121. \begin{lstlisting}
  14122. Module(|$\Def\ldots\Stmt\ldots$|)
  14123. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14124. \end{lstlisting}
  14125. where $\itm{mainDef}$ is
  14126. \begin{lstlisting}
  14127. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14128. \end{lstlisting}
  14129. \fi}
  14130. \section{Reveal Functions and the \LangFunRef{} Language}
  14131. \label{sec:reveal-functions-r4}
  14132. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14133. in that it conflates the use of function names and local
  14134. variables. This is a problem because we need to compile the use of a
  14135. function name differently from the use of a local variable. In
  14136. particular, we use \code{leaq} to convert the function name (a label
  14137. in x86) to an address in a register. Thus, we create a new pass that
  14138. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14139. $n$ is the arity of the function.\python{\footnote{The arity is not
  14140. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14141. This pass is named \code{reveal\_functions} and the output language
  14142. is \LangFunRef{}.
  14143. %is defined in figure~\ref{fig:f1-syntax}.
  14144. %% The concrete syntax for a
  14145. %% function reference is $\CFUNREF{f}$.
  14146. %% \begin{figure}[tp]
  14147. %% \centering
  14148. %% \fbox{
  14149. %% \begin{minipage}{0.96\textwidth}
  14150. %% {\if\edition\racketEd
  14151. %% \[
  14152. %% \begin{array}{lcl}
  14153. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14154. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14155. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14156. %% \end{array}
  14157. %% \]
  14158. %% \fi}
  14159. %% {\if\edition\pythonEd\pythonColor
  14160. %% \[
  14161. %% \begin{array}{lcl}
  14162. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14163. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14164. %% \end{array}
  14165. %% \]
  14166. %% \fi}
  14167. %% \end{minipage}
  14168. %% }
  14169. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14170. %% (figure~\ref{fig:Lfun-syntax}).}
  14171. %% \label{fig:f1-syntax}
  14172. %% \end{figure}
  14173. %% Distinguishing between calls in tail position and non-tail position
  14174. %% requires the pass to have some notion of context. We recommend using
  14175. %% two mutually recursive functions, one for processing expressions in
  14176. %% tail position and another for the rest.
  14177. \racket{Placing this pass after \code{uniquify} will make sure that
  14178. there are no local variables and functions that share the same
  14179. name.}
  14180. %
  14181. The \code{reveal\_functions} pass should come before the
  14182. \code{remove\_complex\_operands} pass because function references
  14183. should be categorized as complex expressions.
  14184. \section{Limit Functions}
  14185. \label{sec:limit-functions-r4}
  14186. Recall that we wish to limit the number of function parameters to six
  14187. so that we do not need to use the stack for argument passing, which
  14188. makes it easier to implement efficient tail calls. However, because
  14189. the input language \LangFun{} supports arbitrary numbers of function
  14190. arguments, we have some work to do! The \code{limit\_functions} pass
  14191. transforms functions and function calls that involve more than six
  14192. arguments to pass the first five arguments as usual, but it packs the
  14193. rest of the arguments into a tuple and passes it as the sixth
  14194. argument.\footnote{The implementation this pass can be postponed to
  14195. last because you can test the rest of the passes on functions with
  14196. six or fewer parameters.}
  14197. Each function definition with seven or more parameters is transformed as
  14198. follows:
  14199. {\if\edition\racketEd
  14200. \begin{lstlisting}
  14201. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14202. |$\Rightarrow$|
  14203. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14204. \end{lstlisting}
  14205. \fi}
  14206. {\if\edition\pythonEd\pythonColor
  14207. \begin{lstlisting}
  14208. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14209. |$\Rightarrow$|
  14210. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14211. |$T_r$|, None, |$\itm{body}'$|, None)
  14212. \end{lstlisting}
  14213. \fi}
  14214. %
  14215. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14216. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14217. the $k$th element of the tuple, where $k = i - 6$.
  14218. %
  14219. {\if\edition\racketEd
  14220. \begin{lstlisting}
  14221. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14222. \end{lstlisting}
  14223. \fi}
  14224. {\if\edition\pythonEd\pythonColor
  14225. \begin{lstlisting}
  14226. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14227. \end{lstlisting}
  14228. \fi}
  14229. For function calls with too many arguments, the \code{limit\_functions}
  14230. pass transforms them in the following way:
  14231. \begin{tabular}{lll}
  14232. \begin{minipage}{0.3\textwidth}
  14233. {\if\edition\racketEd
  14234. \begin{lstlisting}
  14235. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14236. \end{lstlisting}
  14237. \fi}
  14238. {\if\edition\pythonEd\pythonColor
  14239. \begin{lstlisting}
  14240. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14241. \end{lstlisting}
  14242. \fi}
  14243. \end{minipage}
  14244. &
  14245. $\Rightarrow$
  14246. &
  14247. \begin{minipage}{0.5\textwidth}
  14248. {\if\edition\racketEd
  14249. \begin{lstlisting}
  14250. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14251. \end{lstlisting}
  14252. \fi}
  14253. {\if\edition\pythonEd\pythonColor
  14254. \begin{lstlisting}
  14255. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14256. \end{lstlisting}
  14257. \fi}
  14258. \end{minipage}
  14259. \end{tabular}
  14260. \section{Remove Complex Operands}
  14261. \label{sec:rco-r4}
  14262. The primary decisions to make for this pass are whether to classify
  14263. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14264. atomic or complex expressions. Recall that an atomic expression
  14265. ends up as an immediate argument of an x86 instruction. Function
  14266. application translates to a sequence of instructions, so
  14267. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14268. a complex expression. On the other hand, the arguments of
  14269. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14270. expressions.
  14271. %
  14272. Regarding \code{FunRef}, as discussed previously, the function label
  14273. needs to be converted to an address using the \code{leaq}
  14274. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14275. needs to be classified as a complex expression so that we generate an
  14276. assignment statement with a left-hand side that can serve as the
  14277. target of the \code{leaq}.
  14278. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14279. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14280. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14281. and augments programs to include a list of function definitions.
  14282. %
  14283. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14284. \newcommand{\LfunMonadASTRacket}{
  14285. \begin{array}{lcl}
  14286. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14287. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14288. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14289. \end{array}
  14290. }
  14291. \newcommand{\LfunMonadASTPython}{
  14292. \begin{array}{lcl}
  14293. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  14294. \MID \key{TupleType}\LS\Type^+\RS\\
  14295. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14296. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14297. \Stmt &::=& \RETURN{\Exp} \\
  14298. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14299. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14300. \end{array}
  14301. }
  14302. \begin{figure}[tp]
  14303. \centering
  14304. \begin{tcolorbox}[colback=white]
  14305. \small
  14306. {\if\edition\racketEd
  14307. \[
  14308. \begin{array}{l}
  14309. \gray{\LvarMonadASTRacket} \\ \hline
  14310. \gray{\LifMonadASTRacket} \\ \hline
  14311. \gray{\LwhileMonadASTRacket} \\ \hline
  14312. \gray{\LtupMonadASTRacket} \\ \hline
  14313. \LfunMonadASTRacket \\
  14314. \begin{array}{rcl}
  14315. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14316. \end{array}
  14317. \end{array}
  14318. \]
  14319. \fi}
  14320. {\if\edition\pythonEd\pythonColor
  14321. \[
  14322. \begin{array}{l}
  14323. \gray{\LvarMonadASTPython} \\ \hline
  14324. \gray{\LifMonadASTPython} \\ \hline
  14325. \gray{\LwhileMonadASTPython} \\ \hline
  14326. \gray{\LtupMonadASTPython} \\ \hline
  14327. \LfunMonadASTPython \\
  14328. \begin{array}{rcl}
  14329. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14330. \end{array}
  14331. \end{array}
  14332. \]
  14333. \fi}
  14334. \end{tcolorbox}
  14335. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14336. \label{fig:Lfun-anf-syntax}
  14337. \end{figure}
  14338. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14339. %% \LangFunANF{} of this pass.
  14340. %% \begin{figure}[tp]
  14341. %% \centering
  14342. %% \fbox{
  14343. %% \begin{minipage}{0.96\textwidth}
  14344. %% \small
  14345. %% \[
  14346. %% \begin{array}{rcl}
  14347. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14348. %% \MID \VOID{} } \\
  14349. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14350. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14351. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14352. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14353. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14354. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14355. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14356. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14357. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14358. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14359. %% \end{array}
  14360. %% \]
  14361. %% \end{minipage}
  14362. %% }
  14363. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14364. %% \label{fig:Lfun-anf-syntax}
  14365. %% \end{figure}
  14366. \section{Explicate Control and the \LangCFun{} Language}
  14367. \label{sec:explicate-control-r4}
  14368. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14369. output of \code{explicate\_control}.
  14370. %
  14371. %% \racket{(The concrete syntax is given in
  14372. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14373. %
  14374. The auxiliary functions for assignment\racket{ and tail contexts} should
  14375. be updated with cases for
  14376. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14377. function for predicate context should be updated for
  14378. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14379. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14380. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14381. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14382. auxiliary function for processing function definitions. This code is
  14383. similar to the case for \code{Program} in \LangVec{}. The top-level
  14384. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14385. form of \LangFun{} can then apply this new function to all the
  14386. function definitions.
  14387. {\if\edition\pythonEd\pythonColor
  14388. The translation of \code{Return} statements requires a new auxiliary
  14389. function to handle expressions in tail context, called
  14390. \code{explicate\_tail}. The function should take an expression and the
  14391. dictionary of basic blocks and produce a list of statements in the
  14392. \LangCFun{} language. The \code{explicate\_tail} function should
  14393. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  14394. and a default case for other kinds of expressions. The default case
  14395. should produce a \code{Return} statement. The case for \code{Call}
  14396. should change it into \code{TailCall}. The other cases should
  14397. recursively process their subexpressions and statements, choosing the
  14398. appropriate explicate functions for the various contexts.
  14399. \fi}
  14400. \newcommand{\CfunASTRacket}{
  14401. \begin{array}{lcl}
  14402. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14403. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14404. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14405. \end{array}
  14406. }
  14407. \newcommand{\CfunASTPython}{
  14408. \begin{array}{lcl}
  14409. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14410. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14411. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14412. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  14413. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14414. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14415. \end{array}
  14416. }
  14417. \begin{figure}[tp]
  14418. \begin{tcolorbox}[colback=white]
  14419. \small
  14420. {\if\edition\racketEd
  14421. \[
  14422. \begin{array}{l}
  14423. \gray{\CvarASTRacket} \\ \hline
  14424. \gray{\CifASTRacket} \\ \hline
  14425. \gray{\CloopASTRacket} \\ \hline
  14426. \gray{\CtupASTRacket} \\ \hline
  14427. \CfunASTRacket \\
  14428. \begin{array}{lcl}
  14429. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14430. \end{array}
  14431. \end{array}
  14432. \]
  14433. \fi}
  14434. {\if\edition\pythonEd\pythonColor
  14435. \[
  14436. \begin{array}{l}
  14437. \gray{\CifASTPython} \\ \hline
  14438. \gray{\CtupASTPython} \\ \hline
  14439. \CfunASTPython \\
  14440. \begin{array}{lcl}
  14441. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14442. \end{array}
  14443. \end{array}
  14444. \]
  14445. \fi}
  14446. \end{tcolorbox}
  14447. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14448. \label{fig:c3-syntax}
  14449. \end{figure}
  14450. \clearpage
  14451. \section{Select Instructions and the \LangXIndCall{} Language}
  14452. \label{sec:select-r4}
  14453. \index{subject}{select instructions}
  14454. The output of select instructions is a program in the \LangXIndCall{}
  14455. language; the definition of its concrete syntax is shown in
  14456. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14457. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14458. directive on the labels of function definitions to make sure the
  14459. bottom three bits are zero, which we put to use in
  14460. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14461. this section. \index{subject}{x86}
  14462. \newcommand{\GrammarXIndCall}{
  14463. \begin{array}{lcl}
  14464. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14465. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14466. \Block &::= & \Instr^{+} \\
  14467. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14468. \end{array}
  14469. }
  14470. \newcommand{\ASTXIndCallRacket}{
  14471. \begin{array}{lcl}
  14472. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14473. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14474. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14475. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14476. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14477. \end{array}
  14478. }
  14479. \begin{figure}[tp]
  14480. \begin{tcolorbox}[colback=white]
  14481. \small
  14482. \[
  14483. \begin{array}{l}
  14484. \gray{\GrammarXInt} \\ \hline
  14485. \gray{\GrammarXIf} \\ \hline
  14486. \gray{\GrammarXGlobal} \\ \hline
  14487. \GrammarXIndCall \\
  14488. \begin{array}{lcl}
  14489. \LangXIndCallM{} &::= & \Def^{*}
  14490. \end{array}
  14491. \end{array}
  14492. \]
  14493. \end{tcolorbox}
  14494. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14495. \label{fig:x86-3-concrete}
  14496. \end{figure}
  14497. \begin{figure}[tp]
  14498. \begin{tcolorbox}[colback=white]
  14499. \small
  14500. {\if\edition\racketEd
  14501. \[\arraycolsep=3pt
  14502. \begin{array}{l}
  14503. \gray{\ASTXIntRacket} \\ \hline
  14504. \gray{\ASTXIfRacket} \\ \hline
  14505. \gray{\ASTXGlobalRacket} \\ \hline
  14506. \ASTXIndCallRacket \\
  14507. \begin{array}{lcl}
  14508. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14509. \end{array}
  14510. \end{array}
  14511. \]
  14512. \fi}
  14513. {\if\edition\pythonEd\pythonColor
  14514. \[
  14515. \begin{array}{lcl}
  14516. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14517. \MID \BYTEREG{\Reg} } \\
  14518. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14519. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14520. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14521. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14522. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14523. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14524. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14525. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14526. \end{array}
  14527. \]
  14528. \fi}
  14529. \end{tcolorbox}
  14530. \caption{The abstract syntax of \LangXIndCall{} (extends
  14531. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14532. \label{fig:x86-3}
  14533. \end{figure}
  14534. An assignment of a function reference to a variable becomes a
  14535. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14536. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14537. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14538. node, whose concrete syntax is instruction-pointer-relative
  14539. addressing.
  14540. \begin{center}
  14541. \begin{tabular}{lcl}
  14542. \begin{minipage}{0.35\textwidth}
  14543. {\if\edition\racketEd
  14544. \begin{lstlisting}
  14545. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14546. \end{lstlisting}
  14547. \fi}
  14548. {\if\edition\pythonEd\pythonColor
  14549. \begin{lstlisting}
  14550. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14551. \end{lstlisting}
  14552. \fi}
  14553. \end{minipage}
  14554. &
  14555. $\Rightarrow$\qquad\qquad
  14556. &
  14557. \begin{minipage}{0.3\textwidth}
  14558. \begin{lstlisting}
  14559. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14560. \end{lstlisting}
  14561. \end{minipage}
  14562. \end{tabular}
  14563. \end{center}
  14564. Regarding function definitions, we need to remove the parameters and
  14565. instead perform parameter passing using the conventions discussed in
  14566. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14567. registers. We recommend turning the parameters into local variables
  14568. and generating instructions at the beginning of the function to move
  14569. from the argument-passing registers
  14570. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14571. {\if\edition\racketEd
  14572. \begin{lstlisting}
  14573. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14574. |$\Rightarrow$|
  14575. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14576. \end{lstlisting}
  14577. \fi}
  14578. {\if\edition\pythonEd\pythonColor
  14579. \begin{lstlisting}
  14580. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14581. |$\Rightarrow$|
  14582. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14583. \end{lstlisting}
  14584. \fi}
  14585. The basic blocks $B'$ are the same as $B$ except that the
  14586. \code{start} block is modified to add the instructions for moving from
  14587. the argument registers to the parameter variables. So the \code{start}
  14588. block of $B$ shown on the left of the following is changed to the code
  14589. on the right:
  14590. \begin{center}
  14591. \begin{minipage}{0.3\textwidth}
  14592. \begin{lstlisting}
  14593. start:
  14594. |$\itm{instr}_1$|
  14595. |$\cdots$|
  14596. |$\itm{instr}_n$|
  14597. \end{lstlisting}
  14598. \end{minipage}
  14599. $\Rightarrow$
  14600. \begin{minipage}{0.3\textwidth}
  14601. \begin{lstlisting}
  14602. |$f$|start:
  14603. movq %rdi, |$x_1$|
  14604. movq %rsi, |$x_2$|
  14605. |$\cdots$|
  14606. |$\itm{instr}_1$|
  14607. |$\cdots$|
  14608. |$\itm{instr}_n$|
  14609. \end{lstlisting}
  14610. \end{minipage}
  14611. \end{center}
  14612. Recall that we use the label \code{start} for the initial block of a
  14613. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14614. the conclusion of the program with \code{conclusion}, so that
  14615. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14616. by a jump to \code{conclusion}. With the addition of function
  14617. definitions, there is a start block and conclusion for each function,
  14618. but their labels need to be unique. We recommend prepending the
  14619. function's name to \code{start} and \code{conclusion}, respectively,
  14620. to obtain unique labels.
  14621. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14622. number of parameters the function expects, but the parameters are no
  14623. longer in the syntax of function definitions. Instead, add an entry
  14624. to $\itm{info}$ that maps \code{num-params} to the number of
  14625. parameters to construct $\itm{info}'$.}
  14626. By changing the parameters to local variables, we are giving the
  14627. register allocator control over which registers or stack locations to
  14628. use for them. If you implement the move-biasing challenge
  14629. (section~\ref{sec:move-biasing}), the register allocator will try to
  14630. assign the parameter variables to the corresponding argument register,
  14631. in which case the \code{patch\_instructions} pass will remove the
  14632. \code{movq} instruction. This happens in the example translation given
  14633. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14634. the \code{add} function.
  14635. %
  14636. Also, note that the register allocator will perform liveness analysis
  14637. on this sequence of move instructions and build the interference
  14638. graph. So, for example, $x_1$ will be marked as interfering with
  14639. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14640. which is good because otherwise the first \code{movq} would overwrite
  14641. the argument in \code{rsi} that is needed for $x_2$.
  14642. Next, consider the compilation of function calls. In the mirror image
  14643. of the handling of parameters in function definitions, the arguments
  14644. are moved to the argument-passing registers. Note that the function
  14645. is not given as a label, but its address is produced by the argument
  14646. $\itm{arg}_0$. So, we translate the call into an indirect function
  14647. call. The return value from the function is stored in \code{rax}, so
  14648. it needs to be moved into the \itm{lhs}.
  14649. \begin{lstlisting}
  14650. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14651. |$\Rightarrow$|
  14652. movq |$\itm{arg}_1$|, %rdi
  14653. movq |$\itm{arg}_2$|, %rsi
  14654. |$\vdots$|
  14655. callq *|$\itm{arg}_0$|
  14656. movq %rax, |$\itm{lhs}$|
  14657. \end{lstlisting}
  14658. The \code{IndirectCallq} AST node includes an integer for the arity of
  14659. the function, that is, the number of parameters. That information is
  14660. useful in the \code{uncover\_live} pass for determining which
  14661. argument-passing registers are potentially read during the call.
  14662. For tail calls, the parameter passing is the same as non-tail calls:
  14663. generate instructions to move the arguments into the argument-passing
  14664. registers. After that we need to pop the frame from the procedure
  14665. call stack. However, we do not yet know how big the frame is; that
  14666. gets determined during register allocation. So, instead of generating
  14667. those instructions here, we invent a new instruction that means ``pop
  14668. the frame and then do an indirect jump,'' which we name
  14669. \code{TailJmp}. The abstract syntax for this instruction includes an
  14670. argument that specifies where to jump and an integer that represents
  14671. the arity of the function being called.
  14672. \section{Register Allocation}
  14673. \label{sec:register-allocation-r4}
  14674. The addition of functions requires some changes to all three aspects
  14675. of register allocation, which we discuss in the following subsections.
  14676. \subsection{Liveness Analysis}
  14677. \label{sec:liveness-analysis-r4}
  14678. \index{subject}{liveness analysis}
  14679. %% The rest of the passes need only minor modifications to handle the new
  14680. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14681. %% \code{leaq}.
  14682. The \code{IndirectCallq} instruction should be treated like
  14683. \code{Callq} regarding its written locations $W$, in that they should
  14684. include all the caller-saved registers. Recall that the reason for
  14685. that is to force variables that are live across a function call to be assigned to callee-saved
  14686. registers or to be spilled to the stack.
  14687. Regarding the set of read locations $R$, the arity fields of
  14688. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14689. argument-passing registers should be considered as read by those
  14690. instructions. Also, the target field of \code{TailJmp} and
  14691. \code{IndirectCallq} should be included in the set of read locations
  14692. $R$.
  14693. \subsection{Build Interference Graph}
  14694. \label{sec:build-interference-r4}
  14695. With the addition of function definitions, we compute a separate interference
  14696. graph for each function (not just one for the whole program).
  14697. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14698. spill tuple-typed variables that are live during a call to
  14699. \code{collect}, the garbage collector. With the addition of functions
  14700. to our language, we need to revisit this issue. Functions that perform
  14701. allocation contain calls to the collector. Thus, we should not only
  14702. spill a tuple-typed variable when it is live during a call to
  14703. \code{collect}, but we should spill the variable if it is live during
  14704. a call to any user-defined function. Thus, in the
  14705. \code{build\_interference} pass, we recommend adding interference
  14706. edges between call-live tuple-typed variables and the callee-saved
  14707. registers (in addition to creating edges between
  14708. call-live variables and the caller-saved registers).
  14709. \subsection{Allocate Registers}
  14710. The primary change to the \code{allocate\_registers} pass is adding an
  14711. auxiliary function for handling definitions (the \Def{} nonterminal
  14712. shown in figure~\ref{fig:x86-3}) with one case for function
  14713. definitions. The logic is the same as described in
  14714. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14715. allocation is performed many times, once for each function definition,
  14716. instead of just once for the whole program.
  14717. \section{Patch Instructions}
  14718. In \code{patch\_instructions}, you should deal with the x86
  14719. idiosyncrasy that the destination argument of \code{leaq} must be a
  14720. register. Additionally, you should ensure that the argument of
  14721. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14722. trample many other registers before the tail call, as explained in the
  14723. next section.
  14724. \section{Prelude and Conclusion}
  14725. Now that register allocation is complete, we can translate the
  14726. \code{TailJmp} into a sequence of instructions. A naive translation of
  14727. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14728. before the jump we need to pop the current frame to achieve efficient
  14729. tail calls. This sequence of instructions is the same as the code for
  14730. the conclusion of a function, except that the \code{retq} is replaced with
  14731. \code{jmp *$\itm{arg}$}.
  14732. Regarding function definitions, we generate a prelude and conclusion
  14733. for each one. This code is similar to the prelude and conclusion
  14734. generated for the \code{main} function presented in
  14735. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14736. carry out the following steps:
  14737. % TODO: .align the functions!
  14738. \begin{enumerate}
  14739. %% \item Start with \code{.global} and \code{.align} directives followed
  14740. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14741. %% example.)
  14742. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14743. pointer.
  14744. \item Push to the stack all the callee-saved registers that were
  14745. used for register allocation.
  14746. \item Move the stack pointer \code{rsp} down to make room for the
  14747. regular spills (aligned to 16 bytes).
  14748. \item Move the root stack pointer \code{r15} up by the size of the
  14749. root-stack frame for this function, which depends on the number of
  14750. spilled tuple-typed variables. \label{root-stack-init}
  14751. \item Initialize to zero all new entries in the root-stack frame.
  14752. \item Jump to the start block.
  14753. \end{enumerate}
  14754. The prelude of the \code{main} function has an additional task: call
  14755. the \code{initialize} function to set up the garbage collector, and
  14756. then move the value of the global \code{rootstack\_begin} in
  14757. \code{r15}. This initialization should happen before step
  14758. \ref{root-stack-init}, which depends on \code{r15}.
  14759. The conclusion of every function should do the following:
  14760. \begin{enumerate}
  14761. \item Move the stack pointer back up past the regular spills.
  14762. \item Restore the callee-saved registers by popping them from the
  14763. stack.
  14764. \item Move the root stack pointer back down by the size of the
  14765. root-stack frame for this function.
  14766. \item Restore \code{rbp} by popping it from the stack.
  14767. \item Return to the caller with the \code{retq} instruction.
  14768. \end{enumerate}
  14769. The output of this pass is \LangXIndCallFlat{}, which differs from
  14770. \LangXIndCall{} in that there is no longer an AST node for function
  14771. definitions. Instead, a program is just an association list of basic
  14772. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  14773. \[
  14774. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  14775. \]
  14776. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  14777. compiling \LangFun{} to x86.
  14778. \begin{exercise}\normalfont\normalsize
  14779. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  14780. Create eight new programs that use functions including examples that
  14781. pass functions and return functions from other functions, recursive
  14782. functions, functions that create vectors, and functions that make tail
  14783. calls. Test your compiler on these new programs and all your
  14784. previously created test programs.
  14785. \end{exercise}
  14786. \begin{figure}[tbp]
  14787. \begin{tcolorbox}[colback=white]
  14788. {\if\edition\racketEd
  14789. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  14790. \node (Lfun) at (0,2) {\large \LangFun{}};
  14791. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  14792. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  14793. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  14794. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  14795. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  14796. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14797. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14798. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14799. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14800. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14801. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14802. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  14803. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  14804. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  14805. \path[->,bend left=15] (Lfun) edge [above] node
  14806. {\ttfamily\footnotesize shrink} (Lfun-1);
  14807. \path[->,bend left=15] (Lfun-1) edge [above] node
  14808. {\ttfamily\footnotesize uniquify} (Lfun-2);
  14809. \path[->,bend left=15] (Lfun-2) edge [above] node
  14810. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14811. \path[->,bend left=15] (F1-1) edge [left] node
  14812. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14813. \path[->,bend left=15] (F1-2) edge [below] node
  14814. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  14815. \path[->,bend left=15] (F1-3) edge [below] node
  14816. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  14817. \path[->,bend right=15] (F1-4) edge [above] node
  14818. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14819. \path[->,bend right=15] (F1-5) edge [right] node
  14820. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14821. \path[->,bend right=15] (C3-2) edge [right] node
  14822. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14823. \path[->,bend left=15] (x86-2) edge [right] node
  14824. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14825. \path[->,bend right=15] (x86-2-1) edge [below] node
  14826. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  14827. \path[->,bend right=15] (x86-2-2) edge [right] node
  14828. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  14829. \path[->,bend left=15] (x86-3) edge [above] node
  14830. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14831. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14832. \end{tikzpicture}
  14833. \fi}
  14834. {\if\edition\pythonEd\pythonColor
  14835. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  14836. \node (Lfun) at (0,2) {\large \LangFun{}};
  14837. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  14838. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  14839. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  14840. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14841. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14842. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14843. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14844. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14845. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14846. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  14847. \path[->,bend left=15] (Lfun) edge [above] node
  14848. {\ttfamily\footnotesize shrink} (Lfun-2);
  14849. \path[->,bend left=15] (Lfun-2) edge [above] node
  14850. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14851. \path[->,bend left=15] (F1-1) edge [above] node
  14852. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14853. \path[->,bend left=15] (F1-2) edge [right] node
  14854. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  14855. \path[->,bend right=15] (F1-4) edge [above] node
  14856. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14857. \path[->,bend right=15] (F1-5) edge [right] node
  14858. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14859. \path[->,bend left=15] (C3-2) edge [right] node
  14860. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14861. \path[->,bend right=15] (x86-2) edge [below] node
  14862. {\ttfamily\footnotesize assign\_homes} (x86-3);
  14863. \path[->,bend left=15] (x86-3) edge [above] node
  14864. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14865. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14866. \end{tikzpicture}
  14867. \fi}
  14868. \end{tcolorbox}
  14869. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  14870. \label{fig:Lfun-passes}
  14871. \end{figure}
  14872. \section{An Example Translation}
  14873. \label{sec:functions-example}
  14874. Figure~\ref{fig:add-fun} shows an example translation of a simple
  14875. function in \LangFun{} to x86. The figure also includes the results of the
  14876. \code{explicate\_control} and \code{select\_instructions} passes.
  14877. \begin{figure}[htbp]
  14878. \begin{tcolorbox}[colback=white]
  14879. \begin{tabular}{ll}
  14880. \begin{minipage}{0.4\textwidth}
  14881. % s3_2.rkt
  14882. {\if\edition\racketEd
  14883. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14884. (define (add [x : Integer]
  14885. [y : Integer])
  14886. : Integer
  14887. (+ x y))
  14888. (add 40 2)
  14889. \end{lstlisting}
  14890. \fi}
  14891. {\if\edition\pythonEd\pythonColor
  14892. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14893. def add(x:int, y:int) -> int:
  14894. return x + y
  14895. print(add(40, 2))
  14896. \end{lstlisting}
  14897. \fi}
  14898. $\Downarrow$
  14899. {\if\edition\racketEd
  14900. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14901. (define (add86 [x87 : Integer]
  14902. [y88 : Integer])
  14903. : Integer
  14904. add86start:
  14905. return (+ x87 y88);
  14906. )
  14907. (define (main) : Integer ()
  14908. mainstart:
  14909. tmp89 = (fun-ref add86 2);
  14910. (tail-call tmp89 40 2)
  14911. )
  14912. \end{lstlisting}
  14913. \fi}
  14914. {\if\edition\pythonEd\pythonColor
  14915. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14916. def add(x:int, y:int) -> int:
  14917. addstart:
  14918. return x + y
  14919. def main() -> int:
  14920. mainstart:
  14921. fun.0 = add
  14922. tmp.1 = fun.0(40, 2)
  14923. print(tmp.1)
  14924. return 0
  14925. \end{lstlisting}
  14926. \fi}
  14927. \end{minipage}
  14928. &
  14929. $\Rightarrow$
  14930. \begin{minipage}{0.5\textwidth}
  14931. {\if\edition\racketEd
  14932. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14933. (define (add86) : Integer
  14934. add86start:
  14935. movq %rdi, x87
  14936. movq %rsi, y88
  14937. movq x87, %rax
  14938. addq y88, %rax
  14939. jmp inc1389conclusion
  14940. )
  14941. (define (main) : Integer
  14942. mainstart:
  14943. leaq (fun-ref add86 2), tmp89
  14944. movq $40, %rdi
  14945. movq $2, %rsi
  14946. tail-jmp tmp89
  14947. )
  14948. \end{lstlisting}
  14949. \fi}
  14950. {\if\edition\pythonEd\pythonColor
  14951. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14952. def add() -> int:
  14953. addstart:
  14954. movq %rdi, x
  14955. movq %rsi, y
  14956. movq x, %rax
  14957. addq y, %rax
  14958. jmp addconclusion
  14959. def main() -> int:
  14960. mainstart:
  14961. leaq add, fun.0
  14962. movq $40, %rdi
  14963. movq $2, %rsi
  14964. callq *fun.0
  14965. movq %rax, tmp.1
  14966. movq tmp.1, %rdi
  14967. callq print_int
  14968. movq $0, %rax
  14969. jmp mainconclusion
  14970. \end{lstlisting}
  14971. \fi}
  14972. $\Downarrow$
  14973. \end{minipage}
  14974. \end{tabular}
  14975. \begin{tabular}{ll}
  14976. \begin{minipage}{0.3\textwidth}
  14977. {\if\edition\racketEd
  14978. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14979. .globl add86
  14980. .align 8
  14981. add86:
  14982. pushq %rbp
  14983. movq %rsp, %rbp
  14984. jmp add86start
  14985. add86start:
  14986. movq %rdi, %rax
  14987. addq %rsi, %rax
  14988. jmp add86conclusion
  14989. add86conclusion:
  14990. popq %rbp
  14991. retq
  14992. \end{lstlisting}
  14993. \fi}
  14994. {\if\edition\pythonEd\pythonColor
  14995. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14996. .align 8
  14997. add:
  14998. pushq %rbp
  14999. movq %rsp, %rbp
  15000. subq $0, %rsp
  15001. jmp addstart
  15002. addstart:
  15003. movq %rdi, %rdx
  15004. movq %rsi, %rcx
  15005. movq %rdx, %rax
  15006. addq %rcx, %rax
  15007. jmp addconclusion
  15008. addconclusion:
  15009. subq $0, %r15
  15010. addq $0, %rsp
  15011. popq %rbp
  15012. retq
  15013. \end{lstlisting}
  15014. \fi}
  15015. \end{minipage}
  15016. &
  15017. \begin{minipage}{0.5\textwidth}
  15018. {\if\edition\racketEd
  15019. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15020. .globl main
  15021. .align 8
  15022. main:
  15023. pushq %rbp
  15024. movq %rsp, %rbp
  15025. movq $16384, %rdi
  15026. movq $16384, %rsi
  15027. callq initialize
  15028. movq rootstack_begin(%rip), %r15
  15029. jmp mainstart
  15030. mainstart:
  15031. leaq add86(%rip), %rcx
  15032. movq $40, %rdi
  15033. movq $2, %rsi
  15034. movq %rcx, %rax
  15035. popq %rbp
  15036. jmp *%rax
  15037. mainconclusion:
  15038. popq %rbp
  15039. retq
  15040. \end{lstlisting}
  15041. \fi}
  15042. {\if\edition\pythonEd\pythonColor
  15043. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15044. .globl main
  15045. .align 8
  15046. main:
  15047. pushq %rbp
  15048. movq %rsp, %rbp
  15049. subq $0, %rsp
  15050. movq $65536, %rdi
  15051. movq $65536, %rsi
  15052. callq initialize
  15053. movq rootstack_begin(%rip), %r15
  15054. jmp mainstart
  15055. mainstart:
  15056. leaq add(%rip), %rcx
  15057. movq $40, %rdi
  15058. movq $2, %rsi
  15059. callq *%rcx
  15060. movq %rax, %rcx
  15061. movq %rcx, %rdi
  15062. callq print_int
  15063. movq $0, %rax
  15064. jmp mainconclusion
  15065. mainconclusion:
  15066. subq $0, %r15
  15067. addq $0, %rsp
  15068. popq %rbp
  15069. retq
  15070. \end{lstlisting}
  15071. \fi}
  15072. \end{minipage}
  15073. \end{tabular}
  15074. \end{tcolorbox}
  15075. \caption{Example compilation of a simple function to x86.}
  15076. \label{fig:add-fun}
  15077. \end{figure}
  15078. % Challenge idea: inlining! (simple version)
  15079. % Further Reading
  15080. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15081. \chapter{Lexically Scoped Functions}
  15082. \label{ch:Llambda}
  15083. \setcounter{footnote}{0}
  15084. This chapter studies lexically scoped functions. Lexical
  15085. scoping\index{subject}{lexical scoping} means that a function's body
  15086. may refer to variables whose binding site is outside of the function,
  15087. in an enclosing scope.
  15088. %
  15089. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15090. in \LangLam{}, which extends \LangFun{} with the
  15091. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15092. functions. The body of the \key{lambda} refers to three variables:
  15093. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15094. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15095. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15096. function \code{f}}, and \code{x} is a parameter of function
  15097. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15098. result value. The main expression of the program includes two calls to
  15099. \code{f} with different arguments for \code{x}: first \code{5} and
  15100. then \code{3}. The functions returned from \code{f} are bound to
  15101. variables \code{g} and \code{h}. Even though these two functions were
  15102. created by the same \code{lambda}, they are really different functions
  15103. because they use different values for \code{x}. Applying \code{g} to
  15104. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15105. produces \code{22}, so the result of the program is \code{42}.
  15106. \begin{figure}[btp]
  15107. \begin{tcolorbox}[colback=white]
  15108. {\if\edition\racketEd
  15109. % lambda_test_21.rkt
  15110. \begin{lstlisting}
  15111. (define (f [x : Integer]) : (Integer -> Integer)
  15112. (let ([y 4])
  15113. (lambda: ([z : Integer]) : Integer
  15114. (+ x (+ y z)))))
  15115. (let ([g (f 5)])
  15116. (let ([h (f 3)])
  15117. (+ (g 11) (h 15))))
  15118. \end{lstlisting}
  15119. \fi}
  15120. {\if\edition\pythonEd\pythonColor
  15121. \begin{lstlisting}
  15122. def f(x : int) -> Callable[[int], int]:
  15123. y = 4
  15124. return lambda z: x + y + z
  15125. g = f(5)
  15126. h = f(3)
  15127. print( g(11) + h(15) )
  15128. \end{lstlisting}
  15129. \fi}
  15130. \end{tcolorbox}
  15131. \caption{Example of a lexically scoped function.}
  15132. \label{fig:lexical-scoping}
  15133. \end{figure}
  15134. The approach that we take for implementing lexically scoped functions
  15135. is to compile them into top-level function definitions, translating
  15136. from \LangLam{} into \LangFun{}. However, the compiler must give
  15137. special treatment to variable occurrences such as \code{x} and
  15138. \code{y} in the body of the \code{lambda} shown in
  15139. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15140. may not refer to variables defined outside of it. To identify such
  15141. variable occurrences, we review the standard notion of free variable.
  15142. \begin{definition}\normalfont
  15143. A variable is \emph{free in expression} $e$ if the variable occurs
  15144. inside $e$ but does not have an enclosing definition that is also in
  15145. $e$.\index{subject}{free variable}
  15146. \end{definition}
  15147. For example, in the expression
  15148. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15149. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15150. only \code{x} and \code{y} are free in the following expression,
  15151. because \code{z} is defined by the \code{lambda}
  15152. {\if\edition\racketEd
  15153. \begin{lstlisting}
  15154. (lambda: ([z : Integer]) : Integer
  15155. (+ x (+ y z)))
  15156. \end{lstlisting}
  15157. \fi}
  15158. {\if\edition\pythonEd\pythonColor
  15159. \begin{lstlisting}
  15160. lambda z: x + y + z
  15161. \end{lstlisting}
  15162. \fi}
  15163. %
  15164. \noindent Thus the free variables of a \code{lambda} are the ones that
  15165. need special treatment. We need to transport at runtime the values
  15166. of those variables from the point where the \code{lambda} was created
  15167. to the point where the \code{lambda} is applied. An efficient solution
  15168. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15169. values of the free variables together with a function pointer into a
  15170. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15171. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15172. closure}
  15173. %
  15174. By design, we have all the ingredients to make closures:
  15175. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15176. function pointers. The function pointer resides at index $0$, and the
  15177. values for the free variables fill in the rest of the tuple.
  15178. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15179. to see how closures work. It is a three-step dance. The program calls
  15180. function \code{f}, which creates a closure for the \code{lambda}. The
  15181. closure is a tuple whose first element is a pointer to the top-level
  15182. function that we will generate for the \code{lambda}; the second
  15183. element is the value of \code{x}, which is \code{5}; and the third
  15184. element is \code{4}, the value of \code{y}. The closure does not
  15185. contain an element for \code{z} because \code{z} is not a free
  15186. variable of the \code{lambda}. Creating the closure is step 1 of the
  15187. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15188. shown in figure~\ref{fig:closures}.
  15189. %
  15190. The second call to \code{f} creates another closure, this time with
  15191. \code{3} in the second slot (for \code{x}). This closure is also
  15192. returned from \code{f} but bound to \code{h}, which is also shown in
  15193. figure~\ref{fig:closures}.
  15194. \begin{figure}[tbp]
  15195. \centering
  15196. \begin{minipage}{0.65\textwidth}
  15197. \begin{tcolorbox}[colback=white]
  15198. \includegraphics[width=\textwidth]{figs/closures}
  15199. \end{tcolorbox}
  15200. \end{minipage}
  15201. \caption{Flat closure representations for the two functions
  15202. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15203. \label{fig:closures}
  15204. \end{figure}
  15205. Continuing with the example, consider the application of \code{g} to
  15206. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15207. closure, we obtain the function pointer from the first element of the
  15208. closure and call it, passing in the closure itself and then the
  15209. regular arguments, in this case \code{11}. This technique for applying
  15210. a closure is step 2 of the dance.
  15211. %
  15212. But doesn't this \code{lambda} take only one argument, for parameter
  15213. \code{z}? The third and final step of the dance is generating a
  15214. top-level function for a \code{lambda}. We add an additional
  15215. parameter for the closure and insert an initialization at the beginning
  15216. of the function for each free variable, to bind those variables to the
  15217. appropriate elements from the closure parameter.
  15218. %
  15219. This three-step dance is known as \emph{closure
  15220. conversion}\index{subject}{closure conversion}. We discuss the
  15221. details of closure conversion in section~\ref{sec:closure-conversion}
  15222. and show the code generated from the example in
  15223. section~\ref{sec:example-lambda}. First, we define the syntax and
  15224. semantics of \LangLam{} in section~\ref{sec:r5}.
  15225. \section{The \LangLam{} Language}
  15226. \label{sec:r5}
  15227. The definitions of the concrete syntax and abstract syntax for
  15228. \LangLam{}, a language with anonymous functions and lexical scoping,
  15229. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15230. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15231. for \LangFun{}, which already has syntax for function application.
  15232. %
  15233. \python{The syntax also includes an assignment statement that includes
  15234. a type annotation for the variable on the left-hand side, which
  15235. facilitates the type checking of \code{lambda} expressions that we
  15236. discuss later in this section.}
  15237. %
  15238. \racket{The \code{procedure-arity} operation returns the number of parameters
  15239. of a given function, an operation that we need for the translation
  15240. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  15241. %
  15242. \python{The \code{arity} operation returns the number of parameters of
  15243. a given function, an operation that we need for the translation
  15244. of dynamic typing in chapter~\ref{ch:Ldyn}.
  15245. The \code{arity} operation is not in Python, but the same functionality
  15246. is available in a more complex form. We include \code{arity} in the
  15247. \LangLam{} source language to enable testing.}
  15248. \newcommand{\LlambdaGrammarRacket}{
  15249. \begin{array}{lcl}
  15250. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15251. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15252. \end{array}
  15253. }
  15254. \newcommand{\LlambdaASTRacket}{
  15255. \begin{array}{lcl}
  15256. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15257. \itm{op} &::=& \code{procedure-arity}
  15258. \end{array}
  15259. }
  15260. \newcommand{\LlambdaGrammarPython}{
  15261. \begin{array}{lcl}
  15262. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15263. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15264. \end{array}
  15265. }
  15266. \newcommand{\LlambdaASTPython}{
  15267. \begin{array}{lcl}
  15268. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15269. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15270. \end{array}
  15271. }
  15272. % include AnnAssign in ASTPython
  15273. \begin{figure}[tp]
  15274. \centering
  15275. \begin{tcolorbox}[colback=white]
  15276. \small
  15277. {\if\edition\racketEd
  15278. \[
  15279. \begin{array}{l}
  15280. \gray{\LintGrammarRacket{}} \\ \hline
  15281. \gray{\LvarGrammarRacket{}} \\ \hline
  15282. \gray{\LifGrammarRacket{}} \\ \hline
  15283. \gray{\LwhileGrammarRacket} \\ \hline
  15284. \gray{\LtupGrammarRacket} \\ \hline
  15285. \gray{\LfunGrammarRacket} \\ \hline
  15286. \LlambdaGrammarRacket \\
  15287. \begin{array}{lcl}
  15288. \LangLamM{} &::=& \Def\ldots \; \Exp
  15289. \end{array}
  15290. \end{array}
  15291. \]
  15292. \fi}
  15293. {\if\edition\pythonEd\pythonColor
  15294. \[
  15295. \begin{array}{l}
  15296. \gray{\LintGrammarPython{}} \\ \hline
  15297. \gray{\LvarGrammarPython{}} \\ \hline
  15298. \gray{\LifGrammarPython{}} \\ \hline
  15299. \gray{\LwhileGrammarPython} \\ \hline
  15300. \gray{\LtupGrammarPython} \\ \hline
  15301. \gray{\LfunGrammarPython} \\ \hline
  15302. \LlambdaGrammarPython \\
  15303. \begin{array}{lcl}
  15304. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15305. \end{array}
  15306. \end{array}
  15307. \]
  15308. \fi}
  15309. \end{tcolorbox}
  15310. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15311. with \key{lambda}.}
  15312. \label{fig:Llam-concrete-syntax}
  15313. \end{figure}
  15314. \begin{figure}[tp]
  15315. \centering
  15316. \begin{tcolorbox}[colback=white]
  15317. \small
  15318. {\if\edition\racketEd
  15319. \[\arraycolsep=3pt
  15320. \begin{array}{l}
  15321. \gray{\LintOpAST} \\ \hline
  15322. \gray{\LvarASTRacket{}} \\ \hline
  15323. \gray{\LifASTRacket{}} \\ \hline
  15324. \gray{\LwhileASTRacket{}} \\ \hline
  15325. \gray{\LtupASTRacket{}} \\ \hline
  15326. \gray{\LfunASTRacket} \\ \hline
  15327. \LlambdaASTRacket \\
  15328. \begin{array}{lcl}
  15329. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15330. \end{array}
  15331. \end{array}
  15332. \]
  15333. \fi}
  15334. {\if\edition\pythonEd\pythonColor
  15335. \[
  15336. \begin{array}{l}
  15337. \gray{\LintASTPython} \\ \hline
  15338. \gray{\LvarASTPython{}} \\ \hline
  15339. \gray{\LifASTPython{}} \\ \hline
  15340. \gray{\LwhileASTPython{}} \\ \hline
  15341. \gray{\LtupASTPython{}} \\ \hline
  15342. \gray{\LfunASTPython} \\ \hline
  15343. \LlambdaASTPython \\
  15344. \begin{array}{lcl}
  15345. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15346. \end{array}
  15347. \end{array}
  15348. \]
  15349. \fi}
  15350. \end{tcolorbox}
  15351. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15352. \label{fig:Llam-syntax}
  15353. \end{figure}
  15354. Figure~\ref{fig:interp-Llambda} shows the definitional
  15355. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15356. \key{Lambda} saves the current environment inside the returned
  15357. function value. Recall that during function application, the
  15358. environment stored in the function value, extended with the mapping of
  15359. parameters to argument values, is used to interpret the body of the
  15360. function.
  15361. \begin{figure}[tbp]
  15362. \begin{tcolorbox}[colback=white]
  15363. {\if\edition\racketEd
  15364. \begin{lstlisting}
  15365. (define interp-Llambda-class
  15366. (class interp-Lfun-class
  15367. (super-new)
  15368. (define/override (interp-op op)
  15369. (match op
  15370. ['procedure-arity
  15371. (lambda (v)
  15372. (match v
  15373. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15374. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15375. [else (super interp-op op)]))
  15376. (define/override ((interp-exp env) e)
  15377. (define recur (interp-exp env))
  15378. (match e
  15379. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15380. `(function ,xs ,body ,env)]
  15381. [else ((super interp-exp env) e)]))
  15382. ))
  15383. (define (interp-Llambda p)
  15384. (send (new interp-Llambda-class) interp-program p))
  15385. \end{lstlisting}
  15386. \fi}
  15387. {\if\edition\pythonEd\pythonColor
  15388. \begin{lstlisting}
  15389. class InterpLlambda(InterpLfun):
  15390. def arity(self, v):
  15391. match v:
  15392. case Function(name, params, body, env):
  15393. return len(params)
  15394. case _:
  15395. raise Exception('Llambda arity unexpected ' + repr(v))
  15396. def interp_exp(self, e, env):
  15397. match e:
  15398. case Call(Name('arity'), [fun]):
  15399. f = self.interp_exp(fun, env)
  15400. return self.arity(f)
  15401. case Lambda(params, body):
  15402. return Function('lambda', params, [Return(body)], env)
  15403. case _:
  15404. return super().interp_exp(e, env)
  15405. def interp_stmt(self, s, env, cont):
  15406. match s:
  15407. case AnnAssign(lhs, typ, value, simple):
  15408. env[lhs.id] = self.interp_exp(value, env)
  15409. return self.interp_stmts(cont, env)
  15410. case Pass():
  15411. return self.interp_stmts(cont, env)
  15412. case _:
  15413. return super().interp_stmt(s, env, cont)
  15414. \end{lstlisting}
  15415. \fi}
  15416. \end{tcolorbox}
  15417. \caption{Interpreter for \LangLam{}.}
  15418. \label{fig:interp-Llambda}
  15419. \end{figure}
  15420. {\if\edition\racketEd
  15421. %
  15422. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15423. \key{lambda} form. The body of the \key{lambda} is checked in an
  15424. environment that includes the current environment (because it is
  15425. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15426. require the body's type to match the declared return type.
  15427. %
  15428. \fi}
  15429. {\if\edition\pythonEd\pythonColor
  15430. %
  15431. Figures~\ref{fig:type-check-Llambda} and
  15432. \ref{fig:type-check-Llambda-part2} define the type checker for
  15433. \LangLam{}, which is more complex than one might expect. The reason
  15434. for the added complexity is that the syntax of \key{lambda} does not
  15435. include type annotations for the parameters or return type. Instead
  15436. they must be inferred. There are many approaches of type inference to
  15437. choose from of varying degrees of complexity. We choose one of the
  15438. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  15439. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  15440. this book is compilation, not type inference.
  15441. The main idea of bidirectional type inference is to add an auxiliary
  15442. function, here named \code{check\_exp}, that takes an expected type
  15443. and checks whether the given expression is of that type. Thus, in
  15444. \code{check\_exp}, type information flows in a top-down manner with
  15445. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15446. function, where type information flows in a primarily bottom-up
  15447. manner.
  15448. %
  15449. The idea then is to use \code{check\_exp} in all the places where we
  15450. already know what the type of an expression should be, such as in the
  15451. \code{return} statement of a top-level function definition, or on the
  15452. right-hand side of an annotated assignment statement.
  15453. Getting back to \code{lambda}, it is straightforward to check a
  15454. \code{lambda} inside \code{check\_exp} because the expected type
  15455. provides the parameter types and the return type. On the other hand,
  15456. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15457. that we do not allow \code{lambda} in contexts where we don't already
  15458. know its type. This restriction does not incur a loss of
  15459. expressiveness for \LangLam{} because it is straightforward to modify
  15460. a program to sidestep the restriction, for example, by using an
  15461. annotated assignment statement to assign the \code{lambda} to a
  15462. temporary variable.
  15463. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15464. checker records their type in a \code{has\_type} field. This type
  15465. information is used later in this chapter.
  15466. %
  15467. \fi}
  15468. \begin{figure}[tbp]
  15469. \begin{tcolorbox}[colback=white]
  15470. {\if\edition\racketEd
  15471. \begin{lstlisting}
  15472. (define (type-check-Llambda env)
  15473. (lambda (e)
  15474. (match e
  15475. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15476. (define-values (new-body bodyT)
  15477. ((type-check-exp (append (map cons xs Ts) env)) body))
  15478. (define ty `(,@Ts -> ,rT))
  15479. (cond
  15480. [(equal? rT bodyT)
  15481. (values (HasType (Lambda params rT new-body) ty) ty)]
  15482. [else
  15483. (error "mismatch in return type" bodyT rT)])]
  15484. ...
  15485. )))
  15486. \end{lstlisting}
  15487. \fi}
  15488. {\if\edition\pythonEd\pythonColor
  15489. \begin{lstlisting}
  15490. class TypeCheckLlambda(TypeCheckLfun):
  15491. def type_check_exp(self, e, env):
  15492. match e:
  15493. case Name(id):
  15494. e.has_type = env[id]
  15495. return env[id]
  15496. case Lambda(params, body):
  15497. raise Exception('cannot synthesize a type for a lambda')
  15498. case Call(Name('arity'), [func]):
  15499. func_t = self.type_check_exp(func, env)
  15500. match func_t:
  15501. case FunctionType(params_t, return_t):
  15502. return IntType()
  15503. case _:
  15504. raise Exception('in arity, unexpected ' + repr(func_t))
  15505. case _:
  15506. return super().type_check_exp(e, env)
  15507. def check_exp(self, e, ty, env):
  15508. match e:
  15509. case Lambda(params, body):
  15510. e.has_type = ty
  15511. match ty:
  15512. case FunctionType(params_t, return_t):
  15513. new_env = env.copy().update(zip(params, params_t))
  15514. self.check_exp(body, return_t, new_env)
  15515. case _:
  15516. raise Exception('lambda does not have type ' + str(ty))
  15517. case Call(func, args):
  15518. func_t = self.type_check_exp(func, env)
  15519. match func_t:
  15520. case FunctionType(params_t, return_t):
  15521. for (arg, param_t) in zip(args, params_t):
  15522. self.check_exp(arg, param_t, env)
  15523. self.check_type_equal(return_t, ty, e)
  15524. case _:
  15525. raise Exception('type_check_exp: in call, unexpected ' + \
  15526. repr(func_t))
  15527. case _:
  15528. t = self.type_check_exp(e, env)
  15529. self.check_type_equal(t, ty, e)
  15530. \end{lstlisting}
  15531. \fi}
  15532. \end{tcolorbox}
  15533. \caption{Type checking \LangLam{}\python{, part 1}.}
  15534. \label{fig:type-check-Llambda}
  15535. \end{figure}
  15536. {\if\edition\pythonEd\pythonColor
  15537. \begin{figure}[tbp]
  15538. \begin{tcolorbox}[colback=white]
  15539. \begin{lstlisting}
  15540. def check_stmts(self, ss, return_ty, env):
  15541. if len(ss) == 0:
  15542. return
  15543. match ss[0]:
  15544. case FunctionDef(name, params, body, dl, returns, comment):
  15545. new_env = env.copy().update(params)
  15546. rt = self.check_stmts(body, returns, new_env)
  15547. self.check_stmts(ss[1:], return_ty, env)
  15548. case Return(value):
  15549. self.check_exp(value, return_ty, env)
  15550. case Assign([Name(id)], value):
  15551. if id in env:
  15552. self.check_exp(value, env[id], env)
  15553. else:
  15554. env[id] = self.type_check_exp(value, env)
  15555. self.check_stmts(ss[1:], return_ty, env)
  15556. case Assign([Subscript(tup, Constant(index), Store())], value):
  15557. tup_t = self.type_check_exp(tup, env)
  15558. match tup_t:
  15559. case TupleType(ts):
  15560. self.check_exp(value, ts[index], env)
  15561. case _:
  15562. raise Exception('expected a tuple, not ' + repr(tup_t))
  15563. self.check_stmts(ss[1:], return_ty, env)
  15564. case AnnAssign(Name(id), ty_annot, value, simple):
  15565. ss[0].annotation = ty_annot
  15566. if id in env:
  15567. self.check_type_equal(env[id], ty_annot)
  15568. else:
  15569. env[id] = ty_annot
  15570. self.check_exp(value, ty_annot, env)
  15571. self.check_stmts(ss[1:], return_ty, env)
  15572. case _:
  15573. self.type_check_stmts(ss, env)
  15574. def type_check(self, p):
  15575. match p:
  15576. case Module(body):
  15577. env = {}
  15578. for s in body:
  15579. match s:
  15580. case FunctionDef(name, params, bod, dl, returns, comment):
  15581. params_t = [t for (x,t) in params]
  15582. env[name] = FunctionType(params_t, returns)
  15583. self.check_stmts(body, int, env)
  15584. \end{lstlisting}
  15585. \end{tcolorbox}
  15586. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15587. \label{fig:type-check-Llambda-part2}
  15588. \end{figure}
  15589. \fi}
  15590. \clearpage
  15591. \section{Assignment and Lexically Scoped Functions}
  15592. \label{sec:assignment-scoping}
  15593. The combination of lexically scoped functions and assignment to
  15594. variables raises a challenge with the flat-closure approach to
  15595. implementing lexically scoped functions. Consider the following
  15596. example in which function \code{f} has a free variable \code{x} that
  15597. is changed after \code{f} is created but before the call to \code{f}.
  15598. % loop_test_11.rkt
  15599. {\if\edition\racketEd
  15600. \begin{lstlisting}
  15601. (let ([x 0])
  15602. (let ([y 0])
  15603. (let ([z 20])
  15604. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15605. (begin
  15606. (set! x 10)
  15607. (set! y 12)
  15608. (f y))))))
  15609. \end{lstlisting}
  15610. \fi}
  15611. {\if\edition\pythonEd\pythonColor
  15612. % box_free_assign.py
  15613. \begin{lstlisting}
  15614. def g(z : int) -> int:
  15615. x = 0
  15616. y = 0
  15617. f : Callable[[int],int] = lambda a: a + x + z
  15618. x = 10
  15619. y = 12
  15620. return f(y)
  15621. print( g(20) )
  15622. \end{lstlisting}
  15623. \fi} The correct output for this example is \code{42} because the call
  15624. to \code{f} is required to use the current value of \code{x} (which is
  15625. \code{10}). Unfortunately, the closure conversion pass
  15626. (section~\ref{sec:closure-conversion}) generates code for the
  15627. \code{lambda} that copies the old value of \code{x} into a
  15628. closure. Thus, if we naively applied closure conversion, the output of
  15629. this program would be \code{32}.
  15630. A first attempt at solving this problem would be to save a pointer to
  15631. \code{x} in the closure and change the occurrences of \code{x} inside
  15632. the lambda to dereference the pointer. Of course, this would require
  15633. assigning \code{x} to the stack and not to a register. However, the
  15634. problem goes a bit deeper.
  15635. Consider the following example that returns a function that refers to
  15636. a local variable of the enclosing function:
  15637. \begin{center}
  15638. \begin{minipage}{\textwidth}
  15639. {\if\edition\racketEd
  15640. \begin{lstlisting}
  15641. (define (f) : ( -> Integer)
  15642. (let ([x 0])
  15643. (let ([g (lambda: () : Integer x)])
  15644. (begin
  15645. (set! x 42)
  15646. g))))
  15647. ((f))
  15648. \end{lstlisting}
  15649. \fi}
  15650. {\if\edition\pythonEd\pythonColor
  15651. % counter.py
  15652. \begin{lstlisting}
  15653. def f():
  15654. x = 0
  15655. g = lambda: x
  15656. x = 42
  15657. return g
  15658. print( f()() )
  15659. \end{lstlisting}
  15660. \fi}
  15661. \end{minipage}
  15662. \end{center}
  15663. In this example, the lifetime of \code{x} extends beyond the lifetime
  15664. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15665. stack frame for the call to \code{f}, it would be gone by the time we
  15666. called \code{g}, leaving us with dangling pointers for
  15667. \code{x}. This example demonstrates that when a variable occurs free
  15668. inside a function, its lifetime becomes indefinite. Thus, the value of
  15669. the variable needs to live on the heap. The verb
  15670. \emph{box}\index{subject}{box} is often used for allocating a single
  15671. value on the heap, producing a pointer, and
  15672. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15673. %
  15674. We introduce a new pass named \code{convert\_assignments} to address
  15675. this challenge.
  15676. %
  15677. \python{But before diving into that, we have one more
  15678. problem to discuss.}
  15679. {\if\edition\pythonEd\pythonColor
  15680. \section{Uniquify Variables}
  15681. \label{sec:uniquify-lambda}
  15682. With the addition of \code{lambda} we have a complication to deal
  15683. with: name shadowing. Consider the following program with a function
  15684. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15685. \code{lambda} expressions. The first \code{lambda} has a parameter
  15686. that is also named \code{x}.
  15687. \begin{lstlisting}
  15688. def f(x:int, y:int) -> Callable[[int], int]:
  15689. g : Callable[[int],int] = (lambda x: x + y)
  15690. h : Callable[[int],int] = (lambda y: x + y)
  15691. x = input_int()
  15692. return g
  15693. print(f(0, 10)(32))
  15694. \end{lstlisting}
  15695. Many of our compiler passes rely on being able to connect variable
  15696. uses with their definitions using just the name of the variable,
  15697. including new passes in this chapter. However, in the above example
  15698. the name of the variable does not uniquely determine its
  15699. definition. To solve this problem we recommend implementing a pass
  15700. named \code{uniquify} that renames every variable in the program to
  15701. make sure they are all unique.
  15702. The following shows the result of \code{uniquify} for the above
  15703. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  15704. and the \code{x} parameter of the \code{lambda} is renamed to
  15705. \code{x\_4}.
  15706. \begin{lstlisting}
  15707. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15708. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15709. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15710. x_0 = input_int()
  15711. return g_2
  15712. def main() -> int :
  15713. print(f(0, 10)(32))
  15714. return 0
  15715. \end{lstlisting}
  15716. \fi} % pythonEd
  15717. %% \section{Reveal Functions}
  15718. %% \label{sec:reveal-functions-r5}
  15719. %% \racket{To support the \code{procedure-arity} operator we need to
  15720. %% communicate the arity of a function to the point of closure
  15721. %% creation.}
  15722. %% %
  15723. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15724. %% function at runtime. Thus, we need to communicate the arity of a
  15725. %% function to the point of closure creation.}
  15726. %% %
  15727. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15728. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15729. %% \[
  15730. %% \begin{array}{lcl}
  15731. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15732. %% \end{array}
  15733. %% \]
  15734. \section{Assignment Conversion}
  15735. \label{sec:convert-assignments}
  15736. The purpose of the \code{convert\_assignments} pass is to address the
  15737. challenge regarding the interaction between variable assignments and
  15738. closure conversion. First we identify which variables need to be
  15739. boxed, and then we transform the program to box those variables. In
  15740. general, boxing introduces runtime overhead that we would like to
  15741. avoid, so we should box as few variables as possible. We recommend
  15742. boxing the variables in the intersection of the following two sets of
  15743. variables:
  15744. \begin{enumerate}
  15745. \item The variables that are free in a \code{lambda}.
  15746. \item The variables that appear on the left-hand side of an
  15747. assignment.
  15748. \end{enumerate}
  15749. The first condition is a must but the second condition is
  15750. conservative. It is possible to develop a more liberal condition using
  15751. static program analysis.
  15752. Consider again the first example from
  15753. section~\ref{sec:assignment-scoping}:
  15754. %
  15755. {\if\edition\racketEd
  15756. \begin{lstlisting}
  15757. (let ([x 0])
  15758. (let ([y 0])
  15759. (let ([z 20])
  15760. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15761. (begin
  15762. (set! x 10)
  15763. (set! y 12)
  15764. (f y))))))
  15765. \end{lstlisting}
  15766. \fi}
  15767. {\if\edition\pythonEd\pythonColor
  15768. \begin{lstlisting}
  15769. def g(z : int) -> int:
  15770. x = 0
  15771. y = 0
  15772. f : Callable[[int],int] = lambda a: a + x + z
  15773. x = 10
  15774. y = 12
  15775. return f(y)
  15776. print( g(20) )
  15777. \end{lstlisting}
  15778. \fi}
  15779. %
  15780. \noindent The variables \code{x} and \code{y} appear on the left-hand
  15781. side of assignments. The variables \code{x} and \code{z} occur free
  15782. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  15783. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  15784. three transformations: initialize \code{x} with a tuple whose elements
  15785. are uninitialized, replace reads from \code{x} with tuple reads, and
  15786. replace each assignment to \code{x} with a tuple write. The output of
  15787. \code{convert\_assignments} for this example is as follows:
  15788. %
  15789. {\if\edition\racketEd
  15790. \begin{lstlisting}
  15791. (define (main) : Integer
  15792. (let ([x0 (vector 0)])
  15793. (let ([y1 0])
  15794. (let ([z2 20])
  15795. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  15796. (+ a3 (+ (vector-ref x0 0) z2)))])
  15797. (begin
  15798. (vector-set! x0 0 10)
  15799. (set! y1 12)
  15800. (f4 y1)))))))
  15801. \end{lstlisting}
  15802. \fi}
  15803. %
  15804. {\if\edition\pythonEd\pythonColor
  15805. \begin{lstlisting}
  15806. def g(z : int)-> int:
  15807. x = (uninitialized(int),)
  15808. x[0] = 0
  15809. y = 0
  15810. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  15811. x[0] = 10
  15812. y = 12
  15813. return f(y)
  15814. def main() -> int:
  15815. print(g(20))
  15816. return 0
  15817. \end{lstlisting}
  15818. \fi}
  15819. To compute the free variables of all the \code{lambda} expressions, we
  15820. recommend defining the following two auxiliary functions:
  15821. \begin{enumerate}
  15822. \item \code{free\_variables} computes the free variables of an expression, and
  15823. \item \code{free\_in\_lambda} collects all the variables that are
  15824. free in any of the \code{lambda} expressions, using
  15825. \code{free\_variables} in the case for each \code{lambda}.
  15826. \end{enumerate}
  15827. {\if\edition\racketEd
  15828. %
  15829. To compute the variables that are assigned to, we recommend updating
  15830. the \code{collect-set!} function that we introduced in
  15831. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  15832. as \code{Lambda}.
  15833. %
  15834. \fi}
  15835. {\if\edition\pythonEd\pythonColor
  15836. %
  15837. To compute the variables that are assigned to, we recommend defining
  15838. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  15839. the set of variables that occur in the left-hand side of an assignment
  15840. statement, and otherwise returns the empty set.
  15841. %
  15842. \fi}
  15843. Let $\mathit{AF}$ be the intersection of the set of variables that are
  15844. free in a \code{lambda} and that are assigned to in the enclosing
  15845. function definition.
  15846. Next we discuss the \code{convert\_assignments} pass. In the case for
  15847. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  15848. $\VAR{x}$ to a tuple read.
  15849. %
  15850. {\if\edition\racketEd
  15851. \begin{lstlisting}
  15852. (Var |$x$|)
  15853. |$\Rightarrow$|
  15854. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  15855. \end{lstlisting}
  15856. \fi}
  15857. %
  15858. {\if\edition\pythonEd\pythonColor
  15859. \begin{lstlisting}
  15860. Name(|$x$|)
  15861. |$\Rightarrow$|
  15862. Subscript(Name(|$x$|), Constant(0), Load())
  15863. \end{lstlisting}
  15864. \fi}
  15865. %
  15866. \noindent In the case for assignment, recursively process the
  15867. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  15868. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  15869. as follows:
  15870. %
  15871. {\if\edition\racketEd
  15872. \begin{lstlisting}
  15873. (SetBang |$x$| |$\itm{rhs}$|)
  15874. |$\Rightarrow$|
  15875. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  15876. \end{lstlisting}
  15877. \fi}
  15878. {\if\edition\pythonEd\pythonColor
  15879. \begin{lstlisting}
  15880. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  15881. |$\Rightarrow$|
  15882. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  15883. \end{lstlisting}
  15884. \fi}
  15885. %
  15886. {\if\edition\racketEd
  15887. The case for \code{Lambda} is nontrivial, but it is similar to the
  15888. case for function definitions, which we discuss next.
  15889. \fi}
  15890. %
  15891. To translate a function definition, we first compute $\mathit{AF}$,
  15892. the intersection of the variables that are free in a \code{lambda} and
  15893. that are assigned to. We then apply assignment conversion to the body
  15894. of the function definition. Finally, we box the parameters of this
  15895. function definition that are in $\mathit{AF}$. For example,
  15896. the parameter \code{x} of the following function \code{g}
  15897. needs to be boxed:
  15898. {\if\edition\racketEd
  15899. \begin{lstlisting}
  15900. (define (g [x : Integer]) : Integer
  15901. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  15902. (begin
  15903. (set! x 10)
  15904. (f 32))))
  15905. \end{lstlisting}
  15906. \fi}
  15907. %
  15908. {\if\edition\pythonEd\pythonColor
  15909. \begin{lstlisting}
  15910. def g(x : int) -> int:
  15911. f : Callable[[int],int] = lambda a: a + x
  15912. x = 10
  15913. return f(32)
  15914. \end{lstlisting}
  15915. \fi}
  15916. %
  15917. \noindent We box parameter \code{x} by creating a local variable named
  15918. \code{x} that is initialized to a tuple whose contents is the value of
  15919. the parameter, which has been renamed to \code{x\_0}.
  15920. %
  15921. {\if\edition\racketEd
  15922. \begin{lstlisting}
  15923. (define (g [x_0 : Integer]) : Integer
  15924. (let ([x (vector x_0)])
  15925. (let ([f (lambda: ([a : Integer]) : Integer
  15926. (+ a (vector-ref x 0)))])
  15927. (begin
  15928. (vector-set! x 0 10)
  15929. (f 32)))))
  15930. \end{lstlisting}
  15931. \fi}
  15932. %
  15933. {\if\edition\pythonEd\pythonColor
  15934. \begin{lstlisting}
  15935. def g(x_0 : int)-> int:
  15936. x = (x_0,)
  15937. f : Callable[[int], int] = (lambda a: a + x[0])
  15938. x[0] = 10
  15939. return f(32)
  15940. \end{lstlisting}
  15941. \fi}
  15942. \section{Closure Conversion}
  15943. \label{sec:closure-conversion}
  15944. \index{subject}{closure conversion}
  15945. The compiling of lexically scoped functions into top-level function
  15946. definitions and flat closures is accomplished in the pass
  15947. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15948. and before \code{limit\_functions}.
  15949. As usual, we implement the pass as a recursive function over the
  15950. AST. The interesting cases are for \key{lambda} and function
  15951. application. We transform a \key{lambda} expression into an expression
  15952. that creates a closure, that is, a tuple for which the first element
  15953. is a function pointer and the rest of the elements are the values of
  15954. the free variables of the \key{lambda}.
  15955. %
  15956. However, we use the \code{Closure} AST node instead of using a tuple
  15957. so that we can record the arity.
  15958. %
  15959. In the generated code that follows, \itm{fvs} is the free variables of
  15960. the lambda and \itm{name} is a unique symbol generated to identify the
  15961. lambda.
  15962. %
  15963. \racket{The \itm{arity} is the number of parameters (the length of
  15964. \itm{ps}).}
  15965. %
  15966. {\if\edition\racketEd
  15967. \begin{lstlisting}
  15968. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15969. |$\Rightarrow$|
  15970. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15971. \end{lstlisting}
  15972. \fi}
  15973. %
  15974. {\if\edition\pythonEd\pythonColor
  15975. \begin{lstlisting}
  15976. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15977. |$\Rightarrow$|
  15978. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15979. \end{lstlisting}
  15980. \fi}
  15981. %
  15982. In addition to transforming each \key{Lambda} AST node into a
  15983. tuple, we create a top-level function definition for each
  15984. \key{Lambda}, as shown next.\\
  15985. \begin{minipage}{0.8\textwidth}
  15986. {\if\edition\racketEd
  15987. \begin{lstlisting}
  15988. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15989. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15990. ...
  15991. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15992. |\itm{body'}|)...))
  15993. \end{lstlisting}
  15994. \fi}
  15995. {\if\edition\pythonEd\pythonColor
  15996. \begin{lstlisting}
  15997. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15998. |$\itm{fvs}_1$| = clos[1]
  15999. |$\ldots$|
  16000. |$\itm{fvs}_n$| = clos[|$n$|]
  16001. |\itm{body'}|
  16002. \end{lstlisting}
  16003. \fi}
  16004. \end{minipage}\\
  16005. The \code{clos} parameter refers to the closure. Translate the type
  16006. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16007. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  16008. \itm{closTy} is a tuple type for which the first element type is
  16009. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  16010. the element types are the types of the free variables in the
  16011. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16012. is nontrivial to give a type to the function in the closure's type.%
  16013. %
  16014. \footnote{To give an accurate type to a closure, we would need to add
  16015. existential types to the type checker~\citep{Minamide:1996ys}.}
  16016. %
  16017. %% The dummy type is considered to be equal to any other type during type
  16018. %% checking.
  16019. The free variables become local variables that are initialized with
  16020. their values in the closure.
  16021. Closure conversion turns every function into a tuple, so the type
  16022. annotations in the program must also be translated. We recommend
  16023. defining an auxiliary recursive function for this purpose. Function
  16024. types should be translated as follows:
  16025. %
  16026. {\if\edition\racketEd
  16027. \begin{lstlisting}
  16028. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16029. |$\Rightarrow$|
  16030. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16031. \end{lstlisting}
  16032. \fi}
  16033. {\if\edition\pythonEd\pythonColor
  16034. \begin{lstlisting}
  16035. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16036. |$\Rightarrow$|
  16037. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16038. \end{lstlisting}
  16039. \fi}
  16040. %
  16041. This type indicates that the first thing in the tuple is a
  16042. function. The first parameter of the function is a tuple (a closure)
  16043. and the rest of the parameters are the ones from the original
  16044. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16045. omits the types of the free variables because (1) those types are not
  16046. available in this context, and (2) we do not need them in the code that
  16047. is generated for function application. So this type describes only the
  16048. first component of the closure tuple. At runtime the tuple may have
  16049. more components, but we ignore them at this point.
  16050. We transform function application into code that retrieves the
  16051. function from the closure and then calls the function, passing the
  16052. closure as the first argument. We place $e'$ in a temporary variable
  16053. to avoid code duplication.
  16054. \begin{center}
  16055. \begin{minipage}{\textwidth}
  16056. {\if\edition\racketEd
  16057. \begin{lstlisting}
  16058. (Apply |$e$| |$\itm{es}$|)
  16059. |$\Rightarrow$|
  16060. (Let |$\itm{tmp}$| |$e'$|
  16061. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16062. \end{lstlisting}
  16063. \fi}
  16064. %
  16065. {\if\edition\pythonEd\pythonColor
  16066. \begin{lstlisting}
  16067. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16068. |$\Rightarrow$|
  16069. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16070. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16071. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16072. \end{lstlisting}
  16073. \fi}
  16074. \end{minipage}
  16075. \end{center}
  16076. There is also the question of what to do with references to top-level
  16077. function definitions. To maintain a uniform translation of function
  16078. application, we turn function references into closures.
  16079. \begin{tabular}{lll}
  16080. \begin{minipage}{0.2\textwidth}
  16081. {\if\edition\racketEd
  16082. \begin{lstlisting}
  16083. (FunRef |$f$| |$n$|)
  16084. \end{lstlisting}
  16085. \fi}
  16086. {\if\edition\pythonEd\pythonColor
  16087. \begin{lstlisting}
  16088. FunRef(|$f$|, |$n$|)
  16089. \end{lstlisting}
  16090. \fi}
  16091. \end{minipage}
  16092. &
  16093. $\Rightarrow\qquad$
  16094. &
  16095. \begin{minipage}{0.5\textwidth}
  16096. {\if\edition\racketEd
  16097. \begin{lstlisting}
  16098. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16099. \end{lstlisting}
  16100. \fi}
  16101. {\if\edition\pythonEd\pythonColor
  16102. \begin{lstlisting}
  16103. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16104. \end{lstlisting}
  16105. \fi}
  16106. \end{minipage}
  16107. \end{tabular} \\
  16108. We no longer need the annotated assignment statement \code{AnnAssign}
  16109. to support the type checking of \code{lambda} expressions, so we
  16110. translate it to a regular \code{Assign} statement.
  16111. The top-level function definitions need to be updated to take an extra
  16112. closure parameter, but that parameter is ignored in the body of those
  16113. functions.
  16114. \section{An Example Translation}
  16115. \label{sec:example-lambda}
  16116. Figure~\ref{fig:lexical-functions-example} shows the result of
  16117. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16118. program demonstrating lexical scoping that we discussed at the
  16119. beginning of this chapter.
  16120. \begin{figure}[tbp]
  16121. \begin{tcolorbox}[colback=white]
  16122. \begin{minipage}{0.8\textwidth}
  16123. {\if\edition\racketEd
  16124. % tests/lambda_test_6.rkt
  16125. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16126. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16127. (let ([y8 4])
  16128. (lambda: ([z9 : Integer]) : Integer
  16129. (+ x7 (+ y8 z9)))))
  16130. (define (main) : Integer
  16131. (let ([g0 ((fun-ref f6 1) 5)])
  16132. (let ([h1 ((fun-ref f6 1) 3)])
  16133. (+ (g0 11) (h1 15)))))
  16134. \end{lstlisting}
  16135. $\Rightarrow$
  16136. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16137. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16138. (let ([y8 4])
  16139. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16140. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16141. (let ([x7 (vector-ref fvs3 1)])
  16142. (let ([y8 (vector-ref fvs3 2)])
  16143. (+ x7 (+ y8 z9)))))
  16144. (define (main) : Integer
  16145. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16146. ((vector-ref clos5 0) clos5 5))])
  16147. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16148. ((vector-ref clos6 0) clos6 3))])
  16149. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16150. \end{lstlisting}
  16151. \fi}
  16152. %
  16153. {\if\edition\pythonEd\pythonColor
  16154. % free_var.py
  16155. \begin{lstlisting}
  16156. def f(x : int) -> Callable[[int], int]:
  16157. y = 4
  16158. return lambda z: x + y + z
  16159. g = f(5)
  16160. h = f(3)
  16161. print( g(11) + h(15) )
  16162. \end{lstlisting}
  16163. $\Rightarrow$
  16164. \begin{lstlisting}
  16165. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  16166. x = fvs_1[1]
  16167. y = fvs_1[2]
  16168. return x + y[0] + z
  16169. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  16170. y = (777,)
  16171. y[0] = 4
  16172. return (lambda_0, x, y)
  16173. def main() -> int:
  16174. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  16175. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  16176. print((let clos_5 = g in clos_5[0](clos_5, 11))
  16177. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  16178. return 0
  16179. \end{lstlisting}
  16180. \fi}
  16181. \end{minipage}
  16182. \end{tcolorbox}
  16183. \caption{Example of closure conversion.}
  16184. \label{fig:lexical-functions-example}
  16185. \end{figure}
  16186. \begin{exercise}\normalfont\normalsize
  16187. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16188. Create five new programs that use \key{lambda} functions and make use of
  16189. lexical scoping. Test your compiler on these new programs and all
  16190. your previously created test programs.
  16191. \end{exercise}
  16192. \section{Expose Allocation}
  16193. \label{sec:expose-allocation-r5}
  16194. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16195. that allocates and initializes a tuple, similar to the translation of
  16196. the tuple creation in section~\ref{sec:expose-allocation}.
  16197. The only difference is replacing the use of
  16198. \ALLOC{\itm{len}}{\itm{type}} with
  16199. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16200. \section{Explicate Control and \LangCLam{}}
  16201. \label{sec:explicate-r5}
  16202. The output language of \code{explicate\_control} is \LangCLam{}; the
  16203. definition of its abstract syntax is shown in
  16204. figure~\ref{fig:Clam-syntax}.
  16205. %
  16206. \racket{The only differences with respect to \LangCFun{} are the
  16207. addition of the \code{AllocateClosure} form to the grammar for
  16208. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16209. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16210. similar to the handling of other expressions such as primitive
  16211. operators.}
  16212. %
  16213. \python{The differences with respect to \LangCFun{} are the
  16214. additions of \code{Uninitialized}, \code{AllocateClosure},
  16215. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16216. \code{explicate\_control} pass is similar to the handling of other
  16217. expressions such as primitive operators.}
  16218. \newcommand{\ClambdaASTRacket}{
  16219. \begin{array}{lcl}
  16220. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16221. \itm{op} &::= & \code{procedure-arity}
  16222. \end{array}
  16223. }
  16224. \newcommand{\ClambdaASTPython}{
  16225. \begin{array}{lcl}
  16226. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16227. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16228. &\MID& \ARITY{\Atm}
  16229. \end{array}
  16230. }
  16231. \begin{figure}[tp]
  16232. \begin{tcolorbox}[colback=white]
  16233. \small
  16234. {\if\edition\racketEd
  16235. \[
  16236. \begin{array}{l}
  16237. \gray{\CvarASTRacket} \\ \hline
  16238. \gray{\CifASTRacket} \\ \hline
  16239. \gray{\CloopASTRacket} \\ \hline
  16240. \gray{\CtupASTRacket} \\ \hline
  16241. \gray{\CfunASTRacket} \\ \hline
  16242. \ClambdaASTRacket \\
  16243. \begin{array}{lcl}
  16244. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16245. \end{array}
  16246. \end{array}
  16247. \]
  16248. \fi}
  16249. {\if\edition\pythonEd\pythonColor
  16250. \[
  16251. \begin{array}{l}
  16252. \gray{\CifASTPython} \\ \hline
  16253. \gray{\CtupASTPython} \\ \hline
  16254. \gray{\CfunASTPython} \\ \hline
  16255. \ClambdaASTPython \\
  16256. \begin{array}{lcl}
  16257. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16258. \end{array}
  16259. \end{array}
  16260. \]
  16261. \fi}
  16262. \end{tcolorbox}
  16263. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16264. \label{fig:Clam-syntax}
  16265. \end{figure}
  16266. \section{Select Instructions}
  16267. \label{sec:select-instructions-Llambda}
  16268. \index{subject}{select instructions}
  16269. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16270. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16271. (section~\ref{sec:select-instructions-gc}). The only difference is
  16272. that you should place the \itm{arity} in the tag that is stored at
  16273. position $0$ of the vector. Recall that in
  16274. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16275. was not used. We store the arity in the $5$ bits starting at position
  16276. $58$.
  16277. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16278. instructions that access the tag from position $0$ of the vector and
  16279. extract the $5$ bits starting at position $58$ from the tag.}
  16280. %
  16281. \python{Compile a call to the \code{arity} operator to a sequence of
  16282. instructions that access the tag from position $0$ of the tuple
  16283. (representing a closure) and extract the $5$-bits starting at position
  16284. $58$ from the tag.}
  16285. \begin{figure}[p]
  16286. \begin{tcolorbox}[colback=white]
  16287. {\if\edition\racketEd
  16288. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16289. \node (Lfun) at (0,2) {\large \LangLam{}};
  16290. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16291. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16292. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16293. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16294. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16295. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16296. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16297. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16298. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16299. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16300. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16301. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16302. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16303. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16304. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16305. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16306. \path[->,bend left=15] (Lfun) edge [above] node
  16307. {\ttfamily\footnotesize shrink} (Lfun-2);
  16308. \path[->,bend left=15] (Lfun-2) edge [above] node
  16309. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16310. \path[->,bend left=15] (Lfun-3) edge [above] node
  16311. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16312. \path[->,bend left=15] (F1-0) edge [left] node
  16313. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16314. \path[->,bend left=15] (F1-1) edge [below] node
  16315. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16316. \path[->,bend right=15] (F1-2) edge [above] node
  16317. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16318. \path[->,bend right=15] (F1-3) edge [above] node
  16319. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16320. \path[->,bend left=15] (F1-4) edge [right] node
  16321. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16322. \path[->,bend right=15] (F1-5) edge [below] node
  16323. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16324. \path[->,bend left=15] (F1-6) edge [above] node
  16325. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16326. \path[->] (C3-2) edge [right] node
  16327. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16328. \path[->,bend right=15] (x86-2) edge [right] node
  16329. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16330. \path[->,bend right=15] (x86-2-1) edge [below] node
  16331. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16332. \path[->,bend right=15] (x86-2-2) edge [right] node
  16333. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16334. \path[->,bend left=15] (x86-3) edge [above] node
  16335. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16336. \path[->,bend left=15] (x86-4) edge [right] node
  16337. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16338. \end{tikzpicture}
  16339. \fi}
  16340. {\if\edition\pythonEd\pythonColor
  16341. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16342. \node (Lfun) at (0,2) {\large \LangLam{}};
  16343. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16344. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16345. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16346. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16347. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16348. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16349. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16350. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16351. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16352. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16353. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16354. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16355. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16356. \path[->,bend left=15] (Lfun) edge [above] node
  16357. {\ttfamily\footnotesize shrink} (Lfun-2);
  16358. \path[->,bend left=15] (Lfun-2) edge [above] node
  16359. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16360. \path[->,bend left=15] (Lfun-3) edge [above] node
  16361. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16362. \path[->,bend left=15] (F1-0) edge [left] node
  16363. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16364. \path[->,bend left=15] (F1-1) edge [below] node
  16365. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16366. \path[->,bend left=15] (F1-2) edge [below] node
  16367. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16368. \path[->,bend right=15] (F1-3) edge [above] node
  16369. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16370. \path[->,bend right=15] (F1-5) edge [right] node
  16371. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16372. \path[->,bend left=15] (F1-6) edge [right] node
  16373. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16374. \path[->,bend right=15] (C3-2) edge [right] node
  16375. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16376. \path[->,bend right=15] (x86-2) edge [below] node
  16377. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16378. \path[->,bend right=15] (x86-3) edge [below] node
  16379. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16380. \path[->,bend left=15] (x86-4) edge [above] node
  16381. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16382. \end{tikzpicture}
  16383. \fi}
  16384. \end{tcolorbox}
  16385. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16386. functions.}
  16387. \label{fig:Llambda-passes}
  16388. \end{figure}
  16389. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16390. needed for the compilation of \LangLam{}.
  16391. \clearpage
  16392. \section{Challenge: Optimize Closures}
  16393. \label{sec:optimize-closures}
  16394. In this chapter we compile lexically scoped functions into a
  16395. relatively efficient representation: flat closures. However, even this
  16396. representation comes with some overhead. For example, consider the
  16397. following program with a function \code{tail\_sum} that does not have
  16398. any free variables and where all the uses of \code{tail\_sum} are in
  16399. applications in which we know that only \code{tail\_sum} is being applied
  16400. (and not any other functions):
  16401. \begin{center}
  16402. \begin{minipage}{0.95\textwidth}
  16403. {\if\edition\racketEd
  16404. \begin{lstlisting}
  16405. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16406. (if (eq? n 0)
  16407. s
  16408. (tail_sum (- n 1) (+ n s))))
  16409. (+ (tail_sum 3 0) 36)
  16410. \end{lstlisting}
  16411. \fi}
  16412. {\if\edition\pythonEd\pythonColor
  16413. \begin{lstlisting}
  16414. def tail_sum(n : int, s : int) -> int:
  16415. if n == 0:
  16416. return s
  16417. else:
  16418. return tail_sum(n - 1, n + s)
  16419. print( tail_sum(3, 0) + 36)
  16420. \end{lstlisting}
  16421. \fi}
  16422. \end{minipage}
  16423. \end{center}
  16424. As described in this chapter, we uniformly apply closure conversion to
  16425. all functions, obtaining the following output for this program:
  16426. \begin{center}
  16427. \begin{minipage}{0.95\textwidth}
  16428. {\if\edition\racketEd
  16429. \begin{lstlisting}
  16430. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16431. (if (eq? n2 0)
  16432. s3
  16433. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16434. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16435. (define (main) : Integer
  16436. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16437. ((vector-ref clos6 0) clos6 3 0)) 27))
  16438. \end{lstlisting}
  16439. \fi}
  16440. {\if\edition\pythonEd\pythonColor
  16441. \begin{lstlisting}
  16442. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16443. if n_0 == 0:
  16444. return s_1
  16445. else:
  16446. return (let clos_2 = (tail_sum,)
  16447. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16448. def main() -> int :
  16449. print((let clos_4 = (tail_sum,)
  16450. in clos_4[0](clos_4, 3, 0)) + 36)
  16451. return 0
  16452. \end{lstlisting}
  16453. \fi}
  16454. \end{minipage}
  16455. \end{center}
  16456. If this program were compiled according to the previous chapter, there
  16457. would be no allocation and the calls to \code{tail\_sum} would be
  16458. direct calls. In contrast, the program presented here allocates memory
  16459. for each closure and the calls to \code{tail\_sum} are indirect. These
  16460. two differences incur considerable overhead in a program such as this,
  16461. in which the allocations and indirect calls occur inside a tight loop.
  16462. One might think that this problem is trivial to solve: can't we just
  16463. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16464. and compile them to direct calls instead of treating it like a call to
  16465. a closure? We would also drop the new \code{fvs} parameter of
  16466. \code{tail\_sum}.
  16467. %
  16468. However, this problem is not so trivial, because a global function may
  16469. \emph{escape} and become involved in applications that also involve
  16470. closures. Consider the following example in which the application
  16471. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16472. application because the \code{lambda} may flow into \code{f}, but the
  16473. \code{inc} function might also flow into \code{f}:
  16474. \begin{center}
  16475. \begin{minipage}{\textwidth}
  16476. % lambda_test_30.rkt
  16477. {\if\edition\racketEd
  16478. \begin{lstlisting}
  16479. (define (inc [x : Integer]) : Integer
  16480. (+ x 1))
  16481. (let ([y (read)])
  16482. (let ([f (if (eq? (read) 0)
  16483. inc
  16484. (lambda: ([x : Integer]) : Integer (- x y)))])
  16485. (f 41)))
  16486. \end{lstlisting}
  16487. \fi}
  16488. {\if\edition\pythonEd\pythonColor
  16489. \begin{lstlisting}
  16490. def add1(x : int) -> int:
  16491. return x + 1
  16492. y = input_int()
  16493. g : Callable[[int], int] = lambda x: x - y
  16494. f = add1 if input_int() == 0 else g
  16495. print( f(41) )
  16496. \end{lstlisting}
  16497. \fi}
  16498. \end{minipage}
  16499. \end{center}
  16500. If a global function name is used in any way other than as the
  16501. operator in a direct call, then we say that the function
  16502. \emph{escapes}. If a global function does not escape, then we do not
  16503. need to perform closure conversion on the function.
  16504. \begin{exercise}\normalfont\normalsize
  16505. Implement an auxiliary function for detecting which global
  16506. functions escape. Using that function, implement an improved version
  16507. of closure conversion that does not apply closure conversion to
  16508. global functions that do not escape but instead compiles them as
  16509. regular functions. Create several new test cases that check whether
  16510. your compiler properly detects whether global functions escape or not.
  16511. \end{exercise}
  16512. So far we have reduced the overhead of calling global functions, but
  16513. it would also be nice to reduce the overhead of calling a
  16514. \code{lambda} when we can determine at compile time which
  16515. \code{lambda} will be called. We refer to such calls as \emph{known
  16516. calls}. Consider the following example in which a \code{lambda} is
  16517. bound to \code{f} and then applied.
  16518. {\if\edition\racketEd
  16519. % lambda_test_9.rkt
  16520. \begin{lstlisting}
  16521. (let ([y (read)])
  16522. (let ([f (lambda: ([x : Integer]) : Integer
  16523. (+ x y))])
  16524. (f 21)))
  16525. \end{lstlisting}
  16526. \fi}
  16527. {\if\edition\pythonEd\pythonColor
  16528. \begin{lstlisting}
  16529. y = input_int()
  16530. f : Callable[[int],int] = lambda x: x + y
  16531. print( f(21) )
  16532. \end{lstlisting}
  16533. \fi}
  16534. %
  16535. \noindent Closure conversion compiles the application
  16536. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16537. %
  16538. {\if\edition\racketEd
  16539. \begin{lstlisting}
  16540. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16541. (let ([y2 (vector-ref fvs6 1)])
  16542. (+ x3 y2)))
  16543. (define (main) : Integer
  16544. (let ([y2 (read)])
  16545. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16546. ((vector-ref f4 0) f4 21))))
  16547. \end{lstlisting}
  16548. \fi}
  16549. {\if\edition\pythonEd\pythonColor
  16550. \begin{lstlisting}
  16551. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16552. y_1 = fvs_4[1]
  16553. return x_2 + y_1[0]
  16554. def main() -> int:
  16555. y_1 = (777,)
  16556. y_1[0] = input_int()
  16557. f_0 = (lambda_3, y_1)
  16558. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16559. return 0
  16560. \end{lstlisting}
  16561. \fi}
  16562. %
  16563. \noindent However, we can instead compile the application
  16564. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16565. %
  16566. {\if\edition\racketEd
  16567. \begin{lstlisting}
  16568. (define (main) : Integer
  16569. (let ([y2 (read)])
  16570. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16571. ((fun-ref lambda5 1) f4 21))))
  16572. \end{lstlisting}
  16573. \fi}
  16574. {\if\edition\pythonEd\pythonColor
  16575. \begin{lstlisting}
  16576. def main() -> int:
  16577. y_1 = (777,)
  16578. y_1[0] = input_int()
  16579. f_0 = (lambda_3, y_1)
  16580. print(lambda_3(f_0, 21))
  16581. return 0
  16582. \end{lstlisting}
  16583. \fi}
  16584. The problem of determining which \code{lambda} will be called from a
  16585. particular application is quite challenging in general and the topic
  16586. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16587. following exercise we recommend that you compile an application to a
  16588. direct call when the operator is a variable and \racket{the variable
  16589. is \code{let}-bound to a closure}\python{the previous assignment to
  16590. the variable is a closure}. This can be accomplished by maintaining
  16591. an environment that maps variables to function names. Extend the
  16592. environment whenever you encounter a closure on the right-hand side of
  16593. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  16594. name of the global function for the closure. This pass should come
  16595. after closure conversion.
  16596. \begin{exercise}\normalfont\normalsize
  16597. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16598. compiles known calls into direct calls. Verify that your compiler is
  16599. successful in this regard on several example programs.
  16600. \end{exercise}
  16601. These exercises only scratch the surface of closure optimization. A
  16602. good next step for the interested reader is to look at the work of
  16603. \citet{Keep:2012ab}.
  16604. \section{Further Reading}
  16605. The notion of lexically scoped functions predates modern computers by
  16606. about a decade. They were invented by \citet{Church:1932aa}, who
  16607. proposed the lambda calculus as a foundation for logic. Anonymous
  16608. functions were included in the LISP~\citep{McCarthy:1960dz}
  16609. programming language but were initially dynamically scoped. The Scheme
  16610. dialect of LISP adopted lexical scoping, and
  16611. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16612. Scheme programs. However, environments were represented as linked
  16613. lists, so variable look-up was linear in the size of the
  16614. environment. \citet{Appel91} gives a detailed description of several
  16615. closure representations. In this chapter we represent environments
  16616. using flat closures, which were invented by
  16617. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16618. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16619. closures, variable look-up is constant time but the time to create a
  16620. closure is proportional to the number of its free variables. Flat
  16621. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16622. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16623. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16624. % compilers)
  16625. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16626. \chapter{Dynamic Typing}
  16627. \label{ch:Ldyn}
  16628. \index{subject}{dynamic typing}
  16629. \setcounter{footnote}{0}
  16630. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16631. typed language that is a subset of \racket{Racket}\python{Python}. The
  16632. focus on dynamic typing is in contrast to the previous chapters, which
  16633. have studied the compilation of statically typed languages. In
  16634. dynamically typed languages such as \LangDyn{}, a particular
  16635. expression may produce a value of a different type each time it is
  16636. executed. Consider the following example with a conditional \code{if}
  16637. expression that may return a Boolean or an integer depending on the
  16638. input to the program:
  16639. % part of dynamic_test_25.rkt
  16640. {\if\edition\racketEd
  16641. \begin{lstlisting}
  16642. (not (if (eq? (read) 1) #f 0))
  16643. \end{lstlisting}
  16644. \fi}
  16645. {\if\edition\pythonEd\pythonColor
  16646. \begin{lstlisting}
  16647. not (False if input_int() == 1 else 0)
  16648. \end{lstlisting}
  16649. \fi}
  16650. Languages that allow expressions to produce different kinds of values
  16651. are called \emph{polymorphic}, a word composed of the Greek roots
  16652. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16653. There are several kinds of polymorphism in programming languages, such as
  16654. subtype polymorphism\index{subject}{subtype polymorphism} and
  16655. parametric polymorphism\index{subject}{parametric polymorphism}
  16656. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16657. study in this chapter does not have a special name; it is the kind
  16658. that arises in dynamically typed languages.
  16659. Another characteristic of dynamically typed languages is that
  16660. their primitive operations, such as \code{not}, are often defined to operate
  16661. on many different types of values. In fact, in
  16662. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16663. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16664. given anything else it returns \FALSE{}.
  16665. Furthermore, even when primitive operations restrict their inputs to
  16666. values of a certain type, this restriction is enforced at runtime
  16667. instead of during compilation. For example, the tuple read
  16668. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16669. results in a runtime error because the first argument must
  16670. be a tuple, not a Boolean.
  16671. \section{The \LangDyn{} Language}
  16672. \newcommand{\LdynGrammarRacket}{
  16673. \begin{array}{rcl}
  16674. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16675. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16676. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16677. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16678. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16679. \end{array}
  16680. }
  16681. \newcommand{\LdynASTRacket}{
  16682. \begin{array}{lcl}
  16683. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16684. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16685. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16686. \end{array}
  16687. }
  16688. \begin{figure}[tp]
  16689. \centering
  16690. \begin{tcolorbox}[colback=white]
  16691. \small
  16692. {\if\edition\racketEd
  16693. \[
  16694. \begin{array}{l}
  16695. \gray{\LintGrammarRacket{}} \\ \hline
  16696. \gray{\LvarGrammarRacket{}} \\ \hline
  16697. \gray{\LifGrammarRacket{}} \\ \hline
  16698. \gray{\LwhileGrammarRacket} \\ \hline
  16699. \gray{\LtupGrammarRacket} \\ \hline
  16700. \LdynGrammarRacket \\
  16701. \begin{array}{rcl}
  16702. \LangDynM{} &::=& \Def\ldots\; \Exp
  16703. \end{array}
  16704. \end{array}
  16705. \]
  16706. \fi}
  16707. {\if\edition\pythonEd\pythonColor
  16708. \[
  16709. \begin{array}{rcl}
  16710. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16711. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16712. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16713. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16714. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16715. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16716. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16717. \MID \CLEN{\Exp} \\
  16718. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16719. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16720. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16721. \MID \Var\mathop{\key{=}}\Exp \\
  16722. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16723. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16724. &\MID& \CRETURN{\Exp} \\
  16725. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16726. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16727. \end{array}
  16728. \]
  16729. \fi}
  16730. \end{tcolorbox}
  16731. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16732. \label{fig:r7-concrete-syntax}
  16733. \end{figure}
  16734. \begin{figure}[tp]
  16735. \centering
  16736. \begin{tcolorbox}[colback=white]
  16737. \small
  16738. {\if\edition\racketEd
  16739. \[
  16740. \begin{array}{l}
  16741. \gray{\LintASTRacket{}} \\ \hline
  16742. \gray{\LvarASTRacket{}} \\ \hline
  16743. \gray{\LifASTRacket{}} \\ \hline
  16744. \gray{\LwhileASTRacket} \\ \hline
  16745. \gray{\LtupASTRacket} \\ \hline
  16746. \LdynASTRacket \\
  16747. \begin{array}{lcl}
  16748. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16749. \end{array}
  16750. \end{array}
  16751. \]
  16752. \fi}
  16753. {\if\edition\pythonEd\pythonColor
  16754. \[
  16755. \begin{array}{rcl}
  16756. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16757. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16758. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16759. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16760. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16761. &\MID & \code{Is()} \\
  16762. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16763. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16764. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  16765. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  16766. \MID \VAR{\Var{}} \\
  16767. &\MID& \BOOL{\itm{bool}}
  16768. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  16769. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  16770. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  16771. &\MID& \LEN{\Exp} \\
  16772. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  16773. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  16774. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  16775. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  16776. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  16777. &\MID& \RETURN{\Exp} \\
  16778. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  16779. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  16780. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16781. \end{array}
  16782. \]
  16783. \fi}
  16784. \end{tcolorbox}
  16785. \caption{The abstract syntax of \LangDyn{}.}
  16786. \label{fig:r7-syntax}
  16787. \end{figure}
  16788. The definitions of the concrete and abstract syntax of \LangDyn{} are
  16789. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  16790. %
  16791. There is no type checker for \LangDyn{} because it checks types only
  16792. at runtime.
  16793. The definitional interpreter for \LangDyn{} is presented in
  16794. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  16795. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  16796. \INT{n}. Instead of simply returning the integer \code{n} (as
  16797. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  16798. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  16799. value} that combines an underlying value with a tag that identifies
  16800. what kind of value it is. We define the following \racket{struct}\python{class}
  16801. to represent tagged values:
  16802. %
  16803. {\if\edition\racketEd
  16804. \begin{lstlisting}
  16805. (struct Tagged (value tag) #:transparent)
  16806. \end{lstlisting}
  16807. \fi}
  16808. {\if\edition\pythonEd\pythonColor
  16809. \begin{minipage}{\textwidth}
  16810. \begin{lstlisting}
  16811. @dataclass(eq=True)
  16812. class Tagged(Value):
  16813. value : Value
  16814. tag : str
  16815. def __str__(self):
  16816. return str(self.value)
  16817. \end{lstlisting}
  16818. \end{minipage}
  16819. \fi}
  16820. %
  16821. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  16822. \code{Vector}, and \code{Procedure}.}
  16823. %
  16824. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  16825. \code{'tuple'}, and \code{'function'}.}
  16826. %
  16827. Tags are closely related to types but do not always capture all the
  16828. information that a type does.
  16829. %
  16830. \racket{For example, a vector of type \code{(Vector Any Any)} is
  16831. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  16832. Any)} is tagged with \code{Procedure}.}
  16833. %
  16834. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  16835. is tagged with \code{'tuple'} and a function of type
  16836. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  16837. is tagged with \code{'function'}.}
  16838. Next consider the match case for accessing the element of a tuple.
  16839. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  16840. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  16841. argument is a tuple and the second is an integer.
  16842. \racket{
  16843. If they are not, a \code{trapped-error} is raised. Recall from
  16844. section~\ref{sec:interp_Lint} that when a definition interpreter
  16845. raises a \code{trapped-error} error, the compiled code must also
  16846. signal an error by exiting with return code \code{255}. A
  16847. \code{trapped-error} is also raised if the index is not less than the
  16848. length of the vector.
  16849. }
  16850. %
  16851. \python{If they are not, an exception is raised. The compiled code
  16852. must also signal an error by exiting with return code \code{255}. A
  16853. exception is also raised if the index is not less than the length of the
  16854. tuple or if it is negative.}
  16855. \begin{figure}[tbp]
  16856. \begin{tcolorbox}[colback=white]
  16857. {\if\edition\racketEd
  16858. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16859. (define ((interp-Ldyn-exp env) ast)
  16860. (define recur (interp-Ldyn-exp env))
  16861. (match ast
  16862. [(Var x) (dict-ref env x)]
  16863. [(Int n) (Tagged n 'Integer)]
  16864. [(Bool b) (Tagged b 'Boolean)]
  16865. [(Lambda xs rt body)
  16866. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  16867. [(Prim 'vector es)
  16868. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  16869. [(Prim 'vector-ref (list e1 e2))
  16870. (define vec (recur e1)) (define i (recur e2))
  16871. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16872. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16873. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16874. (vector-ref (Tagged-value vec) (Tagged-value i))]
  16875. [(Prim 'vector-set! (list e1 e2 e3))
  16876. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  16877. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16878. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16879. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16880. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  16881. (Tagged (void) 'Void)]
  16882. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  16883. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  16884. [(Prim 'or (list e1 e2))
  16885. (define v1 (recur e1))
  16886. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  16887. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  16888. [(Prim op (list e1))
  16889. #:when (set-member? type-predicates op)
  16890. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  16891. [(Prim op es)
  16892. (define args (map recur es))
  16893. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  16894. (unless (for/or ([expected-tags (op-tags op)])
  16895. (equal? expected-tags tags))
  16896. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  16897. (tag-value
  16898. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  16899. [(If q t f)
  16900. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  16901. [(Apply f es)
  16902. (define new-f (recur f)) (define args (map recur es))
  16903. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  16904. (match f-val
  16905. [`(function ,xs ,body ,lam-env)
  16906. (unless (eq? (length xs) (length args))
  16907. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  16908. (define new-env (append (map cons xs args) lam-env))
  16909. ((interp-Ldyn-exp new-env) body)]
  16910. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  16911. \end{lstlisting}
  16912. \fi}
  16913. {\if\edition\pythonEd\pythonColor
  16914. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16915. class InterpLdyn(InterpLlambda):
  16916. def interp_exp(self, e, env):
  16917. match e:
  16918. case Constant(n):
  16919. return self.tag(super().interp_exp(e, env))
  16920. case Tuple(es, Load()):
  16921. return self.tag(super().interp_exp(e, env))
  16922. case Lambda(params, body):
  16923. return self.tag(super().interp_exp(e, env))
  16924. case Call(Name('input_int'), []):
  16925. return self.tag(super().interp_exp(e, env))
  16926. case BinOp(left, Add(), right):
  16927. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16928. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16929. case BinOp(left, Sub(), right):
  16930. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16931. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16932. case UnaryOp(USub(), e1):
  16933. v = self.interp_exp(e1, env)
  16934. return self.tag(- self.untag(v, 'int', e))
  16935. case IfExp(test, body, orelse):
  16936. v = self.interp_exp(test, env)
  16937. if self.untag(v, 'bool', e):
  16938. return self.interp_exp(body, env)
  16939. else:
  16940. return self.interp_exp(orelse, env)
  16941. case UnaryOp(Not(), e1):
  16942. v = self.interp_exp(e1, env)
  16943. return self.tag(not self.untag(v, 'bool', e))
  16944. case BoolOp(And(), values):
  16945. left = values[0]; right = values[1]
  16946. l = self.interp_exp(left, env)
  16947. if self.untag(l, 'bool', e):
  16948. return self.interp_exp(right, env)
  16949. else:
  16950. return self.tag(False)
  16951. case BoolOp(Or(), values):
  16952. left = values[0]; right = values[1]
  16953. l = self.interp_exp(left, env)
  16954. if self.untag(l, 'bool', e):
  16955. return self.tag(True)
  16956. else:
  16957. return self.interp_exp(right, env)
  16958. case Compare(left, [cmp], [right]):
  16959. l = self.interp_exp(left, env)
  16960. r = self.interp_exp(right, env)
  16961. if l.tag == r.tag:
  16962. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16963. else:
  16964. raise Exception('interp Compare unexpected '
  16965. + repr(l) + ' ' + repr(r))
  16966. case Subscript(tup, index, Load()):
  16967. t = self.interp_exp(tup, env)
  16968. n = self.interp_exp(index, env)
  16969. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16970. case Call(Name('len'), [tup]):
  16971. t = self.interp_exp(tup, env)
  16972. return self.tag(len(self.untag(t, 'tuple', e)))
  16973. case _:
  16974. return self.tag(super().interp_exp(e, env))
  16975. \end{lstlisting}
  16976. \fi}
  16977. \end{tcolorbox}
  16978. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16979. \label{fig:interp-Ldyn}
  16980. \end{figure}
  16981. {\if\edition\pythonEd\pythonColor
  16982. \begin{figure}[tbp]
  16983. \begin{tcolorbox}[colback=white]
  16984. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16985. class InterpLdyn(InterpLlambda):
  16986. def interp_stmt(self, s, env, cont):
  16987. match s:
  16988. case If(test, body, orelse):
  16989. v = self.interp_exp(test, env)
  16990. match self.untag(v, 'bool', s):
  16991. case True:
  16992. return self.interp_stmts(body + cont, env)
  16993. case False:
  16994. return self.interp_stmts(orelse + cont, env)
  16995. case While(test, body, []):
  16996. v = self.interp_exp(test, env)
  16997. if self.untag(v, 'bool', test):
  16998. self.interp_stmts(body + [s] + cont, env)
  16999. else:
  17000. return self.interp_stmts(cont, env)
  17001. case Assign([Subscript(tup, index)], value):
  17002. tup = self.interp_exp(tup, env)
  17003. index = self.interp_exp(index, env)
  17004. tup_v = self.untag(tup, 'tuple', s)
  17005. index_v = self.untag(index, 'int', s)
  17006. tup_v[index_v] = self.interp_exp(value, env)
  17007. return self.interp_stmts(cont, env)
  17008. case FunctionDef(name, params, bod, dl, returns, comment):
  17009. if isinstance(params, ast.arguments):
  17010. ps = [p.arg for p in params.args]
  17011. else:
  17012. ps = [x for (x,t) in params]
  17013. env[name] = self.tag(Function(name, ps, bod, env))
  17014. return self.interp_stmts(cont, env)
  17015. case _:
  17016. return super().interp_stmt(s, env, cont)
  17017. \end{lstlisting}
  17018. \end{tcolorbox}
  17019. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17020. \label{fig:interp-Ldyn-2}
  17021. \end{figure}
  17022. \fi}
  17023. \begin{figure}[tbp]
  17024. \begin{tcolorbox}[colback=white]
  17025. {\if\edition\racketEd
  17026. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17027. (define (interp-op op)
  17028. (match op
  17029. ['+ fx+]
  17030. ['- fx-]
  17031. ['read read-fixnum]
  17032. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17033. ['< (lambda (v1 v2)
  17034. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17035. ['<= (lambda (v1 v2)
  17036. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17037. ['> (lambda (v1 v2)
  17038. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17039. ['>= (lambda (v1 v2)
  17040. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17041. ['boolean? boolean?]
  17042. ['integer? fixnum?]
  17043. ['void? void?]
  17044. ['vector? vector?]
  17045. ['vector-length vector-length]
  17046. ['procedure? (match-lambda
  17047. [`(functions ,xs ,body ,env) #t] [else #f])]
  17048. [else (error 'interp-op "unknown operator" op)]))
  17049. (define (op-tags op)
  17050. (match op
  17051. ['+ '((Integer Integer))]
  17052. ['- '((Integer Integer) (Integer))]
  17053. ['read '(())]
  17054. ['not '((Boolean))]
  17055. ['< '((Integer Integer))]
  17056. ['<= '((Integer Integer))]
  17057. ['> '((Integer Integer))]
  17058. ['>= '((Integer Integer))]
  17059. ['vector-length '((Vector))]))
  17060. (define type-predicates
  17061. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17062. (define (tag-value v)
  17063. (cond [(boolean? v) (Tagged v 'Boolean)]
  17064. [(fixnum? v) (Tagged v 'Integer)]
  17065. [(procedure? v) (Tagged v 'Procedure)]
  17066. [(vector? v) (Tagged v 'Vector)]
  17067. [(void? v) (Tagged v 'Void)]
  17068. [else (error 'tag-value "unidentified value ~a" v)]))
  17069. (define (check-tag val expected ast)
  17070. (define tag (Tagged-tag val))
  17071. (unless (eq? tag expected)
  17072. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17073. \end{lstlisting}
  17074. \fi}
  17075. {\if\edition\pythonEd\pythonColor
  17076. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17077. class InterpLdyn(InterpLlambda):
  17078. def tag(self, v):
  17079. if v is True or v is False:
  17080. return Tagged(v, 'bool')
  17081. elif isinstance(v, int):
  17082. return Tagged(v, 'int')
  17083. elif isinstance(v, Function):
  17084. return Tagged(v, 'function')
  17085. elif isinstance(v, tuple):
  17086. return Tagged(v, 'tuple')
  17087. elif isinstance(v, type(None)):
  17088. return Tagged(v, 'none')
  17089. else:
  17090. raise Exception('tag: unexpected ' + repr(v))
  17091. def untag(self, v, expected_tag, ast):
  17092. match v:
  17093. case Tagged(val, tag) if tag == expected_tag:
  17094. return val
  17095. case _:
  17096. raise TrappedError('expected Tagged value with '
  17097. + expected_tag + ', not ' + ' ' + repr(v))
  17098. def apply_fun(self, fun, args, e):
  17099. f = self.untag(fun, 'function', e)
  17100. return super().apply_fun(f, args, e)
  17101. \end{lstlisting}
  17102. \fi}
  17103. \end{tcolorbox}
  17104. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17105. \label{fig:interp-Ldyn-aux}
  17106. \end{figure}
  17107. \clearpage
  17108. \section{Representation of Tagged Values}
  17109. The interpreter for \LangDyn{} introduced a new kind of value: the
  17110. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17111. represent tagged values at the bit level. Because almost every
  17112. operation in \LangDyn{} involves manipulating tagged values, the
  17113. representation must be efficient. Recall that all our values are 64
  17114. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17115. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17116. $011$ for procedures, and $101$ for the void value\python{,
  17117. \key{None}}. We define the following auxiliary function for mapping
  17118. types to tag codes:
  17119. %
  17120. {\if\edition\racketEd
  17121. \begin{align*}
  17122. \itm{tagof}(\key{Integer}) &= 001 \\
  17123. \itm{tagof}(\key{Boolean}) &= 100 \\
  17124. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17125. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17126. \itm{tagof}(\key{Void}) &= 101
  17127. \end{align*}
  17128. \fi}
  17129. {\if\edition\pythonEd\pythonColor
  17130. \begin{align*}
  17131. \itm{tagof}(\key{IntType()}) &= 001 \\
  17132. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17133. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17134. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17135. \itm{tagof}(\key{type(None)}) &= 101
  17136. \end{align*}
  17137. \fi}
  17138. %
  17139. This stealing of 3 bits comes at some price: integers are now restricted
  17140. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17141. affect tuples and procedures because those values are addresses, and
  17142. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17143. they are always $000$. Thus, we do not lose information by overwriting
  17144. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17145. to recover the original address.
  17146. To make tagged values into first-class entities, we can give them a
  17147. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  17148. operations such as \code{Inject} and \code{Project} for creating and
  17149. using them, yielding the statically typed \LangAny{} intermediate
  17150. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17151. section~\ref{sec:compile-r7}; in the next section we describe the
  17152. \LangAny{} language in greater detail.
  17153. \section{The \LangAny{} Language}
  17154. \label{sec:Rany-lang}
  17155. \newcommand{\LanyASTRacket}{
  17156. \begin{array}{lcl}
  17157. \Type &::= & \ANYTY \\
  17158. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17159. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17160. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17161. \itm{op} &::= & \code{any-vector-length}
  17162. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17163. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17164. \MID \code{procedure?} \MID \code{void?} \\
  17165. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17166. \end{array}
  17167. }
  17168. \newcommand{\LanyASTPython}{
  17169. \begin{array}{lcl}
  17170. \Type &::= & \key{AnyType()} \\
  17171. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17172. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17173. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17174. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17175. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  17176. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  17177. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  17178. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17179. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  17180. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  17181. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  17182. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  17183. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  17184. \end{array}
  17185. }
  17186. \begin{figure}[tp]
  17187. \centering
  17188. \begin{tcolorbox}[colback=white]
  17189. \small
  17190. {\if\edition\racketEd
  17191. \[
  17192. \begin{array}{l}
  17193. \gray{\LintOpAST} \\ \hline
  17194. \gray{\LvarASTRacket{}} \\ \hline
  17195. \gray{\LifASTRacket{}} \\ \hline
  17196. \gray{\LwhileASTRacket{}} \\ \hline
  17197. \gray{\LtupASTRacket{}} \\ \hline
  17198. \gray{\LfunASTRacket} \\ \hline
  17199. \gray{\LlambdaASTRacket} \\ \hline
  17200. \LanyASTRacket \\
  17201. \begin{array}{lcl}
  17202. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17203. \end{array}
  17204. \end{array}
  17205. \]
  17206. \fi}
  17207. {\if\edition\pythonEd\pythonColor
  17208. \[
  17209. \begin{array}{l}
  17210. \gray{\LintASTPython} \\ \hline
  17211. \gray{\LvarASTPython{}} \\ \hline
  17212. \gray{\LifASTPython{}} \\ \hline
  17213. \gray{\LwhileASTPython{}} \\ \hline
  17214. \gray{\LtupASTPython{}} \\ \hline
  17215. \gray{\LfunASTPython} \\ \hline
  17216. \gray{\LlambdaASTPython} \\ \hline
  17217. \LanyASTPython \\
  17218. \begin{array}{lcl}
  17219. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17220. \end{array}
  17221. \end{array}
  17222. \]
  17223. \fi}
  17224. \end{tcolorbox}
  17225. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17226. \label{fig:Lany-syntax}
  17227. \end{figure}
  17228. The definition of the abstract syntax of \LangAny{} is given in
  17229. figure~\ref{fig:Lany-syntax}.
  17230. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17231. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17232. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17233. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17234. converts the tagged value produced by expression $e$ into a value of
  17235. type $T$ or halts the program if the type tag does not match $T$.
  17236. %
  17237. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17238. restricted to be a flat type (the nonterminal $\FType$) which
  17239. simplifies the implementation and complies with the needs for
  17240. compiling \LangDyn{}.
  17241. The \racket{\code{any-vector}} operators
  17242. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17243. operations so that they can be applied to a value of type
  17244. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17245. tuple operations in that the index is not restricted to a literal
  17246. integer in the grammar but is allowed to be any expression.
  17247. \racket{The type predicates such as
  17248. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17249. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17250. the predicate and return {\FALSE} otherwise.}
  17251. The type checker for \LangAny{} is shown in
  17252. figure~\ref{fig:type-check-Lany}
  17253. %
  17254. \racket{ and uses the auxiliary functions presented in
  17255. figure~\ref{fig:type-check-Lany-aux}}.
  17256. %
  17257. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17258. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17259. \begin{figure}[btp]
  17260. \begin{tcolorbox}[colback=white]
  17261. {\if\edition\racketEd
  17262. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17263. (define type-check-Lany-class
  17264. (class type-check-Llambda-class
  17265. (super-new)
  17266. (inherit check-type-equal?)
  17267. (define/override (type-check-exp env)
  17268. (lambda (e)
  17269. (define recur (type-check-exp env))
  17270. (match e
  17271. [(Inject e1 ty)
  17272. (unless (flat-ty? ty)
  17273. (error 'type-check "may only inject from flat type, not ~a" ty))
  17274. (define-values (new-e1 e-ty) (recur e1))
  17275. (check-type-equal? e-ty ty e)
  17276. (values (Inject new-e1 ty) 'Any)]
  17277. [(Project e1 ty)
  17278. (unless (flat-ty? ty)
  17279. (error 'type-check "may only project to flat type, not ~a" ty))
  17280. (define-values (new-e1 e-ty) (recur e1))
  17281. (check-type-equal? e-ty 'Any e)
  17282. (values (Project new-e1 ty) ty)]
  17283. [(Prim 'any-vector-length (list e1))
  17284. (define-values (e1^ t1) (recur e1))
  17285. (check-type-equal? t1 'Any e)
  17286. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17287. [(Prim 'any-vector-ref (list e1 e2))
  17288. (define-values (e1^ t1) (recur e1))
  17289. (define-values (e2^ t2) (recur e2))
  17290. (check-type-equal? t1 'Any e)
  17291. (check-type-equal? t2 'Integer e)
  17292. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17293. [(Prim 'any-vector-set! (list e1 e2 e3))
  17294. (define-values (e1^ t1) (recur e1))
  17295. (define-values (e2^ t2) (recur e2))
  17296. (define-values (e3^ t3) (recur e3))
  17297. (check-type-equal? t1 'Any e)
  17298. (check-type-equal? t2 'Integer e)
  17299. (check-type-equal? t3 'Any e)
  17300. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17301. [(Prim pred (list e1))
  17302. #:when (set-member? (type-predicates) pred)
  17303. (define-values (new-e1 e-ty) (recur e1))
  17304. (check-type-equal? e-ty 'Any e)
  17305. (values (Prim pred (list new-e1)) 'Boolean)]
  17306. [(Prim 'eq? (list arg1 arg2))
  17307. (define-values (e1 t1) (recur arg1))
  17308. (define-values (e2 t2) (recur arg2))
  17309. (match* (t1 t2)
  17310. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17311. [(other wise) (check-type-equal? t1 t2 e)])
  17312. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17313. [else ((super type-check-exp env) e)])))
  17314. ))
  17315. \end{lstlisting}
  17316. \fi}
  17317. {\if\edition\pythonEd\pythonColor
  17318. \begin{lstlisting}
  17319. class TypeCheckLany(TypeCheckLlambda):
  17320. def type_check_exp(self, e, env):
  17321. match e:
  17322. case Inject(value, typ):
  17323. self.check_exp(value, typ, env)
  17324. return AnyType()
  17325. case Project(value, typ):
  17326. self.check_exp(value, AnyType(), env)
  17327. return typ
  17328. case Call(Name('any_tuple_load'), [tup, index]):
  17329. self.check_exp(tup, AnyType(), env)
  17330. self.check_exp(index, IntType(), env)
  17331. return AnyType()
  17332. case Call(Name('any_len'), [tup]):
  17333. self.check_exp(tup, AnyType(), env)
  17334. return IntType()
  17335. case Call(Name('arity'), [fun]):
  17336. ty = self.type_check_exp(fun, env)
  17337. match ty:
  17338. case FunctionType(ps, rt):
  17339. return IntType()
  17340. case TupleType([FunctionType(ps,rs)]):
  17341. return IntType()
  17342. case _:
  17343. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  17344. case Call(Name('make_any'), [value, tag]):
  17345. self.type_check_exp(value, env)
  17346. self.check_exp(tag, IntType(), env)
  17347. return AnyType()
  17348. case AnnLambda(params, returns, body):
  17349. new_env = {x:t for (x,t) in env.items()}
  17350. for (x,t) in params:
  17351. new_env[x] = t
  17352. return_t = self.type_check_exp(body, new_env)
  17353. self.check_type_equal(returns, return_t, e)
  17354. return FunctionType([t for (x,t) in params], return_t)
  17355. case _:
  17356. return super().type_check_exp(e, env)
  17357. \end{lstlisting}
  17358. \fi}
  17359. \end{tcolorbox}
  17360. \caption{Type checker for the \LangAny{} language.}
  17361. \label{fig:type-check-Lany}
  17362. \end{figure}
  17363. {\if\edition\racketEd
  17364. \begin{figure}[tbp]
  17365. \begin{tcolorbox}[colback=white]
  17366. \begin{lstlisting}
  17367. (define/override (operator-types)
  17368. (append
  17369. '((integer? . ((Any) . Boolean))
  17370. (vector? . ((Any) . Boolean))
  17371. (procedure? . ((Any) . Boolean))
  17372. (void? . ((Any) . Boolean)))
  17373. (super operator-types)))
  17374. (define/public (type-predicates)
  17375. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17376. (define/public (flat-ty? ty)
  17377. (match ty
  17378. [(or `Integer `Boolean `Void) #t]
  17379. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17380. [`(,ts ... -> ,rt)
  17381. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17382. [else #f]))
  17383. \end{lstlisting}
  17384. \end{tcolorbox}
  17385. \caption{Auxiliary methods for type checking \LangAny{}.}
  17386. \label{fig:type-check-Lany-aux}
  17387. \end{figure}
  17388. \fi}
  17389. \begin{figure}[btp]
  17390. \begin{tcolorbox}[colback=white]
  17391. {\if\edition\racketEd
  17392. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17393. (define interp-Lany-class
  17394. (class interp-Llambda-class
  17395. (super-new)
  17396. (define/override (interp-op op)
  17397. (match op
  17398. ['boolean? (match-lambda
  17399. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17400. [else #f])]
  17401. ['integer? (match-lambda
  17402. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17403. [else #f])]
  17404. ['vector? (match-lambda
  17405. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17406. [else #f])]
  17407. ['procedure? (match-lambda
  17408. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17409. [else #f])]
  17410. ['eq? (match-lambda*
  17411. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17412. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17413. [ls (apply (super interp-op op) ls)])]
  17414. ['any-vector-ref (lambda (v i)
  17415. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17416. ['any-vector-set! (lambda (v i a)
  17417. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17418. ['any-vector-length (lambda (v)
  17419. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17420. [else (super interp-op op)]))
  17421. (define/override ((interp-exp env) e)
  17422. (define recur (interp-exp env))
  17423. (match e
  17424. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17425. [(Project e ty2) (apply-project (recur e) ty2)]
  17426. [else ((super interp-exp env) e)]))
  17427. ))
  17428. (define (interp-Lany p)
  17429. (send (new interp-Lany-class) interp-program p))
  17430. \end{lstlisting}
  17431. \fi}
  17432. {\if\edition\pythonEd\pythonColor
  17433. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17434. class InterpLany(InterpLlambda):
  17435. def interp_exp(self, e, env):
  17436. match e:
  17437. case Inject(value, typ):
  17438. v = self.interp_exp(value, env)
  17439. return Tagged(v, self.type_to_tag(typ))
  17440. case Project(value, typ):
  17441. v = self.interp_exp(value, env)
  17442. match v:
  17443. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17444. return val
  17445. case _:
  17446. raise Exception('interp project to ' + repr(typ)
  17447. + ' unexpected ' + repr(v))
  17448. case Call(Name('any_tuple_load'), [tup, index]):
  17449. tv = self.interp_exp(tup, env)
  17450. n = self.interp_exp(index, env)
  17451. match tv:
  17452. case Tagged(v, tag):
  17453. return v[n]
  17454. case _:
  17455. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  17456. case Call(Name('any_len'), [value]):
  17457. v = self.interp_exp(value, env)
  17458. match v:
  17459. case Tagged(value, tag):
  17460. return len(value)
  17461. case _:
  17462. raise Exception('interp any_len unexpected ' + repr(v))
  17463. case Call(Name('arity'), [fun]):
  17464. f = self.interp_exp(fun, env)
  17465. return self.arity(f)
  17466. case _:
  17467. return super().interp_exp(e, env)
  17468. \end{lstlisting}
  17469. \fi}
  17470. \end{tcolorbox}
  17471. \caption{Interpreter for \LangAny{}.}
  17472. \label{fig:interp-Lany}
  17473. \end{figure}
  17474. \begin{figure}[tbp]
  17475. \begin{tcolorbox}[colback=white]
  17476. {\if\edition\racketEd
  17477. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17478. (define/public (apply-inject v tg) (Tagged v tg))
  17479. (define/public (apply-project v ty2)
  17480. (define tag2 (any-tag ty2))
  17481. (match v
  17482. [(Tagged v1 tag1)
  17483. (cond
  17484. [(eq? tag1 tag2)
  17485. (match ty2
  17486. [`(Vector ,ts ...)
  17487. (define l1 ((interp-op 'vector-length) v1))
  17488. (cond
  17489. [(eq? l1 (length ts)) v1]
  17490. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17491. l1 (length ts))])]
  17492. [`(,ts ... -> ,rt)
  17493. (match v1
  17494. [`(function ,xs ,body ,env)
  17495. (cond [(eq? (length xs) (length ts)) v1]
  17496. [else
  17497. (error 'apply-project "arity mismatch ~a != ~a"
  17498. (length xs) (length ts))])]
  17499. [else (error 'apply-project "expected function not ~a" v1)])]
  17500. [else v1])]
  17501. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17502. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17503. \end{lstlisting}
  17504. \fi}
  17505. {\if\edition\pythonEd\pythonColor
  17506. \begin{lstlisting}
  17507. class InterpLany(InterpLlambda):
  17508. def type_to_tag(self, typ):
  17509. match typ:
  17510. case FunctionType(params, rt):
  17511. return 'function'
  17512. case TupleType(fields):
  17513. return 'tuple'
  17514. case t if t == int:
  17515. return 'int'
  17516. case t if t == bool:
  17517. return 'bool'
  17518. case IntType():
  17519. return 'int'
  17520. case BoolType():
  17521. return 'int'
  17522. case _:
  17523. raise Exception('type_to_tag unexpected ' + repr(typ))
  17524. def arity(self, v):
  17525. match v:
  17526. case Function(name, params, body, env):
  17527. return len(params)
  17528. case ClosureTuple(args, arity):
  17529. return arity
  17530. case _:
  17531. raise Exception('Lany arity unexpected ' + repr(v))
  17532. \end{lstlisting}
  17533. \fi}
  17534. \end{tcolorbox}
  17535. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17536. \label{fig:interp-Lany-aux}
  17537. \end{figure}
  17538. \clearpage
  17539. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17540. \label{sec:compile-r7}
  17541. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17542. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17543. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17544. is that given any subexpression $e$ in the \LangDyn{} program, the
  17545. pass will produce an expression $e'$ in \LangAny{} that has type
  17546. \ANYTY{}. For example, the first row in
  17547. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17548. \TRUE{}, which must be injected to produce an expression of type
  17549. \ANYTY{}.
  17550. %
  17551. The compilation of addition is shown in the second row of
  17552. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17553. representative of many primitive operations: the arguments have type
  17554. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17555. be performed.
  17556. The compilation of \key{lambda} (third row of
  17557. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17558. produce type annotations: we simply use \ANYTY{}.
  17559. %
  17560. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17561. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17562. this pass has to account for some differences in behavior between
  17563. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17564. permissive than \LangAny{} regarding what kind of values can be used
  17565. in various places. For example, the condition of an \key{if} does
  17566. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17567. of the same type (in that case the result is \code{\#f}).}
  17568. \begin{figure}[btp]
  17569. \centering
  17570. \begin{tcolorbox}[colback=white]
  17571. {\if\edition\racketEd
  17572. \begin{tabular}{lll}
  17573. \begin{minipage}{0.27\textwidth}
  17574. \begin{lstlisting}
  17575. #t
  17576. \end{lstlisting}
  17577. \end{minipage}
  17578. &
  17579. $\Rightarrow$
  17580. &
  17581. \begin{minipage}{0.65\textwidth}
  17582. \begin{lstlisting}
  17583. (inject #t Boolean)
  17584. \end{lstlisting}
  17585. \end{minipage}
  17586. \\[2ex]\hline
  17587. \begin{minipage}{0.27\textwidth}
  17588. \begin{lstlisting}
  17589. (+ |$e_1$| |$e_2$|)
  17590. \end{lstlisting}
  17591. \end{minipage}
  17592. &
  17593. $\Rightarrow$
  17594. &
  17595. \begin{minipage}{0.65\textwidth}
  17596. \begin{lstlisting}
  17597. (inject
  17598. (+ (project |$e'_1$| Integer)
  17599. (project |$e'_2$| Integer))
  17600. Integer)
  17601. \end{lstlisting}
  17602. \end{minipage}
  17603. \\[2ex]\hline
  17604. \begin{minipage}{0.27\textwidth}
  17605. \begin{lstlisting}
  17606. (lambda (|$x_1 \ldots$|) |$e$|)
  17607. \end{lstlisting}
  17608. \end{minipage}
  17609. &
  17610. $\Rightarrow$
  17611. &
  17612. \begin{minipage}{0.65\textwidth}
  17613. \begin{lstlisting}
  17614. (inject
  17615. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17616. (Any|$\ldots$|Any -> Any))
  17617. \end{lstlisting}
  17618. \end{minipage}
  17619. \\[2ex]\hline
  17620. \begin{minipage}{0.27\textwidth}
  17621. \begin{lstlisting}
  17622. (|$e_0$| |$e_1 \ldots e_n$|)
  17623. \end{lstlisting}
  17624. \end{minipage}
  17625. &
  17626. $\Rightarrow$
  17627. &
  17628. \begin{minipage}{0.65\textwidth}
  17629. \begin{lstlisting}
  17630. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17631. \end{lstlisting}
  17632. \end{minipage}
  17633. \\[2ex]\hline
  17634. \begin{minipage}{0.27\textwidth}
  17635. \begin{lstlisting}
  17636. (vector-ref |$e_1$| |$e_2$|)
  17637. \end{lstlisting}
  17638. \end{minipage}
  17639. &
  17640. $\Rightarrow$
  17641. &
  17642. \begin{minipage}{0.65\textwidth}
  17643. \begin{lstlisting}
  17644. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17645. \end{lstlisting}
  17646. \end{minipage}
  17647. \\[2ex]\hline
  17648. \begin{minipage}{0.27\textwidth}
  17649. \begin{lstlisting}
  17650. (if |$e_1$| |$e_2$| |$e_3$|)
  17651. \end{lstlisting}
  17652. \end{minipage}
  17653. &
  17654. $\Rightarrow$
  17655. &
  17656. \begin{minipage}{0.65\textwidth}
  17657. \begin{lstlisting}
  17658. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17659. \end{lstlisting}
  17660. \end{minipage}
  17661. \\[2ex]\hline
  17662. \begin{minipage}{0.27\textwidth}
  17663. \begin{lstlisting}
  17664. (eq? |$e_1$| |$e_2$|)
  17665. \end{lstlisting}
  17666. \end{minipage}
  17667. &
  17668. $\Rightarrow$
  17669. &
  17670. \begin{minipage}{0.65\textwidth}
  17671. \begin{lstlisting}
  17672. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17673. \end{lstlisting}
  17674. \end{minipage}
  17675. \\[2ex]\hline
  17676. \begin{minipage}{0.27\textwidth}
  17677. \begin{lstlisting}
  17678. (not |$e_1$|)
  17679. \end{lstlisting}
  17680. \end{minipage}
  17681. &
  17682. $\Rightarrow$
  17683. &
  17684. \begin{minipage}{0.65\textwidth}
  17685. \begin{lstlisting}
  17686. (if (eq? |$e'_1$| (inject #f Boolean))
  17687. (inject #t Boolean) (inject #f Boolean))
  17688. \end{lstlisting}
  17689. \end{minipage}
  17690. \end{tabular}
  17691. \fi}
  17692. {\if\edition\pythonEd\pythonColor
  17693. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17694. \begin{minipage}{0.23\textwidth}
  17695. \begin{lstlisting}
  17696. True
  17697. \end{lstlisting}
  17698. \end{minipage}
  17699. &
  17700. $\Rightarrow$
  17701. &
  17702. \begin{minipage}{0.7\textwidth}
  17703. \begin{lstlisting}
  17704. Inject(True, BoolType())
  17705. \end{lstlisting}
  17706. \end{minipage}
  17707. \\[2ex]\hline
  17708. \begin{minipage}{0.23\textwidth}
  17709. \begin{lstlisting}
  17710. |$e_1$| + |$e_2$|
  17711. \end{lstlisting}
  17712. \end{minipage}
  17713. &
  17714. $\Rightarrow$
  17715. &
  17716. \begin{minipage}{0.7\textwidth}
  17717. \begin{lstlisting}
  17718. Inject(Project(|$e'_1$|, IntType())
  17719. + Project(|$e'_2$|, IntType()),
  17720. IntType())
  17721. \end{lstlisting}
  17722. \end{minipage}
  17723. \\[2ex]\hline
  17724. \begin{minipage}{0.23\textwidth}
  17725. \begin{lstlisting}
  17726. lambda |$x_1 \ldots$|: |$e$|
  17727. \end{lstlisting}
  17728. \end{minipage}
  17729. &
  17730. $\Rightarrow$
  17731. &
  17732. \begin{minipage}{0.7\textwidth}
  17733. \begin{lstlisting}
  17734. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17735. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17736. \end{lstlisting}
  17737. \end{minipage}
  17738. \\[2ex]\hline
  17739. \begin{minipage}{0.23\textwidth}
  17740. \begin{lstlisting}
  17741. |$e_0$|(|$e_1 \ldots e_n$|)
  17742. \end{lstlisting}
  17743. \end{minipage}
  17744. &
  17745. $\Rightarrow$
  17746. &
  17747. \begin{minipage}{0.7\textwidth}
  17748. \begin{lstlisting}
  17749. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17750. AnyType())), |$e'_1, \ldots, e'_n$|)
  17751. \end{lstlisting}
  17752. \end{minipage}
  17753. \\[2ex]\hline
  17754. \begin{minipage}{0.23\textwidth}
  17755. \begin{lstlisting}
  17756. |$e_1$|[|$e_2$|]
  17757. \end{lstlisting}
  17758. \end{minipage}
  17759. &
  17760. $\Rightarrow$
  17761. &
  17762. \begin{minipage}{0.7\textwidth}
  17763. \begin{lstlisting}
  17764. Call(Name('any_tuple_load'),
  17765. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  17766. \end{lstlisting}
  17767. \end{minipage}
  17768. %% \begin{minipage}{0.23\textwidth}
  17769. %% \begin{lstlisting}
  17770. %% |$e_2$| if |$e_1$| else |$e_3$|
  17771. %% \end{lstlisting}
  17772. %% \end{minipage}
  17773. %% &
  17774. %% $\Rightarrow$
  17775. %% &
  17776. %% \begin{minipage}{0.7\textwidth}
  17777. %% \begin{lstlisting}
  17778. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17779. %% \end{lstlisting}
  17780. %% \end{minipage}
  17781. %% \\[2ex]\hline
  17782. %% \begin{minipage}{0.23\textwidth}
  17783. %% \begin{lstlisting}
  17784. %% (eq? |$e_1$| |$e_2$|)
  17785. %% \end{lstlisting}
  17786. %% \end{minipage}
  17787. %% &
  17788. %% $\Rightarrow$
  17789. %% &
  17790. %% \begin{minipage}{0.7\textwidth}
  17791. %% \begin{lstlisting}
  17792. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17793. %% \end{lstlisting}
  17794. %% \end{minipage}
  17795. %% \\[2ex]\hline
  17796. %% \begin{minipage}{0.23\textwidth}
  17797. %% \begin{lstlisting}
  17798. %% (not |$e_1$|)
  17799. %% \end{lstlisting}
  17800. %% \end{minipage}
  17801. %% &
  17802. %% $\Rightarrow$
  17803. %% &
  17804. %% \begin{minipage}{0.7\textwidth}
  17805. %% \begin{lstlisting}
  17806. %% (if (eq? |$e'_1$| (inject #f Boolean))
  17807. %% (inject #t Boolean) (inject #f Boolean))
  17808. %% \end{lstlisting}
  17809. %% \end{minipage}
  17810. %% \\[2ex]\hline
  17811. \\\hline
  17812. \end{tabular}
  17813. \fi}
  17814. \end{tcolorbox}
  17815. \caption{Cast insertion.}
  17816. \label{fig:compile-r7-Lany}
  17817. \end{figure}
  17818. \section{Reveal Casts}
  17819. \label{sec:reveal-casts-Lany}
  17820. % TODO: define R'_6
  17821. In the \code{reveal\_casts} pass, we recommend compiling
  17822. \code{Project} into a conditional expression that checks whether the
  17823. value's tag matches the target type; if it does, the value is
  17824. converted to a value of the target type by removing the tag; if it
  17825. does not, the program exits.
  17826. %
  17827. {\if\edition\racketEd
  17828. %
  17829. To perform these actions we need a new primitive operation,
  17830. \code{tag-of-any}, and a new form, \code{ValueOf}.
  17831. The \code{tag-of-any} operation retrieves the type tag from a tagged
  17832. value of type \code{Any}. The \code{ValueOf} form retrieves the
  17833. underlying value from a tagged value. The \code{ValueOf} form
  17834. includes the type for the underlying value that is used by the type
  17835. checker.
  17836. %
  17837. \fi}
  17838. %
  17839. {\if\edition\pythonEd\pythonColor
  17840. %
  17841. To perform these actions we need two new AST classes: \code{TagOf} and
  17842. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  17843. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  17844. the underlying value from a tagged value. The \code{ValueOf}
  17845. operation includes the type for the underlying value which is used by
  17846. the type checker.
  17847. %
  17848. \fi}
  17849. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  17850. \code{Project} can be translated as follows:
  17851. \begin{center}
  17852. \begin{minipage}{1.0\textwidth}
  17853. {\if\edition\racketEd
  17854. \begin{lstlisting}
  17855. (Project |$e$| |$\FType$|)
  17856. |$\Rightarrow$|
  17857. (Let |$\itm{tmp}$| |$e'$|
  17858. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  17859. (Int |$\itm{tagof}(\FType)$|)))
  17860. (ValueOf |$\itm{tmp}$| |$\FType$|)
  17861. (Exit)))
  17862. \end{lstlisting}
  17863. \fi}
  17864. {\if\edition\pythonEd\pythonColor
  17865. \begin{lstlisting}
  17866. Project(|$e$|, |$\FType$|)
  17867. |$\Rightarrow$|
  17868. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  17869. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  17870. [Constant(|$\itm{tagof}(\FType)$|)]),
  17871. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  17872. Call(Name('exit'), [])))
  17873. \end{lstlisting}
  17874. \fi}
  17875. \end{minipage}
  17876. \end{center}
  17877. If the target type of the projection is a tuple or function type, then
  17878. there is a bit more work to do. For tuples, check that the length of
  17879. the tuple type matches the length of the tuple. For functions, check
  17880. that the number of parameters in the function type matches the
  17881. function's arity.
  17882. Regarding \code{Inject}, we recommend compiling it to a slightly
  17883. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  17884. takes a tag instead of a type.
  17885. \begin{center}
  17886. \begin{minipage}{1.0\textwidth}
  17887. {\if\edition\racketEd
  17888. \begin{lstlisting}
  17889. (Inject |$e$| |$\FType$|)
  17890. |$\Rightarrow$|
  17891. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  17892. \end{lstlisting}
  17893. \fi}
  17894. {\if\edition\pythonEd\pythonColor
  17895. \begin{lstlisting}
  17896. Inject(|$e$|, |$\FType$|)
  17897. |$\Rightarrow$|
  17898. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  17899. \end{lstlisting}
  17900. \fi}
  17901. \end{minipage}
  17902. \end{center}
  17903. {\if\edition\pythonEd\pythonColor
  17904. %
  17905. The introduction of \code{make\_any} makes it difficult to use
  17906. bidirectional type checking because we no longer have an expected type
  17907. to use for type checking the expression $e'$. Thus, we run into
  17908. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  17909. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  17910. annotated lambda) whose parameters have type annotations and that
  17911. records the return type.
  17912. %
  17913. \fi}
  17914. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  17915. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  17916. translation of \code{Project}.}
  17917. {\if\edition\racketEd
  17918. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17919. combine the projection action with the vector operation. Also, the
  17920. read and write operations allow arbitrary expressions for the index, so
  17921. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17922. cannot guarantee that the index is within bounds. Thus, we insert code
  17923. to perform bounds checking at runtime. The translation for
  17924. \code{any-vector-ref} is as follows, and the other two operations are
  17925. translated in a similar way:
  17926. \begin{center}
  17927. \begin{minipage}{0.95\textwidth}
  17928. \begin{lstlisting}
  17929. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17930. |$\Rightarrow$|
  17931. (Let |$v$| |$e'_1$|
  17932. (Let |$i$| |$e'_2$|
  17933. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17934. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17935. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17936. (Exit))
  17937. (Exit))))
  17938. \end{lstlisting}
  17939. \end{minipage}
  17940. \end{center}
  17941. \fi}
  17942. %
  17943. {\if\edition\pythonEd\pythonColor
  17944. %
  17945. The \code{any\_tuple\_load} operation combines the projection action
  17946. with the load operation. Also, the load operation allows arbitrary
  17947. expressions for the index so the type checker for \LangAny{}
  17948. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17949. within bounds. Thus, we insert code to perform bounds checking at
  17950. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17951. \begin{lstlisting}
  17952. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17953. |$\Rightarrow$|
  17954. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17955. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17956. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17957. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17958. Call(Name('exit'), [])),
  17959. Call(Name('exit'), [])))
  17960. \end{lstlisting}
  17961. \fi}
  17962. {\if\edition\pythonEd\pythonColor
  17963. \section{Assignment Conversion}
  17964. \label{sec:convert-assignments-Lany}
  17965. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17966. \code{AnnLambda} AST classes.
  17967. \section{Closure Conversion}
  17968. \label{sec:closure-conversion-Lany}
  17969. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17970. \code{AnnLambda} AST classes.
  17971. \fi}
  17972. \section{Remove Complex Operands}
  17973. \label{sec:rco-Lany}
  17974. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17975. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17976. %
  17977. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17978. complex expressions. Their subexpressions must be atomic.}
  17979. \section{Explicate Control and \LangCAny{}}
  17980. \label{sec:explicate-Lany}
  17981. The output of \code{explicate\_control} is the \LangCAny{} language,
  17982. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  17983. %
  17984. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17985. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17986. note that the index argument of \code{vector-ref} and
  17987. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  17988. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17989. %
  17990. \python{
  17991. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17992. and \code{explicate\_pred} as appropriately to handle the new expressions
  17993. in \LangCAny{}.
  17994. }
  17995. \newcommand{\CanyASTPython}{
  17996. \begin{array}{lcl}
  17997. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17998. &\MID& \key{TagOf}\LP \Atm \RP
  17999. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18000. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  18001. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  18002. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  18003. \end{array}
  18004. }
  18005. \newcommand{\CanyASTRacket}{
  18006. \begin{array}{lcl}
  18007. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18008. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18009. &\MID& \VALUEOF{\Atm}{\FType} \\
  18010. \Tail &::= & \LP\key{Exit}\RP
  18011. \end{array}
  18012. }
  18013. \begin{figure}[tp]
  18014. \begin{tcolorbox}[colback=white]
  18015. \small
  18016. {\if\edition\racketEd
  18017. \[
  18018. \begin{array}{l}
  18019. \gray{\CvarASTRacket} \\ \hline
  18020. \gray{\CifASTRacket} \\ \hline
  18021. \gray{\CloopASTRacket} \\ \hline
  18022. \gray{\CtupASTRacket} \\ \hline
  18023. \gray{\CfunASTRacket} \\ \hline
  18024. \gray{\ClambdaASTRacket} \\ \hline
  18025. \CanyASTRacket \\
  18026. \begin{array}{lcl}
  18027. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18028. \end{array}
  18029. \end{array}
  18030. \]
  18031. \fi}
  18032. {\if\edition\pythonEd\pythonColor
  18033. \[
  18034. \begin{array}{l}
  18035. \gray{\CifASTPython} \\ \hline
  18036. \gray{\CtupASTPython} \\ \hline
  18037. \gray{\CfunASTPython} \\ \hline
  18038. \gray{\ClambdaASTPython} \\ \hline
  18039. \CanyASTPython \\
  18040. \begin{array}{lcl}
  18041. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18042. \end{array}
  18043. \end{array}
  18044. \]
  18045. \fi}
  18046. \end{tcolorbox}
  18047. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18048. \label{fig:c5-syntax}
  18049. \end{figure}
  18050. \section{Select Instructions}
  18051. \label{sec:select-Lany}
  18052. \index{subject}{select instructions}
  18053. In the \code{select\_instructions} pass, we translate the primitive
  18054. operations on the \ANYTY{} type to x86 instructions that manipulate
  18055. the three tag bits of the tagged value. In the following descriptions,
  18056. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18057. of translating $e$ into an x86 argument:
  18058. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18059. We recommend compiling the
  18060. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18061. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18062. shifts the destination to the left by the number of bits specified by its
  18063. source argument (in this case three, the length of the tag), and it
  18064. preserves the sign of the integer. We use the \key{orq} instruction to
  18065. combine the tag and the value to form the tagged value.
  18066. {\if\edition\racketEd
  18067. \begin{lstlisting}
  18068. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18069. |$\Rightarrow$|
  18070. movq |$e'$|, |\itm{lhs'}|
  18071. salq $3, |\itm{lhs'}|
  18072. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18073. \end{lstlisting}
  18074. \fi}
  18075. %
  18076. {\if\edition\pythonEd\pythonColor
  18077. \begin{lstlisting}
  18078. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18079. |$\Rightarrow$|
  18080. movq |$e'$|, |\itm{lhs'}|
  18081. salq $3, |\itm{lhs'}|
  18082. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18083. \end{lstlisting}
  18084. \fi}
  18085. %
  18086. The instruction selection\index{subject}{instruction selection} for
  18087. tuples and procedures is different because there is no need to shift
  18088. them to the left. The rightmost 3 bits are already zeros, so we simply
  18089. combine the value and the tag using \key{orq}. \\
  18090. %
  18091. {\if\edition\racketEd
  18092. \begin{center}
  18093. \begin{minipage}{\textwidth}
  18094. \begin{lstlisting}
  18095. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18096. |$\Rightarrow$|
  18097. movq |$e'$|, |\itm{lhs'}|
  18098. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18099. \end{lstlisting}
  18100. \end{minipage}
  18101. \end{center}
  18102. \fi}
  18103. %
  18104. {\if\edition\pythonEd\pythonColor
  18105. \begin{lstlisting}
  18106. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18107. |$\Rightarrow$|
  18108. movq |$e'$|, |\itm{lhs'}|
  18109. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18110. \end{lstlisting}
  18111. \fi}
  18112. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18113. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18114. operation extracts the type tag from a value of type \ANYTY{}. The
  18115. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18116. bitwise-and of the value with $111$ ($7$ decimal).
  18117. %
  18118. {\if\edition\racketEd
  18119. \begin{lstlisting}
  18120. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18121. |$\Rightarrow$|
  18122. movq |$e'$|, |\itm{lhs'}|
  18123. andq $7, |\itm{lhs'}|
  18124. \end{lstlisting}
  18125. \fi}
  18126. %
  18127. {\if\edition\pythonEd\pythonColor
  18128. \begin{lstlisting}
  18129. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18130. |$\Rightarrow$|
  18131. movq |$e'$|, |\itm{lhs'}|
  18132. andq $7, |\itm{lhs'}|
  18133. \end{lstlisting}
  18134. \fi}
  18135. \paragraph{\code{ValueOf}}
  18136. The instructions for \key{ValueOf} also differ, depending on whether
  18137. the type $T$ is a pointer (tuple or function) or not (integer or
  18138. Boolean). The following shows the instruction
  18139. selection for integers and
  18140. Booleans, in which we produce an untagged value by shifting it to the
  18141. right by 3 bits:
  18142. %
  18143. {\if\edition\racketEd
  18144. \begin{lstlisting}
  18145. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18146. |$\Rightarrow$|
  18147. movq |$e'$|, |\itm{lhs'}|
  18148. sarq $3, |\itm{lhs'}|
  18149. \end{lstlisting}
  18150. \fi}
  18151. %
  18152. {\if\edition\pythonEd\pythonColor
  18153. \begin{lstlisting}
  18154. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18155. |$\Rightarrow$|
  18156. movq |$e'$|, |\itm{lhs'}|
  18157. sarq $3, |\itm{lhs'}|
  18158. \end{lstlisting}
  18159. \fi}
  18160. %
  18161. In the case for tuples and procedures, we zero out the rightmost 3
  18162. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18163. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18164. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18165. Finally, we apply \code{andq} with the tagged value to get the desired
  18166. result.
  18167. %
  18168. {\if\edition\racketEd
  18169. \begin{lstlisting}
  18170. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18171. |$\Rightarrow$|
  18172. movq $|$-8$|, |\itm{lhs'}|
  18173. andq |$e'$|, |\itm{lhs'}|
  18174. \end{lstlisting}
  18175. \fi}
  18176. %
  18177. {\if\edition\pythonEd\pythonColor
  18178. \begin{lstlisting}
  18179. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18180. |$\Rightarrow$|
  18181. movq $|$-8$|, |\itm{lhs'}|
  18182. andq |$e'$|, |\itm{lhs'}|
  18183. \end{lstlisting}
  18184. \fi}
  18185. %% \paragraph{Type Predicates} We leave it to the reader to
  18186. %% devise a sequence of instructions to implement the type predicates
  18187. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18188. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18189. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18190. operation combines the effect of \code{ValueOf} with accessing the
  18191. length of a tuple from the tag stored at the zero index of the tuple.
  18192. {\if\edition\racketEd
  18193. \begin{lstlisting}
  18194. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18195. |$\Longrightarrow$|
  18196. movq $|$-8$|, %r11
  18197. andq |$e_1'$|, %r11
  18198. movq 0(%r11), %r11
  18199. andq $126, %r11
  18200. sarq $1, %r11
  18201. movq %r11, |$\itm{lhs'}$|
  18202. \end{lstlisting}
  18203. \fi}
  18204. {\if\edition\pythonEd\pythonColor
  18205. \begin{lstlisting}
  18206. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18207. |$\Longrightarrow$|
  18208. movq $|$-8$|, %r11
  18209. andq |$e_1'$|, %r11
  18210. movq 0(%r11), %r11
  18211. andq $126, %r11
  18212. sarq $1, %r11
  18213. movq %r11, |$\itm{lhs'}$|
  18214. \end{lstlisting}
  18215. \fi}
  18216. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18217. This operation combines the effect of \code{ValueOf} with reading an
  18218. element of the tuple (see
  18219. section~\ref{sec:select-instructions-gc}). However, the index may be
  18220. an arbitrary atom, so instead of computing the offset at compile time,
  18221. we must generate instructions to compute the offset at runtime as
  18222. follows. Note the use of the new instruction \code{imulq}.
  18223. \begin{center}
  18224. \begin{minipage}{0.96\textwidth}
  18225. {\if\edition\racketEd
  18226. \begin{lstlisting}
  18227. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18228. |$\Longrightarrow$|
  18229. movq |$\neg 111$|, %r11
  18230. andq |$e_1'$|, %r11
  18231. movq |$e_2'$|, %rax
  18232. addq $1, %rax
  18233. imulq $8, %rax
  18234. addq %rax, %r11
  18235. movq 0(%r11) |$\itm{lhs'}$|
  18236. \end{lstlisting}
  18237. \fi}
  18238. %
  18239. {\if\edition\pythonEd\pythonColor
  18240. \begin{lstlisting}
  18241. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18242. |$\Longrightarrow$|
  18243. movq $|$-8$|, %r11
  18244. andq |$e_1'$|, %r11
  18245. movq |$e_2'$|, %rax
  18246. addq $1, %rax
  18247. imulq $8, %rax
  18248. addq %rax, %r11
  18249. movq 0(%r11) |$\itm{lhs'}$|
  18250. \end{lstlisting}
  18251. \fi}
  18252. \end{minipage}
  18253. \end{center}
  18254. % $ pacify font lock
  18255. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18256. %% The code generation for
  18257. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18258. %% analogous to the above translation for reading from a tuple.
  18259. \section{Register Allocation for \LangAny{}}
  18260. \label{sec:register-allocation-Lany}
  18261. \index{subject}{register allocation}
  18262. There is an interesting interaction between tagged values and garbage
  18263. collection that has an impact on register allocation. A variable of
  18264. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18265. that needs to be inspected and copied during garbage collection. Thus,
  18266. we need to treat variables of type \ANYTY{} in a similar way to
  18267. variables of tuple type for purposes of register allocation,
  18268. with particular attention to the following:
  18269. \begin{itemize}
  18270. \item If a variable of type \ANYTY{} is live during a function call,
  18271. then it must be spilled. This can be accomplished by changing
  18272. \code{build\_interference} to mark all variables of type \ANYTY{}
  18273. that are live after a \code{callq} to be interfering with all the
  18274. registers.
  18275. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18276. the root stack instead of the normal procedure call stack.
  18277. \end{itemize}
  18278. Another concern regarding the root stack is that the garbage collector
  18279. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18280. tagged value that points to a tuple, and (3) a tagged value that is
  18281. not a tuple. We enable this differentiation by choosing not to use the
  18282. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18283. reserved for identifying plain old pointers to tuples. That way, if
  18284. one of the first three bits is set, then we have a tagged value and
  18285. inspecting the tag can differentiate between tuples ($010$) and the
  18286. other kinds of values.
  18287. %% \begin{exercise}\normalfont
  18288. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18289. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18290. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18291. %% compiler on these new programs and all of your previously created test
  18292. %% programs.
  18293. %% \end{exercise}
  18294. \begin{exercise}\normalfont\normalsize
  18295. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18296. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18297. by removing type annotations. Add five more test programs that
  18298. specifically rely on the language being dynamically typed. That is,
  18299. they should not be legal programs in a statically typed language, but
  18300. nevertheless they should be valid \LangDyn{} programs that run to
  18301. completion without error.
  18302. \end{exercise}
  18303. \begin{figure}[p]
  18304. \begin{tcolorbox}[colback=white]
  18305. {\if\edition\racketEd
  18306. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18307. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18308. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18309. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18310. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18311. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18312. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18313. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18314. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18315. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18316. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18317. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18318. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18319. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18320. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18321. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18322. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18323. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18324. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18325. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18326. \path[->,bend left=15] (Lfun) edge [above] node
  18327. {\ttfamily\footnotesize shrink} (Lfun-2);
  18328. \path[->,bend left=15] (Lfun-2) edge [above] node
  18329. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18330. \path[->,bend left=15] (Lfun-3) edge [above] node
  18331. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18332. \path[->,bend left=15] (Lfun-4) edge [left] node
  18333. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18334. \path[->,bend left=15] (Lfun-5) edge [below] node
  18335. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18336. \path[->,bend left=15] (Lfun-6) edge [below] node
  18337. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18338. \path[->,bend right=15] (Lfun-7) edge [above] node
  18339. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18340. \path[->,bend right=15] (F1-2) edge [right] node
  18341. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18342. \path[->,bend right=15] (F1-3) edge [below] node
  18343. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18344. \path[->,bend right=15] (F1-4) edge [below] node
  18345. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18346. \path[->,bend left=15] (F1-5) edge [above] node
  18347. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18348. \path[->,bend left=10] (F1-6) edge [below] node
  18349. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18350. \path[->,bend left=15] (C3-2) edge [right] node
  18351. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18352. \path[->,bend right=15] (x86-2) edge [right] node
  18353. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18354. \path[->,bend right=15] (x86-2-1) edge [below] node
  18355. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18356. \path[->,bend right=15] (x86-2-2) edge [right] node
  18357. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18358. \path[->,bend left=15] (x86-3) edge [above] node
  18359. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18360. \path[->,bend left=15] (x86-4) edge [right] node
  18361. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18362. \end{tikzpicture}
  18363. \fi}
  18364. {\if\edition\pythonEd\pythonColor
  18365. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18366. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18367. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18368. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18369. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18370. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18371. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18372. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18373. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18374. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18375. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18376. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18377. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18378. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18379. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18380. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18381. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18382. \path[->,bend left=15] (Lfun) edge [above] node
  18383. {\ttfamily\footnotesize shrink} (Lfun-2);
  18384. \path[->,bend left=15] (Lfun-2) edge [above] node
  18385. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18386. \path[->,bend left=15] (Lfun-3) edge [above] node
  18387. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18388. \path[->,bend left=15] (Lfun-4) edge [left] node
  18389. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18390. \path[->,bend left=15] (Lfun-5) edge [below] node
  18391. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18392. \path[->,bend right=15] (Lfun-6) edge [above] node
  18393. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18394. \path[->,bend right=15] (Lfun-7) edge [above] node
  18395. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18396. \path[->,bend right=15] (F1-2) edge [right] node
  18397. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18398. \path[->,bend right=15] (F1-3) edge [below] node
  18399. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18400. \path[->,bend left=15] (F1-5) edge [above] node
  18401. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18402. \path[->,bend left=10] (F1-6) edge [below] node
  18403. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18404. \path[->,bend right=15] (C3-2) edge [right] node
  18405. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18406. \path[->,bend right=15] (x86-2) edge [below] node
  18407. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18408. \path[->,bend right=15] (x86-3) edge [below] node
  18409. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18410. \path[->,bend left=15] (x86-4) edge [above] node
  18411. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18412. \end{tikzpicture}
  18413. \fi}
  18414. \end{tcolorbox}
  18415. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18416. \label{fig:Ldyn-passes}
  18417. \end{figure}
  18418. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18419. for the compilation of \LangDyn{}.
  18420. % Further Reading
  18421. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18422. %% {\if\edition\pythonEd\pythonColor
  18423. %% \chapter{Objects}
  18424. %% \label{ch:Lobject}
  18425. %% \index{subject}{objects}
  18426. %% \index{subject}{classes}
  18427. %% \setcounter{footnote}{0}
  18428. %% \fi}
  18429. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18430. \chapter{Gradual Typing}
  18431. \label{ch:Lgrad}
  18432. \index{subject}{gradual typing}
  18433. \setcounter{footnote}{0}
  18434. This chapter studies the language \LangGrad{}, in which the programmer
  18435. can choose between static and dynamic type checking in different parts
  18436. of a program, thereby mixing the statically typed \LangLam{} language
  18437. with the dynamically typed \LangDyn{}. There are several approaches to
  18438. mixing static and dynamic typing, including multilanguage
  18439. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18440. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18441. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18442. programmer controls the amount of static versus dynamic checking by
  18443. adding or removing type annotations on parameters and
  18444. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18445. The definition of the concrete syntax of \LangGrad{} is shown in
  18446. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18447. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18448. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18449. annotations are optional, which is specified in the grammar using the
  18450. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18451. annotations are not optional, but we use the \CANYTY{} type when a type
  18452. annotation is absent.
  18453. %
  18454. Both the type checker and the interpreter for \LangGrad{} require some
  18455. interesting changes to enable gradual typing, which we discuss in the
  18456. next two sections.
  18457. \newcommand{\LgradGrammarRacket}{
  18458. \begin{array}{lcl}
  18459. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18460. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18461. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18462. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18463. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18464. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18465. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18466. \end{array}
  18467. }
  18468. \newcommand{\LgradASTRacket}{
  18469. \begin{array}{lcl}
  18470. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18471. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18472. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18473. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18474. \itm{op} &::=& \code{procedure-arity} \\
  18475. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18476. \end{array}
  18477. }
  18478. \newcommand{\LgradGrammarPython}{
  18479. \begin{array}{lcl}
  18480. \Type &::=& \key{Any}
  18481. \MID \key{int}
  18482. \MID \key{bool}
  18483. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18484. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18485. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18486. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18487. \MID \CARITY{\Exp} \\
  18488. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18489. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18490. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18491. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18492. \end{array}
  18493. }
  18494. \newcommand{\LgradASTPython}{
  18495. \begin{array}{lcl}
  18496. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18497. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18498. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18499. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18500. &\MID& \ARITY{\Exp} \\
  18501. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18502. \MID \RETURN{\Exp} \\
  18503. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18504. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18505. \end{array}
  18506. }
  18507. \begin{figure}[tp]
  18508. \centering
  18509. \begin{tcolorbox}[colback=white]
  18510. \small
  18511. {\if\edition\racketEd
  18512. \[
  18513. \begin{array}{l}
  18514. \gray{\LintGrammarRacket{}} \\ \hline
  18515. \gray{\LvarGrammarRacket{}} \\ \hline
  18516. \gray{\LifGrammarRacket{}} \\ \hline
  18517. \gray{\LwhileGrammarRacket} \\ \hline
  18518. \gray{\LtupGrammarRacket} \\ \hline
  18519. \LgradGrammarRacket \\
  18520. \begin{array}{lcl}
  18521. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18522. \end{array}
  18523. \end{array}
  18524. \]
  18525. \fi}
  18526. {\if\edition\pythonEd\pythonColor
  18527. \[
  18528. \begin{array}{l}
  18529. \gray{\LintGrammarPython{}} \\ \hline
  18530. \gray{\LvarGrammarPython{}} \\ \hline
  18531. \gray{\LifGrammarPython{}} \\ \hline
  18532. \gray{\LwhileGrammarPython} \\ \hline
  18533. \gray{\LtupGrammarPython} \\ \hline
  18534. \LgradGrammarPython \\
  18535. \begin{array}{lcl}
  18536. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18537. \end{array}
  18538. \end{array}
  18539. \]
  18540. \fi}
  18541. \end{tcolorbox}
  18542. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18543. \label{fig:Lgrad-concrete-syntax}
  18544. \end{figure}
  18545. \begin{figure}[tp]
  18546. \centering
  18547. \begin{tcolorbox}[colback=white]
  18548. \small
  18549. {\if\edition\racketEd
  18550. \[
  18551. \begin{array}{l}
  18552. \gray{\LintOpAST} \\ \hline
  18553. \gray{\LvarASTRacket{}} \\ \hline
  18554. \gray{\LifASTRacket{}} \\ \hline
  18555. \gray{\LwhileASTRacket{}} \\ \hline
  18556. \gray{\LtupASTRacket{}} \\ \hline
  18557. \LgradASTRacket \\
  18558. \begin{array}{lcl}
  18559. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18560. \end{array}
  18561. \end{array}
  18562. \]
  18563. \fi}
  18564. {\if\edition\pythonEd\pythonColor
  18565. \[
  18566. \begin{array}{l}
  18567. \gray{\LintASTPython{}} \\ \hline
  18568. \gray{\LvarASTPython{}} \\ \hline
  18569. \gray{\LifASTPython{}} \\ \hline
  18570. \gray{\LwhileASTPython} \\ \hline
  18571. \gray{\LtupASTPython} \\ \hline
  18572. \LgradASTPython \\
  18573. \begin{array}{lcl}
  18574. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18575. \end{array}
  18576. \end{array}
  18577. \]
  18578. \fi}
  18579. \end{tcolorbox}
  18580. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18581. \label{fig:Lgrad-syntax}
  18582. \end{figure}
  18583. % TODO: more road map -Jeremy
  18584. %\clearpage
  18585. \section{Type Checking \LangGrad{}}
  18586. \label{sec:gradual-type-check}
  18587. We begin by discussing the type checking of a partially typed variant
  18588. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18589. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18590. statically typed, so there is nothing special happening there with
  18591. respect to type checking. On the other hand, the \code{inc} function
  18592. does not have type annotations, so the type checker assigns the type
  18593. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18594. \code{+} operator inside \code{inc}. It expects both arguments to have
  18595. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18596. a gradually typed language, such differences are allowed so long as
  18597. the types are \emph{consistent}; that is, they are equal except in
  18598. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18599. is consistent with every other type. Figure~\ref{fig:consistent}
  18600. shows the definition of the
  18601. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18602. %
  18603. So the type checker allows the \code{+} operator to be applied
  18604. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18605. %
  18606. Next consider the call to the \code{map} function shown in
  18607. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18608. tuple. The \code{inc} function has type
  18609. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18610. but parameter \code{f} of \code{map} has type
  18611. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18612. The type checker for \LangGrad{} accepts this call because the two types are
  18613. consistent.
  18614. \begin{figure}[btp]
  18615. % gradual_test_9.rkt
  18616. \begin{tcolorbox}[colback=white]
  18617. {\if\edition\racketEd
  18618. \begin{lstlisting}
  18619. (define (map [f : (Integer -> Integer)]
  18620. [v : (Vector Integer Integer)])
  18621. : (Vector Integer Integer)
  18622. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18623. (define (inc x) (+ x 1))
  18624. (vector-ref (map inc (vector 0 41)) 1)
  18625. \end{lstlisting}
  18626. \fi}
  18627. {\if\edition\pythonEd\pythonColor
  18628. \begin{lstlisting}
  18629. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18630. return f(v[0]), f(v[1])
  18631. def inc(x):
  18632. return x + 1
  18633. t = map(inc, (0, 41))
  18634. print(t[1])
  18635. \end{lstlisting}
  18636. \fi}
  18637. \end{tcolorbox}
  18638. \caption{A partially typed version of the \code{map} example.}
  18639. \label{fig:gradual-map}
  18640. \end{figure}
  18641. \begin{figure}[tbp]
  18642. \begin{tcolorbox}[colback=white]
  18643. {\if\edition\racketEd
  18644. \begin{lstlisting}
  18645. (define/public (consistent? t1 t2)
  18646. (match* (t1 t2)
  18647. [('Integer 'Integer) #t]
  18648. [('Boolean 'Boolean) #t]
  18649. [('Void 'Void) #t]
  18650. [('Any t2) #t]
  18651. [(t1 'Any) #t]
  18652. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18653. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18654. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18655. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18656. (consistent? rt1 rt2))]
  18657. [(other wise) #f]))
  18658. \end{lstlisting}
  18659. \fi}
  18660. {\if\edition\pythonEd\pythonColor
  18661. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18662. def consistent(self, t1, t2):
  18663. match (t1, t2):
  18664. case (AnyType(), _):
  18665. return True
  18666. case (_, AnyType()):
  18667. return True
  18668. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18669. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18670. case (TupleType(ts1), TupleType(ts2)):
  18671. return all(map(self.consistent, ts1, ts2))
  18672. case (_, _):
  18673. return t1 == t2
  18674. \end{lstlisting}
  18675. \fi}
  18676. \end{tcolorbox}
  18677. \caption{The consistency method on types.}
  18678. \label{fig:consistent}
  18679. \end{figure}
  18680. It is also helpful to consider how gradual typing handles programs with an
  18681. error, such as applying \code{map} to a function that sometimes
  18682. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18683. type checker for \LangGrad{} accepts this program because the type of
  18684. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18685. \code{map}; that is,
  18686. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18687. is consistent with
  18688. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18689. One might say that a gradual type checker is optimistic in that it
  18690. accepts programs that might execute without a runtime type error.
  18691. %
  18692. The definition of the type checker for \LangGrad{} is shown in
  18693. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18694. and \ref{fig:type-check-Lgradual-3}.
  18695. %% \begin{figure}[tp]
  18696. %% \centering
  18697. %% \fbox{
  18698. %% \begin{minipage}{0.96\textwidth}
  18699. %% \small
  18700. %% \[
  18701. %% \begin{array}{lcl}
  18702. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18703. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18704. %% \end{array}
  18705. %% \]
  18706. %% \end{minipage}
  18707. %% }
  18708. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18709. %% \label{fig:Lgrad-prime-syntax}
  18710. %% \end{figure}
  18711. \begin{figure}[tbp]
  18712. \begin{tcolorbox}[colback=white]
  18713. {\if\edition\racketEd
  18714. \begin{lstlisting}
  18715. (define (map [f : (Integer -> Integer)]
  18716. [v : (Vector Integer Integer)])
  18717. : (Vector Integer Integer)
  18718. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18719. (define (inc x) (+ x 1))
  18720. (define (true) #t)
  18721. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18722. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18723. \end{lstlisting}
  18724. \fi}
  18725. {\if\edition\pythonEd\pythonColor
  18726. \begin{lstlisting}
  18727. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18728. return f(v[0]), f(v[1])
  18729. def inc(x):
  18730. return x + 1
  18731. def true():
  18732. return True
  18733. def maybe_inc(x):
  18734. return inc(x) if input_int() == 0 else true()
  18735. t = map(maybe_inc, (0, 41))
  18736. print( t[1] )
  18737. \end{lstlisting}
  18738. \fi}
  18739. \end{tcolorbox}
  18740. \caption{A variant of the \code{map} example with an error.}
  18741. \label{fig:map-maybe_inc}
  18742. \end{figure}
  18743. Running this program with input \code{1} triggers an
  18744. error when the \code{maybe\_inc} function returns
  18745. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18746. performs checking at runtime to ensure the integrity of the static
  18747. types, such as the
  18748. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18749. annotation on
  18750. parameter \code{f} of \code{map}.
  18751. Here we give a preview of how the runtime checking is accomplished;
  18752. the following sections provide the details.
  18753. The runtime checking is carried out by a new \code{Cast} AST node that
  18754. is generated in a new pass named \code{cast\_insert}. The output of
  18755. \code{cast\_insert} is a program in the \LangCast{} language, which
  18756. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18757. %
  18758. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18759. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18760. inserted every time the type checker encounters two types that are
  18761. consistent but not equal. In the \code{inc} function, \code{x} is
  18762. cast to \INTTY{} and the result of the \code{+} is cast to
  18763. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18764. is cast from
  18765. \racket{\code{(Any -> Any)}}
  18766. \python{\code{Callable[[Any], Any]}}
  18767. to
  18768. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18769. %
  18770. In the next section we see how to interpret the \code{Cast} node.
  18771. \begin{figure}[btp]
  18772. \begin{tcolorbox}[colback=white]
  18773. {\if\edition\racketEd
  18774. \begin{lstlisting}
  18775. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  18776. : (Vector Integer Integer)
  18777. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18778. (define (inc [x : Any]) : Any
  18779. (cast (+ (cast x Any Integer) 1) Integer Any))
  18780. (define (true) : Any (cast #t Boolean Any))
  18781. (define (maybe_inc [x : Any]) : Any
  18782. (if (eq? 0 (read)) (inc x) (true)))
  18783. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  18784. (vector 0 41)) 0)
  18785. \end{lstlisting}
  18786. \fi}
  18787. {\if\edition\pythonEd\pythonColor
  18788. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18789. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18790. return f(v[0]), f(v[1])
  18791. def inc(x : Any) -> Any:
  18792. return Cast(Cast(x, Any, int) + 1, int, Any)
  18793. def true() -> Any:
  18794. return Cast(True, bool, Any)
  18795. def maybe_inc(x : Any) -> Any:
  18796. return inc(x) if input_int() == 0 else true()
  18797. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  18798. (0, 41))
  18799. print(t[1])
  18800. \end{lstlisting}
  18801. \fi}
  18802. \end{tcolorbox}
  18803. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  18804. and \code{maybe\_inc} example.}
  18805. \label{fig:map-cast}
  18806. \end{figure}
  18807. {\if\edition\pythonEd\pythonColor
  18808. \begin{figure}[tbp]
  18809. \begin{tcolorbox}[colback=white]
  18810. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18811. class TypeCheckLgrad(TypeCheckLlambda):
  18812. def type_check_exp(self, e, env) -> Type:
  18813. match e:
  18814. case Name(id):
  18815. return env[id]
  18816. case Constant(value) if isinstance(value, bool):
  18817. return BoolType()
  18818. case Constant(value) if isinstance(value, int):
  18819. return IntType()
  18820. case Call(Name('input_int'), []):
  18821. return IntType()
  18822. case BinOp(left, op, right):
  18823. left_type = self.type_check_exp(left, env)
  18824. self.check_consistent(left_type, IntType(), left)
  18825. right_type = self.type_check_exp(right, env)
  18826. self.check_consistent(right_type, IntType(), right)
  18827. return IntType()
  18828. case IfExp(test, body, orelse):
  18829. test_t = self.type_check_exp(test, env)
  18830. self.check_consistent(test_t, BoolType(), test)
  18831. body_t = self.type_check_exp(body, env)
  18832. orelse_t = self.type_check_exp(orelse, env)
  18833. self.check_consistent(body_t, orelse_t, e)
  18834. return self.join_types(body_t, orelse_t)
  18835. case Call(func, args):
  18836. func_t = self.type_check_exp(func, env)
  18837. args_t = [self.type_check_exp(arg, env) for arg in args]
  18838. match func_t:
  18839. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  18840. for (arg_t, param_t) in zip(args_t, params_t):
  18841. self.check_consistent(param_t, arg_t, e)
  18842. return return_t
  18843. case AnyType():
  18844. return AnyType()
  18845. case _:
  18846. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  18847. ...
  18848. case _:
  18849. raise Exception('type_check_exp: unexpected ' + repr(e))
  18850. \end{lstlisting}
  18851. \end{tcolorbox}
  18852. \caption{Type checking expressions in the \LangGrad{} language.}
  18853. \label{fig:type-check-Lgradual-1}
  18854. \end{figure}
  18855. \begin{figure}[tbp]
  18856. \begin{tcolorbox}[colback=white]
  18857. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18858. def check_exp(self, e, expected_ty, env):
  18859. match e:
  18860. case Lambda(params, body):
  18861. match expected_ty:
  18862. case FunctionType(params_t, return_t):
  18863. new_env = env.copy().update(zip(params, params_t))
  18864. e.has_type = expected_ty
  18865. body_ty = self.type_check_exp(body, new_env)
  18866. self.check_consistent(body_ty, return_t)
  18867. case AnyType():
  18868. new_env = env.copy().update((p, AnyType()) for p in params)
  18869. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  18870. body_ty = self.type_check_exp(body, new_env)
  18871. case _:
  18872. raise Exception('lambda does not have type ' + str(expected_ty))
  18873. case _:
  18874. e_ty = self.type_check_exp(e, env)
  18875. self.check_consistent(e_ty, expected_ty, e)
  18876. \end{lstlisting}
  18877. \end{tcolorbox}
  18878. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  18879. \label{fig:type-check-Lgradual-2}
  18880. \end{figure}
  18881. \begin{figure}[tbp]
  18882. \begin{tcolorbox}[colback=white]
  18883. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18884. def type_check_stmt(self, s, env, return_type):
  18885. match s:
  18886. case Assign([Name(id)], value):
  18887. value_ty = self.type_check_exp(value, env)
  18888. if id in env:
  18889. self.check_consistent(env[id], value_ty, value)
  18890. else:
  18891. env[id] = value_ty
  18892. ...
  18893. case _:
  18894. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  18895. def type_check_stmts(self, ss, env, return_type):
  18896. for s in ss:
  18897. self.type_check_stmt(s, env, return_type)
  18898. \end{lstlisting}
  18899. \end{tcolorbox}
  18900. \caption{Type checking statements in the \LangGrad{} language.}
  18901. \label{fig:type-check-Lgradual-3}
  18902. \end{figure}
  18903. \begin{figure}[tbp]
  18904. \begin{tcolorbox}[colback=white]
  18905. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18906. def join_types(self, t1, t2):
  18907. match (t1, t2):
  18908. case (AnyType(), _):
  18909. return t2
  18910. case (_, AnyType()):
  18911. return t1
  18912. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18913. return FunctionType(list(map(self.join_types, ps1, ps2)),
  18914. self.join_types(rt1,rt2))
  18915. case (TupleType(ts1), TupleType(ts2)):
  18916. return TupleType(list(map(self.join_types, ts1, ts2)))
  18917. case (_, _):
  18918. return t1
  18919. def check_consistent(self, t1, t2, e):
  18920. if not self.consistent(t1, t2):
  18921. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  18922. + ' in ' + repr(e))
  18923. \end{lstlisting}
  18924. \end{tcolorbox}
  18925. \caption{Auxiliary methods for type checking \LangGrad{}.}
  18926. \label{fig:type-check-Lgradual-aux}
  18927. \end{figure}
  18928. \fi}
  18929. {\if\edition\racketEd
  18930. \begin{figure}[tbp]
  18931. \begin{tcolorbox}[colback=white]
  18932. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18933. (define/override (type-check-exp env)
  18934. (lambda (e)
  18935. (define recur (type-check-exp env))
  18936. (match e
  18937. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  18938. (define-values (new-es ts)
  18939. (for/lists (exprs types) ([e es])
  18940. (recur e)))
  18941. (define t-ret (type-check-op op ts e))
  18942. (values (Prim op new-es) t-ret)]
  18943. [(Prim 'eq? (list e1 e2))
  18944. (define-values (e1^ t1) (recur e1))
  18945. (define-values (e2^ t2) (recur e2))
  18946. (check-consistent? t1 t2 e)
  18947. (define T (meet t1 t2))
  18948. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  18949. [(Prim 'and (list e1 e2))
  18950. (recur (If e1 e2 (Bool #f)))]
  18951. [(Prim 'or (list e1 e2))
  18952. (define tmp (gensym 'tmp))
  18953. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18954. [(If e1 e2 e3)
  18955. (define-values (e1^ T1) (recur e1))
  18956. (define-values (e2^ T2) (recur e2))
  18957. (define-values (e3^ T3) (recur e3))
  18958. (check-consistent? T1 'Boolean e)
  18959. (check-consistent? T2 T3 e)
  18960. (define Tif (meet T2 T3))
  18961. (values (If e1^ e2^ e3^) Tif)]
  18962. [(SetBang x e1)
  18963. (define-values (e1^ T1) (recur e1))
  18964. (define varT (dict-ref env x))
  18965. (check-consistent? T1 varT e)
  18966. (values (SetBang x e1^) 'Void)]
  18967. [(WhileLoop e1 e2)
  18968. (define-values (e1^ T1) (recur e1))
  18969. (check-consistent? T1 'Boolean e)
  18970. (define-values (e2^ T2) ((type-check-exp env) e2))
  18971. (values (WhileLoop e1^ e2^) 'Void)]
  18972. [(Prim 'vector-length (list e1))
  18973. (define-values (e1^ t) (recur e1))
  18974. (match t
  18975. [`(Vector ,ts ...)
  18976. (values (Prim 'vector-length (list e1^)) 'Integer)]
  18977. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  18978. \end{lstlisting}
  18979. \end{tcolorbox}
  18980. \caption{Type checker for the \LangGrad{} language, part 1.}
  18981. \label{fig:type-check-Lgradual-1}
  18982. \end{figure}
  18983. \begin{figure}[tbp]
  18984. \begin{tcolorbox}[colback=white]
  18985. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18986. [(Prim 'vector-ref (list e1 e2))
  18987. (define-values (e1^ t1) (recur e1))
  18988. (define-values (e2^ t2) (recur e2))
  18989. (check-consistent? t2 'Integer e)
  18990. (match t1
  18991. [`(Vector ,ts ...)
  18992. (match e2^
  18993. [(Int i)
  18994. (unless (and (0 . <= . i) (i . < . (length ts)))
  18995. (error 'type-check "invalid index ~a in ~a" i e))
  18996. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  18997. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  18998. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  18999. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19000. [(Prim 'vector-set! (list e1 e2 e3) )
  19001. (define-values (e1^ t1) (recur e1))
  19002. (define-values (e2^ t2) (recur e2))
  19003. (define-values (e3^ t3) (recur e3))
  19004. (check-consistent? t2 'Integer e)
  19005. (match t1
  19006. [`(Vector ,ts ...)
  19007. (match e2^
  19008. [(Int i)
  19009. (unless (and (0 . <= . i) (i . < . (length ts)))
  19010. (error 'type-check "invalid index ~a in ~a" i e))
  19011. (check-consistent? (list-ref ts i) t3 e)
  19012. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19013. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19014. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19015. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19016. [(Apply e1 e2s)
  19017. (define-values (e1^ T1) (recur e1))
  19018. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19019. (match T1
  19020. [`(,T1ps ... -> ,T1rt)
  19021. (for ([T2 T2s] [Tp T1ps])
  19022. (check-consistent? T2 Tp e))
  19023. (values (Apply e1^ e2s^) T1rt)]
  19024. [`Any (values (Apply e1^ e2s^) 'Any)]
  19025. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19026. [(Lambda params Tr e1)
  19027. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19028. (match p
  19029. [`[,x : ,T] (values x T)]
  19030. [(? symbol? x) (values x 'Any)])))
  19031. (define-values (e1^ T1)
  19032. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19033. (check-consistent? Tr T1 e)
  19034. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19035. `(,@Ts -> ,Tr))]
  19036. [else ((super type-check-exp env) e)]
  19037. )))
  19038. \end{lstlisting}
  19039. \end{tcolorbox}
  19040. \caption{Type checker for the \LangGrad{} language, part 2.}
  19041. \label{fig:type-check-Lgradual-2}
  19042. \end{figure}
  19043. \begin{figure}[tbp]
  19044. \begin{tcolorbox}[colback=white]
  19045. \begin{lstlisting}
  19046. (define/override (type-check-def env)
  19047. (lambda (e)
  19048. (match e
  19049. [(Def f params rt info body)
  19050. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19051. (match p
  19052. [`[,x : ,T] (values x T)]
  19053. [(? symbol? x) (values x 'Any)])))
  19054. (define new-env (append (map cons xs ps) env))
  19055. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19056. (check-consistent? ty^ rt e)
  19057. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19058. [else (error 'type-check "ill-formed function definition ~a" e)]
  19059. )))
  19060. (define/override (type-check-program e)
  19061. (match e
  19062. [(Program info body)
  19063. (define-values (body^ ty) ((type-check-exp '()) body))
  19064. (check-consistent? ty 'Integer e)
  19065. (ProgramDefsExp info '() body^)]
  19066. [(ProgramDefsExp info ds body)
  19067. (define new-env (for/list ([d ds])
  19068. (cons (Def-name d) (fun-def-type d))))
  19069. (define ds^ (for/list ([d ds])
  19070. ((type-check-def new-env) d)))
  19071. (define-values (body^ ty) ((type-check-exp new-env) body))
  19072. (check-consistent? ty 'Integer e)
  19073. (ProgramDefsExp info ds^ body^)]
  19074. [else (super type-check-program e)]))
  19075. \end{lstlisting}
  19076. \end{tcolorbox}
  19077. \caption{Type checker for the \LangGrad{} language, part 3.}
  19078. \label{fig:type-check-Lgradual-3}
  19079. \end{figure}
  19080. \begin{figure}[tbp]
  19081. \begin{tcolorbox}[colback=white]
  19082. \begin{lstlisting}
  19083. (define/public (join t1 t2)
  19084. (match* (t1 t2)
  19085. [('Integer 'Integer) 'Integer]
  19086. [('Boolean 'Boolean) 'Boolean]
  19087. [('Void 'Void) 'Void]
  19088. [('Any t2) t2]
  19089. [(t1 'Any) t1]
  19090. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19091. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19092. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19093. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19094. -> ,(join rt1 rt2))]))
  19095. (define/public (meet t1 t2)
  19096. (match* (t1 t2)
  19097. [('Integer 'Integer) 'Integer]
  19098. [('Boolean 'Boolean) 'Boolean]
  19099. [('Void 'Void) 'Void]
  19100. [('Any t2) 'Any]
  19101. [(t1 'Any) 'Any]
  19102. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19103. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19104. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19105. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19106. -> ,(meet rt1 rt2))]))
  19107. (define/public (check-consistent? t1 t2 e)
  19108. (unless (consistent? t1 t2)
  19109. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19110. (define explicit-prim-ops
  19111. (set-union
  19112. (type-predicates)
  19113. (set 'procedure-arity 'eq? 'not 'and 'or
  19114. 'vector 'vector-length 'vector-ref 'vector-set!
  19115. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19116. (define/override (fun-def-type d)
  19117. (match d
  19118. [(Def f params rt info body)
  19119. (define ps
  19120. (for/list ([p params])
  19121. (match p
  19122. [`[,x : ,T] T]
  19123. [(? symbol?) 'Any]
  19124. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19125. `(,@ps -> ,rt)]
  19126. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19127. \end{lstlisting}
  19128. \end{tcolorbox}
  19129. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19130. \label{fig:type-check-Lgradual-aux}
  19131. \end{figure}
  19132. \fi}
  19133. \clearpage
  19134. \section{Interpreting \LangCast{}}
  19135. \label{sec:interp-casts}
  19136. The runtime behavior of casts involving simple types such as
  19137. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19138. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19139. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19140. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19141. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19142. operator, by checking the value's tag and either retrieving
  19143. the underlying integer or signaling an error if the tag is not the
  19144. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19145. %
  19146. Things get more interesting with casts involving
  19147. \racket{function and tuple types}\python{function, tuple, and array types}.
  19148. Consider the cast of the function \code{maybe\_inc} from
  19149. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19150. to
  19151. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19152. shown in figure~\ref{fig:map-maybe_inc}.
  19153. When the \code{maybe\_inc} function flows through
  19154. this cast at runtime, we don't know whether it will return
  19155. an integer, because that depends on the input from the user.
  19156. The \LangCast{} interpreter therefore delays the checking
  19157. of the cast until the function is applied. To do so it
  19158. wraps \code{maybe\_inc} in a new function that casts its parameter
  19159. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19160. casts the return value from \CANYTY{} to \INTTY{}.
  19161. {\if\edition\pythonEd\pythonColor
  19162. %
  19163. There are further complications regarding casts on mutable data
  19164. such as the \code{list} type introduced in
  19165. the challenge assignment of section~\ref{sec:arrays}.
  19166. %
  19167. \fi}
  19168. %
  19169. Consider the example presented in figure~\ref{fig:map-bang} that
  19170. defines a partially typed version of \code{map} whose parameter
  19171. \code{v} has type
  19172. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19173. and that updates \code{v} in place
  19174. instead of returning a new tuple. We name this function
  19175. \code{map\_inplace}. We apply \code{map\_inplace} to
  19176. \racket{a tuple}\python{an array} of integers, so the type checker
  19177. inserts a cast from
  19178. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19179. to
  19180. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19181. A naive way for the \LangCast{} interpreter to cast between
  19182. \racket{tuple}\python{array} types would be to build a new
  19183. \racket{tuple}\python{array} whose elements are the result
  19184. of casting each of the original elements to the appropriate target
  19185. type. However, this approach is not valid for mutable data structures.
  19186. In the example of figure~\ref{fig:map-bang},
  19187. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19188. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19189. the original one.
  19190. \begin{figure}[tbp]
  19191. \begin{tcolorbox}[colback=white]
  19192. % gradual_test_11.rkt
  19193. {\if\edition\racketEd
  19194. \begin{lstlisting}
  19195. (define (map_inplace [f : (Any -> Any)]
  19196. [v : (Vector Any Any)]) : Void
  19197. (begin
  19198. (vector-set! v 0 (f (vector-ref v 0)))
  19199. (vector-set! v 1 (f (vector-ref v 1)))))
  19200. (define (inc x) (+ x 1))
  19201. (let ([v (vector 0 41)])
  19202. (begin (map_inplace inc v) (vector-ref v 1)))
  19203. \end{lstlisting}
  19204. \fi}
  19205. {\if\edition\pythonEd\pythonColor
  19206. \begin{lstlisting}
  19207. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19208. i = 0
  19209. while i != len(v):
  19210. v[i] = f(v[i])
  19211. i = i + 1
  19212. def inc(x : int) -> int:
  19213. return x + 1
  19214. v = [0, 41]
  19215. map_inplace(inc, v)
  19216. print( v[1] )
  19217. \end{lstlisting}
  19218. \fi}
  19219. \end{tcolorbox}
  19220. \caption{An example involving casts on arrays.}
  19221. \label{fig:map-bang}
  19222. \end{figure}
  19223. Instead the interpreter needs to create a new kind of value, a
  19224. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19225. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19226. and then applies a
  19227. cast to the resulting value. On a write, the proxy casts the argument
  19228. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19229. \racket{
  19230. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19231. \code{0} from \INTTY{} to \CANYTY{}.
  19232. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19233. from \CANYTY{} to \INTTY{}.
  19234. }
  19235. \python{
  19236. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19237. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19238. For the subscript on the left of the assignment,
  19239. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19240. }
  19241. Finally we consider casts between the \CANYTY{} type and higher-order types
  19242. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19243. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19244. have a type annotation, so it is given type \CANYTY{}. In the call to
  19245. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19246. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19247. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19248. \code{Inject}, but that doesn't work because
  19249. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19250. a flat type. Instead, we must first cast to
  19251. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19252. and then inject to \CANYTY{}.
  19253. \begin{figure}[tbp]
  19254. \begin{tcolorbox}[colback=white]
  19255. {\if\edition\racketEd
  19256. \begin{lstlisting}
  19257. (define (map_inplace [f : (Any -> Any)] v) : Void
  19258. (begin
  19259. (vector-set! v 0 (f (vector-ref v 0)))
  19260. (vector-set! v 1 (f (vector-ref v 1)))))
  19261. (define (inc x) (+ x 1))
  19262. (let ([v (vector 0 41)])
  19263. (begin (map_inplace inc v) (vector-ref v 1)))
  19264. \end{lstlisting}
  19265. \fi}
  19266. {\if\edition\pythonEd\pythonColor
  19267. \begin{lstlisting}
  19268. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19269. i = 0
  19270. while i != len(v):
  19271. v[i] = f(v[i])
  19272. i = i + 1
  19273. def inc(x):
  19274. return x + 1
  19275. v = [0, 41]
  19276. map_inplace(inc, v)
  19277. print( v[1] )
  19278. \end{lstlisting}
  19279. \fi}
  19280. \end{tcolorbox}
  19281. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19282. \label{fig:map-any}
  19283. \end{figure}
  19284. \begin{figure}[tbp]
  19285. \begin{tcolorbox}[colback=white]
  19286. {\if\edition\racketEd
  19287. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19288. (define/public (apply_cast v s t)
  19289. (match* (s t)
  19290. [(t1 t2) #:when (equal? t1 t2) v]
  19291. [('Any t2)
  19292. (match t2
  19293. [`(,ts ... -> ,rt)
  19294. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19295. (define v^ (apply-project v any->any))
  19296. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19297. [`(Vector ,ts ...)
  19298. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19299. (define v^ (apply-project v vec-any))
  19300. (apply_cast v^ vec-any `(Vector ,@ts))]
  19301. [else (apply-project v t2)])]
  19302. [(t1 'Any)
  19303. (match t1
  19304. [`(,ts ... -> ,rt)
  19305. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19306. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19307. (apply-inject v^ (any-tag any->any))]
  19308. [`(Vector ,ts ...)
  19309. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19310. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19311. (apply-inject v^ (any-tag vec-any))]
  19312. [else (apply-inject v (any-tag t1))])]
  19313. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19314. (define x (gensym 'x))
  19315. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19316. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19317. (define cast-writes
  19318. (for/list ([t1 ts1] [t2 ts2])
  19319. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19320. `(vector-proxy ,(vector v (apply vector cast-reads)
  19321. (apply vector cast-writes)))]
  19322. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19323. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19324. `(function ,xs ,(Cast
  19325. (Apply (Value v)
  19326. (for/list ([x xs][t1 ts1][t2 ts2])
  19327. (Cast (Var x) t2 t1)))
  19328. rt1 rt2) ())]
  19329. ))
  19330. \end{lstlisting}
  19331. \fi}
  19332. {\if\edition\pythonEd\pythonColor
  19333. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19334. def apply_cast(self, value, src, tgt):
  19335. match (src, tgt):
  19336. case (AnyType(), FunctionType(ps2, rt2)):
  19337. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19338. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19339. case (AnyType(), TupleType(ts2)):
  19340. anytup = TupleType([AnyType() for t1 in ts2])
  19341. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19342. case (AnyType(), ListType(t2)):
  19343. anylist = ListType([AnyType() for t1 in ts2])
  19344. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19345. case (AnyType(), AnyType()):
  19346. return value
  19347. case (AnyType(), _):
  19348. return self.apply_project(value, tgt)
  19349. case (FunctionType(ps1,rt1), AnyType()):
  19350. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19351. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19352. case (TupleType(ts1), AnyType()):
  19353. anytup = TupleType([AnyType() for t1 in ts1])
  19354. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19355. case (ListType(t1), AnyType()):
  19356. anylist = ListType(AnyType())
  19357. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19358. case (_, AnyType()):
  19359. return self.apply_inject(value, src)
  19360. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19361. params = [generate_name('x') for p in ps2]
  19362. args = [Cast(Name(x), t2, t1)
  19363. for (x,t1,t2) in zip(params, ps1, ps2)]
  19364. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19365. return Function('cast', params, [Return(body)], {})
  19366. case (TupleType(ts1), TupleType(ts2)):
  19367. x = generate_name('x')
  19368. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19369. for (t1,t2) in zip(ts1,ts2)]
  19370. return ProxiedTuple(value, reads)
  19371. case (ListType(t1), ListType(t2)):
  19372. x = generate_name('x')
  19373. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19374. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19375. return ProxiedList(value, read, write)
  19376. case (t1, t2) if t1 == t2:
  19377. return value
  19378. case (t1, t2):
  19379. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19380. def apply_inject(self, value, src):
  19381. return Tagged(value, self.type_to_tag(src))
  19382. def apply_project(self, value, tgt):
  19383. match value:
  19384. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19385. return val
  19386. case _:
  19387. raise Exception('apply_project, unexpected ' + repr(value))
  19388. \end{lstlisting}
  19389. \fi}
  19390. \end{tcolorbox}
  19391. \caption{The \code{apply\_cast} auxiliary method.}
  19392. \label{fig:apply_cast}
  19393. \end{figure}
  19394. The \LangCast{} interpreter uses an auxiliary function named
  19395. \code{apply\_cast} to cast a value from a source type to a target type,
  19396. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19397. the kinds of casts that we've discussed in this section.
  19398. %
  19399. The definition of the interpreter for \LangCast{} is shown in
  19400. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19401. dispatching to \code{apply\_cast}.
  19402. \racket{To handle the addition of tuple
  19403. proxies, we update the tuple primitives in \code{interp-op} using the
  19404. functions given in figure~\ref{fig:guarded-tuple}.}
  19405. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19406. \begin{figure}[tbp]
  19407. \begin{tcolorbox}[colback=white]
  19408. {\if\edition\racketEd
  19409. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19410. (define interp-Lcast-class
  19411. (class interp-Llambda-class
  19412. (super-new)
  19413. (inherit apply-fun apply-inject apply-project)
  19414. (define/override (interp-op op)
  19415. (match op
  19416. ['vector-length guarded-vector-length]
  19417. ['vector-ref guarded-vector-ref]
  19418. ['vector-set! guarded-vector-set!]
  19419. ['any-vector-ref (lambda (v i)
  19420. (match v [`(tagged ,v^ ,tg)
  19421. (guarded-vector-ref v^ i)]))]
  19422. ['any-vector-set! (lambda (v i a)
  19423. (match v [`(tagged ,v^ ,tg)
  19424. (guarded-vector-set! v^ i a)]))]
  19425. ['any-vector-length (lambda (v)
  19426. (match v [`(tagged ,v^ ,tg)
  19427. (guarded-vector-length v^)]))]
  19428. [else (super interp-op op)]
  19429. ))
  19430. (define/override ((interp-exp env) e)
  19431. (define (recur e) ((interp-exp env) e))
  19432. (match e
  19433. [(Value v) v]
  19434. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19435. [else ((super interp-exp env) e)]))
  19436. ))
  19437. (define (interp-Lcast p)
  19438. (send (new interp-Lcast-class) interp-program p))
  19439. \end{lstlisting}
  19440. \fi}
  19441. {\if\edition\pythonEd\pythonColor
  19442. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19443. class InterpLcast(InterpLany):
  19444. def interp_exp(self, e, env):
  19445. match e:
  19446. case Cast(value, src, tgt):
  19447. v = self.interp_exp(value, env)
  19448. return self.apply_cast(v, src, tgt)
  19449. case ValueExp(value):
  19450. return value
  19451. ...
  19452. case _:
  19453. return super().interp_exp(e, env)
  19454. \end{lstlisting}
  19455. \fi}
  19456. \end{tcolorbox}
  19457. \caption{The interpreter for \LangCast{}.}
  19458. \label{fig:interp-Lcast}
  19459. \end{figure}
  19460. {\if\edition\racketEd
  19461. \begin{figure}[tbp]
  19462. \begin{tcolorbox}[colback=white]
  19463. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19464. (define (guarded-vector-ref vec i)
  19465. (match vec
  19466. [`(vector-proxy ,proxy)
  19467. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19468. (define rd (vector-ref (vector-ref proxy 1) i))
  19469. (apply-fun rd (list val) 'guarded-vector-ref)]
  19470. [else (vector-ref vec i)]))
  19471. (define (guarded-vector-set! vec i arg)
  19472. (match vec
  19473. [`(vector-proxy ,proxy)
  19474. (define wr (vector-ref (vector-ref proxy 2) i))
  19475. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19476. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19477. [else (vector-set! vec i arg)]))
  19478. (define (guarded-vector-length vec)
  19479. (match vec
  19480. [`(vector-proxy ,proxy)
  19481. (guarded-vector-length (vector-ref proxy 0))]
  19482. [else (vector-length vec)]))
  19483. \end{lstlisting}
  19484. %% {\if\edition\pythonEd\pythonColor
  19485. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19486. %% UNDER CONSTRUCTION
  19487. %% \end{lstlisting}
  19488. %% \fi}
  19489. \end{tcolorbox}
  19490. \caption{The \code{guarded-vector} auxiliary functions.}
  19491. \label{fig:guarded-tuple}
  19492. \end{figure}
  19493. \fi}
  19494. {\if\edition\pythonEd\pythonColor
  19495. \section{Overload Resolution}
  19496. \label{sec:gradual-resolution}
  19497. Recall that when we added support for arrays in
  19498. section~\ref{sec:arrays}, the syntax for the array operations were the
  19499. same as for tuple operations (for example, accessing an element, getting the
  19500. length). So we performed overload resolution, with a pass named
  19501. \code{resolve}, to separate the array and tuple operations. In
  19502. particular, we introduced the primitives \code{array\_load},
  19503. \code{array\_store}, and \code{array\_len}.
  19504. For gradual typing, we further overload these operators to work on
  19505. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19506. updated with new cases for the \CANYTY{} type, translating the element
  19507. access and length operations to the primitives \code{any\_load},
  19508. \code{any\_store}, and \code{any\_len}.
  19509. \fi}
  19510. \section{Cast Insertion}
  19511. \label{sec:gradual-insert-casts}
  19512. In our discussion of type checking of \LangGrad{}, we mentioned how
  19513. the runtime aspect of type checking is carried out by the \code{Cast}
  19514. AST node, which is added to the program by a new pass named
  19515. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19516. language. We now discuss the details of this pass.
  19517. The \code{cast\_insert} pass is closely related to the type checker
  19518. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19519. In particular, the type checker allows implicit casts between
  19520. consistent types. The job of the \code{cast\_insert} pass is to make
  19521. those casts explicit. It does so by inserting
  19522. \code{Cast} nodes into the AST.
  19523. %
  19524. For the most part, the implicit casts occur in places where the type
  19525. checker checks two types for consistency. Consider the case for
  19526. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19527. checker requires that the type of the left operand is consistent with
  19528. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19529. \code{Cast} around the left operand, converting from its type to
  19530. \INTTY{}. The story is similar for the right operand. It is not always
  19531. necessary to insert a cast, for example, if the left operand already has type
  19532. \INTTY{} then there is no need for a \code{Cast}.
  19533. Some of the implicit casts are not as straightforward. One such case
  19534. arises with the
  19535. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19536. see that the type checker requires that the two branches have
  19537. consistent types and that type of the conditional expression is the
  19538. meet of the branches' types. In the target language \LangCast{}, both
  19539. branches will need to have the same type, and that type
  19540. will be the type of the conditional expression. Thus, each branch requires
  19541. a \code{Cast} to convert from its type to the meet of the branches' types.
  19542. The case for the function call exhibits another interesting situation. If
  19543. the function expression is of type \CANYTY{}, then it needs to be cast
  19544. to a function type so that it can be used in a function call in
  19545. \LangCast{}. Which function type should it be cast to? The parameter
  19546. and return types are unknown, so we can simply use \CANYTY{} for all
  19547. of them. Furthermore, in \LangCast{} the argument types will need to
  19548. exactly match the parameter types, so we must cast all the arguments
  19549. to type \CANYTY{} (if they are not already of that type).
  19550. {\if\edition\racketEd
  19551. %
  19552. Likewise, the cases for the tuple operators \code{vector-length},
  19553. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19554. where the tuple expression is of type \CANYTY{}. Instead of
  19555. handling these situations with casts, we recommend translating
  19556. the special-purpose variants of the tuple operators that handle
  19557. tuples of type \CANYTY{}: \code{any-vector-length},
  19558. \code{any-vector-ref}, and \code{any-vector-set!}.
  19559. %
  19560. \fi}
  19561. \section{Lower Casts}
  19562. \label{sec:lower_casts}
  19563. The next step in the journey toward x86 is the \code{lower\_casts}
  19564. pass that translates the casts in \LangCast{} to the lower-level
  19565. \code{Inject} and \code{Project} operators and new operators for
  19566. proxies, extending the \LangLam{} language to \LangProxy{}.
  19567. The \LangProxy{} language can also be described as an extension of
  19568. \LangAny{}, with the addition of proxies. We recommend creating an
  19569. auxiliary function named \code{lower\_cast} that takes an expression
  19570. (in \LangCast{}), a source type, and a target type and translates it
  19571. to an expression in \LangProxy{}.
  19572. The \code{lower\_cast} function can follow a code structure similar to
  19573. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19574. the interpreter for \LangCast{}, because it must handle the same cases
  19575. as \code{apply\_cast} and it needs to mimic the behavior of
  19576. \code{apply\_cast}. The most interesting cases concern
  19577. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19578. {\if\edition\racketEd
  19579. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19580. type to another tuple type is accomplished by creating a proxy that
  19581. intercepts the operations on the underlying tuple. Here we make the
  19582. creation of the proxy explicit with the \code{vector-proxy} AST
  19583. node. It takes three arguments: the first is an expression for the
  19584. tuple, the second is a tuple of functions for casting an element that is
  19585. being read from the tuple, and the third is a tuple of functions for
  19586. casting an element that is being written to the array. You can create
  19587. the functions for reading and writing using lambda expressions. Also,
  19588. as we show in the next section, we need to differentiate these tuples
  19589. of functions from the user-created ones, so we recommend using a new
  19590. AST node named \code{raw-vector} instead of \code{vector}.
  19591. %
  19592. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19593. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19594. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19595. \fi}
  19596. {\if\edition\pythonEd\pythonColor
  19597. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19598. type to another array type is accomplished by creating a proxy that
  19599. intercepts the operations on the underlying array. Here we make the
  19600. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19601. takes fives arguments: the first is an expression for the array, the
  19602. second is a function for casting an element that is being read from
  19603. the array, the third is a function for casting an element that is
  19604. being written to the array, the fourth is the type of the underlying
  19605. array, and the fifth is the type of the proxied array. You can create
  19606. the functions for reading and writing using lambda expressions.
  19607. A cast between two tuple types can be handled in a similar manner. We
  19608. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19609. immutable, so there is no need for a function to cast the value during
  19610. a write. Because there is a separate element type for each slot in
  19611. the tuple, we need not just one function for casting during a read,
  19612. but instead a tuple of functions.
  19613. %
  19614. Also, as we show in the next section, we need to differentiate these
  19615. tuples from the user-created ones, so we recommend using a new AST
  19616. node named \code{RawTuple} instead of \code{Tuple} to create the
  19617. tuples of functions.
  19618. %
  19619. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19620. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19621. that involved casting an array of integers to an array of \CANYTY{}.
  19622. \fi}
  19623. \begin{figure}[tbp]
  19624. \begin{tcolorbox}[colback=white]
  19625. {\if\edition\racketEd
  19626. \begin{lstlisting}
  19627. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19628. (begin
  19629. (vector-set! v 0 (f (vector-ref v 0)))
  19630. (vector-set! v 1 (f (vector-ref v 1)))))
  19631. (define (inc [x : Any]) : Any
  19632. (inject (+ (project x Integer) 1) Integer))
  19633. (let ([v (vector 0 41)])
  19634. (begin
  19635. (map_inplace inc (vector-proxy v
  19636. (raw-vector (lambda: ([x9 : Integer]) : Any
  19637. (inject x9 Integer))
  19638. (lambda: ([x9 : Integer]) : Any
  19639. (inject x9 Integer)))
  19640. (raw-vector (lambda: ([x9 : Any]) : Integer
  19641. (project x9 Integer))
  19642. (lambda: ([x9 : Any]) : Integer
  19643. (project x9 Integer)))))
  19644. (vector-ref v 1)))
  19645. \end{lstlisting}
  19646. \fi}
  19647. {\if\edition\pythonEd\pythonColor
  19648. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19649. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19650. i = 0
  19651. while i != array_len(v):
  19652. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19653. i = (i + 1)
  19654. def inc(x : int) -> int:
  19655. return (x + 1)
  19656. def main() -> int:
  19657. v = [0, 41]
  19658. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19659. print(array_load(v, 1))
  19660. return 0
  19661. \end{lstlisting}
  19662. \fi}
  19663. \end{tcolorbox}
  19664. \caption{Output of \code{lower\_casts} on the example shown in
  19665. figure~\ref{fig:map-bang}.}
  19666. \label{fig:map-bang-lower-cast}
  19667. \end{figure}
  19668. A cast from one function type to another function type is accomplished
  19669. by generating a \code{lambda} whose parameter and return types match
  19670. the target function type. The body of the \code{lambda} should cast
  19671. the parameters from the target type to the source type. (Yes,
  19672. backward! Functions are contravariant\index{subject}{contravariant}
  19673. in the parameters.) Afterward, call the underlying function and then
  19674. cast the result from the source return type to the target return type.
  19675. Figure~\ref{fig:map-lower-cast} shows the output of the
  19676. \code{lower\_casts} pass on the \code{map} example give in
  19677. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19678. call to \code{map} is wrapped in a \code{lambda}.
  19679. \begin{figure}[tbp]
  19680. \begin{tcolorbox}[colback=white]
  19681. {\if\edition\racketEd
  19682. \begin{lstlisting}
  19683. (define (map [f : (Integer -> Integer)]
  19684. [v : (Vector Integer Integer)])
  19685. : (Vector Integer Integer)
  19686. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19687. (define (inc [x : Any]) : Any
  19688. (inject (+ (project x Integer) 1) Integer))
  19689. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19690. (project (inc (inject x9 Integer)) Integer))
  19691. (vector 0 41)) 1)
  19692. \end{lstlisting}
  19693. \fi}
  19694. {\if\edition\pythonEd\pythonColor
  19695. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19696. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19697. return (f(v[0]), f(v[1]),)
  19698. def inc(x : any) -> any:
  19699. return inject((project(x, int) + 1), int)
  19700. def main() -> int:
  19701. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19702. print(t[1])
  19703. return 0
  19704. \end{lstlisting}
  19705. \fi}
  19706. \end{tcolorbox}
  19707. \caption{Output of \code{lower\_casts} on the example shown in
  19708. figure~\ref{fig:gradual-map}.}
  19709. \label{fig:map-lower-cast}
  19710. \end{figure}
  19711. \section{Differentiate Proxies}
  19712. \label{sec:differentiate-proxies}
  19713. So far, the responsibility of differentiating tuples and tuple proxies
  19714. has been the job of the interpreter.
  19715. %
  19716. \racket{For example, the interpreter for \LangCast{} implements
  19717. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19718. figure~\ref{fig:guarded-tuple}.}
  19719. %
  19720. In the \code{differentiate\_proxies} pass we shift this responsibility
  19721. to the generated code.
  19722. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19723. we used the type \TUPLETYPENAME{} for both
  19724. real tuples and tuple proxies.
  19725. \python{Similarly, we use the type \code{list} for both arrays and
  19726. array proxies.}
  19727. In \LangPVec{} we return the
  19728. \TUPLETYPENAME{} type to its original
  19729. meaning, as the type of just tuples, and we introduce a new type,
  19730. \PTUPLETYNAME{}, whose values
  19731. can be either real tuples or tuple
  19732. proxies.
  19733. %
  19734. {\if\edition\pythonEd\pythonColor
  19735. Likewise, we return the
  19736. \ARRAYTYPENAME{} type to its original
  19737. meaning, as the type of arrays, and we introduce a new type,
  19738. \PARRAYTYNAME{}, whose values
  19739. can be either arrays or array proxies.
  19740. These new types come with a suite of new primitive operations.
  19741. \fi}
  19742. {\if\edition\racketEd
  19743. A tuple proxy is represented by a tuple containing three things: (1) the
  19744. underlying tuple, (2) a tuple of functions for casting elements that
  19745. are read from the tuple, and (3) a tuple of functions for casting
  19746. values to be written to the tuple. So, we define the following
  19747. abbreviation for the type of a tuple proxy:
  19748. \[
  19749. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19750. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19751. \]
  19752. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19753. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19754. %
  19755. Next we describe each of the new primitive operations.
  19756. \begin{description}
  19757. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19758. (\key{PVector} $T \ldots$)]\ \\
  19759. %
  19760. This operation brands a vector as a value of the \code{PVector} type.
  19761. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19762. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19763. %
  19764. This operation brands a vector proxy as value of the \code{PVector} type.
  19765. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19766. \BOOLTY{}] \ \\
  19767. %
  19768. This returns true if the value is a tuple proxy and false if it is a
  19769. real tuple.
  19770. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  19771. (\key{Vector} $T \ldots$)]\ \\
  19772. %
  19773. Assuming that the input is a tuple, this operation returns the
  19774. tuple.
  19775. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  19776. $\to$ \BOOLTY{}]\ \\
  19777. %
  19778. Given a tuple proxy, this operation returns the length of the tuple.
  19779. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  19780. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  19781. %
  19782. Given a tuple proxy, this operation returns the $i$th element of the
  19783. tuple.
  19784. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  19785. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  19786. Given a tuple proxy, this operation writes a value to the $i$th element
  19787. of the tuple.
  19788. \end{description}
  19789. \fi}
  19790. {\if\edition\pythonEd\pythonColor
  19791. %
  19792. A tuple proxy is represented by a tuple containing 1) the underlying
  19793. tuple and 2) a tuple of functions for casting elements that are read
  19794. from the tuple. The \LangPVec{} language includes the following AST
  19795. classes and primitive functions.
  19796. \begin{description}
  19797. \item[\code{InjectTuple}] \ \\
  19798. %
  19799. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  19800. \item[\code{InjectTupleProxy}]\ \\
  19801. %
  19802. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  19803. \item[\code{is\_tuple\_proxy}]\ \\
  19804. %
  19805. This primitive returns true if the value is a tuple proxy and false
  19806. if it is a tuple.
  19807. \item[\code{project\_tuple}]\ \\
  19808. %
  19809. Converts a tuple that is branded as \PTUPLETYNAME{}
  19810. back to a tuple.
  19811. \item[\code{proxy\_tuple\_len}]\ \\
  19812. %
  19813. Given a tuple proxy, returns the length of the underlying tuple.
  19814. \item[\code{proxy\_tuple\_load}]\ \\
  19815. %
  19816. Given a tuple proxy, returns the $i$th element of the underlying
  19817. tuple.
  19818. \end{description}
  19819. An array proxy is represented by a tuple containing 1) the underlying
  19820. array, 2) a function for casting elements that are read from the
  19821. array, and 3) a function for casting elements that are written to the
  19822. array. The \LangPVec{} language includes the following AST classes
  19823. and primitive functions.
  19824. \begin{description}
  19825. \item[\code{InjectList}]\ \\
  19826. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  19827. \item[\code{InjectListProxy}]\ \\
  19828. %
  19829. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  19830. \item[\code{is\_array\_proxy}]\ \\
  19831. %
  19832. Returns true if the value is a array proxy and false if it is an
  19833. array.
  19834. \item[\code{project\_array}]\ \\
  19835. %
  19836. Converts an array that is branded as \PARRAYTYNAME{} back to an
  19837. array.
  19838. \item[\code{proxy\_array\_len}]\ \\
  19839. %
  19840. Given a array proxy, returns the length of the underlying array.
  19841. \item[\code{proxy\_array\_load}]\ \\
  19842. %
  19843. Given a array proxy, returns the $i$th element of the underlying
  19844. array.
  19845. \item[\code{proxy\_array\_store}]\ \\
  19846. %
  19847. Given an array proxy, writes a value to the $i$th element of the
  19848. underlying array.
  19849. \end{description}
  19850. \fi}
  19851. Now we discuss the translation that differentiates tuples and arrays
  19852. from proxies. First, every type annotation in the program is
  19853. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  19854. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  19855. places. For example, we wrap every tuple creation with an
  19856. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  19857. %
  19858. {\if\edition\racketEd
  19859. \begin{minipage}{0.96\textwidth}
  19860. \begin{lstlisting}
  19861. (vector |$e_1 \ldots e_n$|)
  19862. |$\Rightarrow$|
  19863. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  19864. \end{lstlisting}
  19865. \end{minipage}
  19866. \fi}
  19867. {\if\edition\pythonEd\pythonColor
  19868. \begin{lstlisting}
  19869. Tuple(|$e_1, \ldots, e_n$|)
  19870. |$\Rightarrow$|
  19871. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  19872. \end{lstlisting}
  19873. \fi}
  19874. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  19875. AST node that we introduced in the previous
  19876. section does not get injected.
  19877. {\if\edition\racketEd
  19878. \begin{lstlisting}
  19879. (raw-vector |$e_1 \ldots e_n$|)
  19880. |$\Rightarrow$|
  19881. (vector |$e'_1 \ldots e'_n$|)
  19882. \end{lstlisting}
  19883. \fi}
  19884. {\if\edition\pythonEd\pythonColor
  19885. \begin{lstlisting}
  19886. RawTuple(|$e_1, \ldots, e_n$|)
  19887. |$\Rightarrow$|
  19888. Tuple(|$e'_1, \ldots, e'_n$|)
  19889. \end{lstlisting}
  19890. \fi}
  19891. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  19892. translates as follows:
  19893. %
  19894. {\if\edition\racketEd
  19895. \begin{lstlisting}
  19896. (vector-proxy |$e_1~e_2~e_3$|)
  19897. |$\Rightarrow$|
  19898. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  19899. \end{lstlisting}
  19900. \fi}
  19901. {\if\edition\pythonEd\pythonColor
  19902. \begin{lstlisting}
  19903. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  19904. |$\Rightarrow$|
  19905. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  19906. \end{lstlisting}
  19907. \fi}
  19908. We translate the element access operations into conditional
  19909. expressions that check whether the value is a proxy and then dispatch
  19910. to either the appropriate proxy tuple operation or the regular tuple
  19911. operation.
  19912. {\if\edition\racketEd
  19913. \begin{lstlisting}
  19914. (vector-ref |$e_1$| |$i$|)
  19915. |$\Rightarrow$|
  19916. (let ([|$v~e_1$|])
  19917. (if (proxy? |$v$|)
  19918. (proxy-vector-ref |$v$| |$i$|)
  19919. (vector-ref (project-vector |$v$|) |$i$|)
  19920. \end{lstlisting}
  19921. \fi}
  19922. %
  19923. Note that in the branch for a tuple, we must apply
  19924. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  19925. from the tuple.
  19926. The translation of array operations is similar to the ones for tuples.
  19927. \section{Reveal Casts}
  19928. \label{sec:reveal-casts-gradual}
  19929. {\if\edition\racketEd
  19930. Recall that the \code{reveal\_casts} pass
  19931. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  19932. \code{Inject} and \code{Project} into lower-level operations.
  19933. %
  19934. In particular, \code{Project} turns into a conditional expression that
  19935. inspects the tag and retrieves the underlying value. Here we need to
  19936. augment the translation of \code{Project} to handle the situation in which
  19937. the target type is \code{PVector}. Instead of using
  19938. \code{vector-length} we need to use \code{proxy-vector-length}.
  19939. \begin{lstlisting}
  19940. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  19941. |$\Rightarrow$|
  19942. (let |$\itm{tmp}$| |$e'$|
  19943. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  19944. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  19945. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  19946. (exit)))
  19947. \end{lstlisting}
  19948. \fi}
  19949. %
  19950. {\if\edition\pythonEd\pythonColor
  19951. Recall that the $\itm{tagof}$ function determines the bits used to
  19952. identify values of different types and it is used in the \code{reveal\_casts}
  19953. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  19954. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  19955. decimal), just like the tuple and array types.
  19956. \fi}
  19957. %
  19958. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  19959. \section{Closure Conversion}
  19960. \label{sec:closure-conversion-gradual}
  19961. The auxiliary function that translates type annotations needs to be
  19962. updated to handle the \PTUPLETYNAME{}
  19963. \racket{type}\python{and \PARRAYTYNAME{} types}.
  19964. %
  19965. Otherwise, the only other changes are adding cases that copy the new
  19966. AST nodes.
  19967. \section{Select Instructions}
  19968. \label{sec:select-instructions-gradual}
  19969. \index{subject}{select instructions}
  19970. Recall that the \code{select\_instructions} pass is responsible for
  19971. lowering the primitive operations into x86 instructions. So, we need
  19972. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  19973. to x86. To do so, the first question we need to answer is how to
  19974. differentiate between tuple and tuple proxies\python{, and likewise for
  19975. arrays and array proxies}. We need just one bit to accomplish this;
  19976. we use the bit in position $63$ of the 64-bit tag at the front of
  19977. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  19978. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  19979. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  19980. it that way.
  19981. {\if\edition\racketEd
  19982. \begin{lstlisting}
  19983. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  19984. |$\Rightarrow$|
  19985. movq |$e'_1$|, |$\itm{lhs'}$|
  19986. \end{lstlisting}
  19987. \fi}
  19988. {\if\edition\pythonEd\pythonColor
  19989. \begin{lstlisting}
  19990. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  19991. |$\Rightarrow$|
  19992. movq |$e'_1$|, |$\itm{lhs'}$|
  19993. \end{lstlisting}
  19994. \fi}
  19995. \python{The translation for \code{InjectList} is also a move instruction.}
  19996. \noindent On the other hand,
  19997. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  19998. $63$ to $1$.
  19999. %
  20000. {\if\edition\racketEd
  20001. \begin{lstlisting}
  20002. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20003. |$\Rightarrow$|
  20004. movq |$e'_1$|, %r11
  20005. movq |$(1 << 63)$|, %rax
  20006. orq 0(%r11), %rax
  20007. movq %rax, 0(%r11)
  20008. movq %r11, |$\itm{lhs'}$|
  20009. \end{lstlisting}
  20010. \fi}
  20011. {\if\edition\pythonEd\pythonColor
  20012. \begin{lstlisting}
  20013. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20014. |$\Rightarrow$|
  20015. movq |$e'_1$|, %r11
  20016. movq |$(1 << 63)$|, %rax
  20017. orq 0(%r11), %rax
  20018. movq %rax, 0(%r11)
  20019. movq %r11, |$\itm{lhs'}$|
  20020. \end{lstlisting}
  20021. \fi}
  20022. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20023. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20024. The \racket{\code{proxy?} operation consumes}%
  20025. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20026. consume}
  20027. the information so carefully stashed away by the injections. It
  20028. isolates bit $63$ to tell whether the value is a proxy.
  20029. %
  20030. {\if\edition\racketEd
  20031. \begin{lstlisting}
  20032. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20033. |$\Rightarrow$|
  20034. movq |$e_1'$|, %r11
  20035. movq 0(%r11), %rax
  20036. sarq $63, %rax
  20037. andq $1, %rax
  20038. movq %rax, |$\itm{lhs'}$|
  20039. \end{lstlisting}
  20040. \fi}%
  20041. %
  20042. {\if\edition\pythonEd\pythonColor
  20043. \begin{lstlisting}
  20044. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20045. |$\Rightarrow$|
  20046. movq |$e_1'$|, %r11
  20047. movq 0(%r11), %rax
  20048. sarq $63, %rax
  20049. andq $1, %rax
  20050. movq %rax, |$\itm{lhs'}$|
  20051. \end{lstlisting}
  20052. \fi}%
  20053. %
  20054. The \racket{\code{project-vector} operation is}
  20055. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20056. straightforward to translate, so we leave that to the reader.
  20057. Regarding the element access operations for tuples\python{ and arrays}, the
  20058. runtime provides procedures that implement them (they are recursive
  20059. functions!), so here we simply need to translate these tuple
  20060. operations into the appropriate function call. For example, here is
  20061. the translation for
  20062. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20063. {\if\edition\racketEd
  20064. \begin{minipage}{0.96\textwidth}
  20065. \begin{lstlisting}
  20066. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20067. |$\Rightarrow$|
  20068. movq |$e_1'$|, %rdi
  20069. movq |$e_2'$|, %rsi
  20070. callq proxy_vector_ref
  20071. movq %rax, |$\itm{lhs'}$|
  20072. \end{lstlisting}
  20073. \end{minipage}
  20074. \fi}
  20075. {\if\edition\pythonEd\pythonColor
  20076. \begin{lstlisting}
  20077. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20078. |$\Rightarrow$|
  20079. movq |$e_1'$|, %rdi
  20080. movq |$e_2'$|, %rsi
  20081. callq proxy_vector_ref
  20082. movq %rax, |$\itm{lhs'}$|
  20083. \end{lstlisting}
  20084. \fi}
  20085. {\if\edition\pythonEd\pythonColor
  20086. % TODO: revisit the names vecof for python -Jeremy
  20087. We translate
  20088. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20089. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20090. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20091. \fi}
  20092. We have another batch of operations to deal with: those for the
  20093. \CANYTY{} type. Recall that we generate an
  20094. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20095. there is a element access on something of type \CANYTY{}, and
  20096. similarly for
  20097. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20098. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20099. section~\ref{sec:select-Lany} we selected instructions for these
  20100. operations on the basis of the idea that the underlying value was a tuple or
  20101. array. But in the current setting, the underlying value is of type
  20102. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20103. functions to deal with this:
  20104. \code{proxy\_vector\_ref},
  20105. \code{proxy\_vector\_set}, and
  20106. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20107. to determine whether the value is a proxy, and then
  20108. dispatches to the the appropriate code.
  20109. %
  20110. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20111. can be translated as follows.
  20112. We begin by projecting the underlying value out of the tagged value and
  20113. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20114. {\if\edition\racketEd
  20115. \begin{lstlisting}
  20116. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  20117. |$\Rightarrow$|
  20118. movq |$\neg 111$|, %rdi
  20119. andq |$e_1'$|, %rdi
  20120. movq |$e_2'$|, %rsi
  20121. callq proxy_vector_ref
  20122. movq %rax, |$\itm{lhs'}$|
  20123. \end{lstlisting}
  20124. \fi}
  20125. {\if\edition\pythonEd\pythonColor
  20126. \begin{lstlisting}
  20127. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20128. |$\Rightarrow$|
  20129. movq |$\neg 111$|, %rdi
  20130. andq |$e_1'$|, %rdi
  20131. movq |$e_2'$|, %rsi
  20132. callq proxy_vector_ref
  20133. movq %rax, |$\itm{lhs'}$|
  20134. \end{lstlisting}
  20135. \fi}
  20136. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20137. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20138. are translated in a similar way. Alternatively, you could generate
  20139. instructions to open-code
  20140. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20141. and \code{proxy\_vector\_length} functions.
  20142. \begin{exercise}\normalfont\normalsize
  20143. Implement a compiler for the gradually typed \LangGrad{} language by
  20144. extending and adapting your compiler for \LangLam{}. Create ten new
  20145. partially typed test programs. In addition to testing with these
  20146. new programs, test your compiler on all the tests for \LangLam{}
  20147. and for \LangDyn{}.
  20148. %
  20149. \racket{Sometimes you may get a type checking error on the
  20150. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20151. the \CANYTY{} type around each subexpression that has caused a type
  20152. error. Although \LangDyn{} does not have explicit casts, you can
  20153. induce one by wrapping the subexpression \code{e} with a call to
  20154. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20155. %
  20156. \python{Sometimes you may get a type checking error on the
  20157. \LangDyn{} programs but you can adapt them by inserting a
  20158. temporary variable of type \CANYTY{} that is initialized with the
  20159. troublesome expression.}
  20160. \end{exercise}
  20161. \begin{figure}[p]
  20162. \begin{tcolorbox}[colback=white]
  20163. {\if\edition\racketEd
  20164. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20165. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20166. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20167. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20168. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20169. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20170. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20171. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20172. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20173. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20174. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20175. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20176. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20177. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20178. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20179. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20180. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20181. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20182. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20183. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20184. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20185. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20186. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20187. \path[->,bend left=15] (Lgradual) edge [above] node
  20188. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20189. \path[->,bend left=15] (Lgradual2) edge [above] node
  20190. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20191. \path[->,bend left=15] (Lgradual3) edge [above] node
  20192. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20193. \path[->,bend left=15] (Lgradual4) edge [left] node
  20194. {\ttfamily\footnotesize shrink} (Lgradualr);
  20195. \path[->,bend left=15] (Lgradualr) edge [above] node
  20196. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20197. \path[->,bend right=15] (Lgradualp) edge [above] node
  20198. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20199. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20200. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20201. \path[->,bend right=15] (Llambdapp) edge [above] node
  20202. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20203. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20204. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20205. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20206. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20207. \path[->,bend left=15] (F1-2) edge [above] node
  20208. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20209. \path[->,bend left=15] (F1-3) edge [left] node
  20210. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20211. \path[->,bend left=15] (F1-4) edge [below] node
  20212. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20213. \path[->,bend right=15] (F1-5) edge [above] node
  20214. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20215. \path[->,bend right=15] (F1-6) edge [above] node
  20216. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20217. \path[->,bend right=15] (C3-2) edge [right] node
  20218. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20219. \path[->,bend right=15] (x86-2) edge [right] node
  20220. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20221. \path[->,bend right=15] (x86-2-1) edge [below] node
  20222. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20223. \path[->,bend right=15] (x86-2-2) edge [right] node
  20224. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20225. \path[->,bend left=15] (x86-3) edge [above] node
  20226. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20227. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20228. \end{tikzpicture}
  20229. \fi}
  20230. {\if\edition\pythonEd\pythonColor
  20231. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20232. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20233. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20234. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20235. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20236. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20237. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20238. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20239. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20240. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20241. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20242. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20243. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20244. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20245. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20246. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20247. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20248. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20249. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20250. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20251. \path[->,bend left=15] (Lgradual) edge [above] node
  20252. {\ttfamily\footnotesize shrink} (Lgradual2);
  20253. \path[->,bend left=15] (Lgradual2) edge [above] node
  20254. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20255. \path[->,bend left=15] (Lgradual3) edge [above] node
  20256. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20257. \path[->,bend left=15] (Lgradual4) edge [left] node
  20258. {\ttfamily\footnotesize resolve} (Lgradualr);
  20259. \path[->,bend left=15] (Lgradualr) edge [below] node
  20260. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20261. \path[->,bend right=15] (Lgradualp) edge [above] node
  20262. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20263. \path[->,bend right=15] (Llambdapp) edge [above] node
  20264. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20265. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20266. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20267. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20268. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20269. \path[->,bend left=15] (F1-1) edge [above] node
  20270. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20271. \path[->,bend left=15] (F1-2) edge [above] node
  20272. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20273. \path[->,bend left=15] (F1-3) edge [right] node
  20274. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20275. \path[->,bend right=15] (F1-5) edge [above] node
  20276. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20277. \path[->,bend right=15] (F1-6) edge [above] node
  20278. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20279. \path[->,bend right=15] (C3-2) edge [right] node
  20280. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20281. \path[->,bend right=15] (x86-2) edge [below] node
  20282. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20283. \path[->,bend right=15] (x86-3) edge [below] node
  20284. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20285. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20286. \end{tikzpicture}
  20287. \fi}
  20288. \end{tcolorbox}
  20289. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20290. \label{fig:Lgradual-passes}
  20291. \end{figure}
  20292. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20293. needed for the compilation of \LangGrad{}.
  20294. \section{Further Reading}
  20295. This chapter just scratches the surface of gradual typing. The basic
  20296. approach described here is missing two key ingredients that one would
  20297. want in a implementation of gradual typing: blame
  20298. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20299. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20300. problem addressed by blame tracking is that when a cast on a
  20301. higher-order value fails, it often does so at a point in the program
  20302. that is far removed from the original cast. Blame tracking is a
  20303. technique for propagating extra information through casts and proxies
  20304. so that when a cast fails, the error message can point back to the
  20305. original location of the cast in the source program.
  20306. The problem addressed by space-efficient casts also relates to
  20307. higher-order casts. It turns out that in partially typed programs, a
  20308. function or tuple can flow through a great many casts at runtime. With
  20309. the approach described in this chapter, each cast adds another
  20310. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20311. considerable space, but it also makes the function calls and tuple
  20312. operations slow. For example, a partially typed version of quicksort
  20313. could, in the worst case, build a chain of proxies of length $O(n)$
  20314. around the tuple, changing the overall time complexity of the
  20315. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20316. solution to this problem by representing casts using the coercion
  20317. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20318. long chains of proxies by compressing them into a concise normal
  20319. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20320. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20321. the Grift compiler:
  20322. \begin{center}
  20323. \url{https://github.com/Gradual-Typing/Grift}
  20324. \end{center}
  20325. There are also interesting interactions between gradual typing and
  20326. other language features, such as generics, information-flow types, and
  20327. type inference, to name a few. We recommend to the reader the
  20328. online gradual typing bibliography for more material:
  20329. \begin{center}
  20330. \url{http://samth.github.io/gradual-typing-bib/}
  20331. \end{center}
  20332. % TODO: challenge problem:
  20333. % type analysis and type specialization?
  20334. % coercions?
  20335. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20336. \chapter{Generics}
  20337. \label{ch:Lpoly}
  20338. \setcounter{footnote}{0}
  20339. This chapter studies the compilation of
  20340. generics\index{subject}{generics} (aka parametric
  20341. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20342. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20343. enable programmers to make code more reusable by parameterizing
  20344. functions and data structures with respect to the types on which they
  20345. operate. For example, figure~\ref{fig:map-poly} revisits the
  20346. \code{map} example and this time gives it a more fitting type. This
  20347. \code{map} function is parameterized with respect to the element type
  20348. of the tuple. The type of \code{map} is the following generic type
  20349. specified by the \code{All} type with parameter \code{T}:
  20350. {\if\edition\racketEd
  20351. \begin{lstlisting}
  20352. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20353. \end{lstlisting}
  20354. \fi}
  20355. {\if\edition\pythonEd\pythonColor
  20356. \begin{lstlisting}
  20357. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20358. \end{lstlisting}
  20359. \fi}
  20360. %
  20361. The idea is that \code{map} can be used at \emph{all} choices of a
  20362. type for parameter \code{T}. In the example shown in
  20363. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20364. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20365. \code{T}, but we could have just as well applied \code{map} to a tuple
  20366. of Booleans.
  20367. %
  20368. A \emph{monomorphic} function is simply one that is not generic.
  20369. %
  20370. We use the term \emph{instantiation} for the process (within the
  20371. language implementation) of turning a generic function into a
  20372. monomorphic one, where the type parameters have been replaced by
  20373. types.
  20374. {\if\edition\pythonEd\pythonColor
  20375. %
  20376. In Python, when writing a generic function such as \code{map}, one
  20377. does not explicitly write down its generic type (using \code{All}).
  20378. Instead, the fact that it is generic is implied by the use of type
  20379. variables (such as \code{T}) in the type annotations of its
  20380. parameters.
  20381. %
  20382. \fi}
  20383. \begin{figure}[tbp]
  20384. % poly_test_2.rkt
  20385. \begin{tcolorbox}[colback=white]
  20386. {\if\edition\racketEd
  20387. \begin{lstlisting}
  20388. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20389. (define (map f v)
  20390. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20391. (define (inc [x : Integer]) : Integer (+ x 1))
  20392. (vector-ref (map inc (vector 0 41)) 1)
  20393. \end{lstlisting}
  20394. \fi}
  20395. {\if\edition\pythonEd\pythonColor
  20396. \begin{lstlisting}
  20397. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20398. return (f(tup[0]), f(tup[1]))
  20399. def add1(x : int) -> int:
  20400. return x + 1
  20401. t = map(add1, (0, 41))
  20402. print(t[1])
  20403. \end{lstlisting}
  20404. \fi}
  20405. \end{tcolorbox}
  20406. \caption{A generic version of the \code{map} function.}
  20407. \label{fig:map-poly}
  20408. \end{figure}
  20409. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20410. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20411. shows the definition of the abstract syntax.
  20412. %
  20413. {\if\edition\racketEd
  20414. We add a second form for function definitions in which a type
  20415. declaration comes before the \code{define}. In the abstract syntax,
  20416. the return type in the \code{Def} is \CANYTY{}, but that should be
  20417. ignored in favor of the return type in the type declaration. (The
  20418. \CANYTY{} comes from using the same parser as discussed in
  20419. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20420. enables the use of an \code{All} type for a function, thereby making
  20421. it generic.
  20422. \fi}
  20423. %
  20424. The grammar for types is extended to include the type of a generic
  20425. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20426. abstract syntax)}.
  20427. \newcommand{\LpolyGrammarRacket}{
  20428. \begin{array}{lcl}
  20429. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20430. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20431. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20432. \end{array}
  20433. }
  20434. \newcommand{\LpolyASTRacket}{
  20435. \begin{array}{lcl}
  20436. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20437. \Def &::=& \DECL{\Var}{\Type} \\
  20438. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20439. \end{array}
  20440. }
  20441. \newcommand{\LpolyGrammarPython}{
  20442. \begin{array}{lcl}
  20443. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20444. \end{array}
  20445. }
  20446. \newcommand{\LpolyASTPython}{
  20447. \begin{array}{lcl}
  20448. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20449. \MID \key{GenericVar}\LP\Var\RP
  20450. \end{array}
  20451. }
  20452. \begin{figure}[tp]
  20453. \centering
  20454. \begin{tcolorbox}[colback=white]
  20455. \footnotesize
  20456. {\if\edition\racketEd
  20457. \[
  20458. \begin{array}{l}
  20459. \gray{\LintGrammarRacket{}} \\ \hline
  20460. \gray{\LvarGrammarRacket{}} \\ \hline
  20461. \gray{\LifGrammarRacket{}} \\ \hline
  20462. \gray{\LwhileGrammarRacket} \\ \hline
  20463. \gray{\LtupGrammarRacket} \\ \hline
  20464. \gray{\LfunGrammarRacket} \\ \hline
  20465. \gray{\LlambdaGrammarRacket} \\ \hline
  20466. \LpolyGrammarRacket \\
  20467. \begin{array}{lcl}
  20468. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20469. \end{array}
  20470. \end{array}
  20471. \]
  20472. \fi}
  20473. {\if\edition\pythonEd\pythonColor
  20474. \[
  20475. \begin{array}{l}
  20476. \gray{\LintGrammarPython{}} \\ \hline
  20477. \gray{\LvarGrammarPython{}} \\ \hline
  20478. \gray{\LifGrammarPython{}} \\ \hline
  20479. \gray{\LwhileGrammarPython} \\ \hline
  20480. \gray{\LtupGrammarPython} \\ \hline
  20481. \gray{\LfunGrammarPython} \\ \hline
  20482. \gray{\LlambdaGrammarPython} \\\hline
  20483. \LpolyGrammarPython \\
  20484. \begin{array}{lcl}
  20485. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20486. \end{array}
  20487. \end{array}
  20488. \]
  20489. \fi}
  20490. \end{tcolorbox}
  20491. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20492. (figure~\ref{fig:Llam-concrete-syntax}).}
  20493. \label{fig:Lpoly-concrete-syntax}
  20494. \end{figure}
  20495. \begin{figure}[tp]
  20496. \centering
  20497. \begin{tcolorbox}[colback=white]
  20498. \footnotesize
  20499. {\if\edition\racketEd
  20500. \[
  20501. \begin{array}{l}
  20502. \gray{\LintOpAST} \\ \hline
  20503. \gray{\LvarASTRacket{}} \\ \hline
  20504. \gray{\LifASTRacket{}} \\ \hline
  20505. \gray{\LwhileASTRacket{}} \\ \hline
  20506. \gray{\LtupASTRacket{}} \\ \hline
  20507. \gray{\LfunASTRacket} \\ \hline
  20508. \gray{\LlambdaASTRacket} \\ \hline
  20509. \LpolyASTRacket \\
  20510. \begin{array}{lcl}
  20511. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20512. \end{array}
  20513. \end{array}
  20514. \]
  20515. \fi}
  20516. {\if\edition\pythonEd\pythonColor
  20517. \[
  20518. \begin{array}{l}
  20519. \gray{\LintASTPython} \\ \hline
  20520. \gray{\LvarASTPython{}} \\ \hline
  20521. \gray{\LifASTPython{}} \\ \hline
  20522. \gray{\LwhileASTPython{}} \\ \hline
  20523. \gray{\LtupASTPython{}} \\ \hline
  20524. \gray{\LfunASTPython} \\ \hline
  20525. \gray{\LlambdaASTPython} \\ \hline
  20526. \LpolyASTPython \\
  20527. \begin{array}{lcl}
  20528. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20529. \end{array}
  20530. \end{array}
  20531. \]
  20532. \fi}
  20533. \end{tcolorbox}
  20534. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20535. (figure~\ref{fig:Llam-syntax}).}
  20536. \label{fig:Lpoly-syntax}
  20537. \end{figure}
  20538. By including the \code{All} type in the $\Type$ nonterminal of the
  20539. grammar we choose to make generics first class, which has interesting
  20540. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20541. not include syntax for the \code{All} type. It is inferred for functions whose
  20542. type annotations contain type variables.} Many languages with generics, such as
  20543. C++~\citep{stroustrup88:_param_types} and Standard
  20544. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20545. may be helpful to see an example of first-class generics in action. In
  20546. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20547. whose parameter is a generic function. Indeed, because the grammar for
  20548. $\Type$ includes the \code{All} type, a generic function may also be
  20549. returned from a function or stored inside a tuple. The body of
  20550. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20551. and also to an integer, which would not be possible if \code{f} were
  20552. not generic.
  20553. \begin{figure}[tbp]
  20554. \begin{tcolorbox}[colback=white]
  20555. {\if\edition\racketEd
  20556. \begin{lstlisting}
  20557. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20558. (define (apply_twice f)
  20559. (if (f #t) (f 42) (f 777)))
  20560. (: id (All (T) (T -> T)))
  20561. (define (id x) x)
  20562. (apply_twice id)
  20563. \end{lstlisting}
  20564. \fi}
  20565. {\if\edition\pythonEd\pythonColor
  20566. \begin{lstlisting}
  20567. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20568. if f(True):
  20569. return f(42)
  20570. else:
  20571. return f(777)
  20572. def id(x: T) -> T:
  20573. return x
  20574. print(apply_twice(id))
  20575. \end{lstlisting}
  20576. \fi}
  20577. \end{tcolorbox}
  20578. \caption{An example illustrating first-class generics.}
  20579. \label{fig:apply-twice}
  20580. \end{figure}
  20581. The type checker for \LangPoly{} shown in
  20582. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20583. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20584. {\if\edition\pythonEd\pythonColor
  20585. %
  20586. Regarding function definitions, if the type annotations on its
  20587. parameters contain generic variables, then the function is generic and
  20588. therefore its type is an \code{All} type wrapped around a function
  20589. type. Otherwise the function is monomorphic and its type is simply
  20590. a function type.
  20591. %
  20592. \fi}
  20593. The type checking of a function application is extended to handle the
  20594. case in which the operator expression is a generic function. In that case
  20595. the type arguments are deduced by matching the types of the parameters
  20596. with the types of the arguments.
  20597. %
  20598. The \code{match\_types} auxiliary function
  20599. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20600. recursively descending through a parameter type \code{param\_ty} and
  20601. the corresponding argument type \code{arg\_ty}, making sure that they
  20602. are equal except when there is a type parameter in the parameter
  20603. type. Upon encountering a type parameter for the first time, the
  20604. algorithm deduces an association of the type parameter to the
  20605. corresponding part of the argument type. If it is not the first time
  20606. that the type parameter has been encountered, the algorithm looks up
  20607. its deduced type and makes sure that it is equal to the corresponding
  20608. part of the argument type. The return type of the application is the
  20609. return type of the generic function with the type parameters
  20610. replaced by the deduced type arguments, using the
  20611. \code{substitute\_type} auxiliary function, which is also listed in
  20612. figure~\ref{fig:type-check-Lpoly-aux}.
  20613. The type checker extends type equality to handle the \code{All} type.
  20614. This is not quite as simple as for other types, such as function and
  20615. tuple types, because two \code{All} types can be syntactically
  20616. different even though they are equivalent. For example,
  20617. \begin{center}
  20618. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20619. \end{center}
  20620. is equivalent to
  20621. \begin{center}
  20622. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20623. \end{center}
  20624. Two generic types are equal if they differ only in
  20625. the choice of the names of the type parameters. The definition of type
  20626. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20627. parameters in one type to match the type parameters of the other type.
  20628. {\if\edition\racketEd
  20629. %
  20630. The type checker also ensures that only defined type variables appear
  20631. in type annotations. The \code{check\_well\_formed} function for which
  20632. the definition is shown in figure~\ref{fig:well-formed-types}
  20633. recursively inspects a type, making sure that each type variable has
  20634. been defined.
  20635. %
  20636. \fi}
  20637. \begin{figure}[tbp]
  20638. \begin{tcolorbox}[colback=white]
  20639. {\if\edition\racketEd
  20640. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20641. (define type-check-poly-class
  20642. (class type-check-Llambda-class
  20643. (super-new)
  20644. (inherit check-type-equal?)
  20645. (define/override (type-check-apply env e1 es)
  20646. (define-values (e^ ty) ((type-check-exp env) e1))
  20647. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20648. ((type-check-exp env) e)))
  20649. (match ty
  20650. [`(,ty^* ... -> ,rt)
  20651. (for ([arg-ty ty*] [param-ty ty^*])
  20652. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20653. (values e^ es^ rt)]
  20654. [`(All ,xs (,tys ... -> ,rt))
  20655. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20656. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20657. (match_types env^^ param-ty arg-ty)))
  20658. (define targs
  20659. (for/list ([x xs])
  20660. (match (dict-ref env^^ x (lambda () #f))
  20661. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20662. x (Apply e1 es))]
  20663. [ty ty])))
  20664. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20665. [else (error 'type-check "expected a function, not ~a" ty)]))
  20666. (define/override ((type-check-exp env) e)
  20667. (match e
  20668. [(Lambda `([,xs : ,Ts] ...) rT body)
  20669. (for ([T Ts]) ((check_well_formed env) T))
  20670. ((check_well_formed env) rT)
  20671. ((super type-check-exp env) e)]
  20672. [(HasType e1 ty)
  20673. ((check_well_formed env) ty)
  20674. ((super type-check-exp env) e)]
  20675. [else ((super type-check-exp env) e)]))
  20676. (define/override ((type-check-def env) d)
  20677. (verbose 'type-check "poly/def" d)
  20678. (match d
  20679. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20680. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20681. (for ([p ps]) ((check_well_formed ts-env) p))
  20682. ((check_well_formed ts-env) rt)
  20683. (define new-env (append ts-env (map cons xs ps) env))
  20684. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20685. (check-type-equal? ty^ rt body)
  20686. (Generic ts (Def f p:t* rt info body^))]
  20687. [else ((super type-check-def env) d)]))
  20688. (define/override (type-check-program p)
  20689. (match p
  20690. [(Program info body)
  20691. (type-check-program (ProgramDefsExp info '() body))]
  20692. [(ProgramDefsExp info ds body)
  20693. (define ds^ (combine-decls-defs ds))
  20694. (define new-env (for/list ([d ds^])
  20695. (cons (def-name d) (fun-def-type d))))
  20696. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20697. (define-values (body^ ty) ((type-check-exp new-env) body))
  20698. (check-type-equal? ty 'Integer body)
  20699. (ProgramDefsExp info ds^^ body^)]))
  20700. ))
  20701. \end{lstlisting}
  20702. \fi}
  20703. {\if\edition\pythonEd\pythonColor
  20704. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20705. def type_check_exp(self, e, env):
  20706. match e:
  20707. case Call(Name(f), args) if f in builtin_functions:
  20708. return super().type_check_exp(e, env)
  20709. case Call(func, args):
  20710. func_t = self.type_check_exp(func, env)
  20711. func.has_type = func_t
  20712. match func_t:
  20713. case AllType(ps, FunctionType(p_tys, rt)):
  20714. for arg in args:
  20715. arg.has_type = self.type_check_exp(arg, env)
  20716. arg_tys = [arg.has_type for arg in args]
  20717. deduced = {}
  20718. for (p, a) in zip(p_tys, arg_tys):
  20719. self.match_types(p, a, deduced, e)
  20720. return self.substitute_type(rt, deduced)
  20721. case _:
  20722. return super().type_check_exp(e, env)
  20723. case _:
  20724. return super().type_check_exp(e, env)
  20725. def type_check(self, p):
  20726. match p:
  20727. case Module(body):
  20728. env = {}
  20729. for s in body:
  20730. match s:
  20731. case FunctionDef(name, params, bod, dl, returns, comment):
  20732. params_t = [t for (x,t) in params]
  20733. ty_params = set()
  20734. for t in params_t:
  20735. ty_params |$\mid$|= self.generic_variables(t)
  20736. ty = FunctionType(params_t, returns)
  20737. if len(ty_params) > 0:
  20738. ty = AllType(list(ty_params), ty)
  20739. env[name] = ty
  20740. self.check_stmts(body, IntType(), env)
  20741. case _:
  20742. raise Exception('type_check: unexpected ' + repr(p))
  20743. \end{lstlisting}
  20744. \fi}
  20745. \end{tcolorbox}
  20746. \caption{Type checker for the \LangPoly{} language.}
  20747. \label{fig:type-check-Lpoly}
  20748. \end{figure}
  20749. \begin{figure}[tbp]
  20750. \begin{tcolorbox}[colback=white]
  20751. {\if\edition\racketEd
  20752. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20753. (define/override (type-equal? t1 t2)
  20754. (match* (t1 t2)
  20755. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20756. (define env (map cons xs ys))
  20757. (type-equal? (substitute_type env T1) T2)]
  20758. [(other wise)
  20759. (super type-equal? t1 t2)]))
  20760. (define/public (match_types env pt at)
  20761. (match* (pt at)
  20762. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20763. [('Void 'Void) env] [('Any 'Any) env]
  20764. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20765. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20766. (match_types env^ pt1 at1))]
  20767. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  20768. (define env^ (match_types env prt art))
  20769. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  20770. (match_types env^^ pt1 at1))]
  20771. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  20772. (define env^ (append (map cons pxs axs) env))
  20773. (match_types env^ pt1 at1)]
  20774. [((? symbol? x) at)
  20775. (match (dict-ref env x (lambda () #f))
  20776. [#f (error 'type-check "undefined type variable ~a" x)]
  20777. ['Type (cons (cons x at) env)]
  20778. [t^ (check-type-equal? at t^ 'matching) env])]
  20779. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  20780. (define/public (substitute_type env pt)
  20781. (match pt
  20782. ['Integer 'Integer] ['Boolean 'Boolean]
  20783. ['Void 'Void] ['Any 'Any]
  20784. [`(Vector ,ts ...)
  20785. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  20786. [`(,ts ... -> ,rt)
  20787. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  20788. [`(All ,xs ,t)
  20789. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  20790. [(? symbol? x) (dict-ref env x)]
  20791. [else (error 'type-check "expected a type not ~a" pt)]))
  20792. (define/public (combine-decls-defs ds)
  20793. (match ds
  20794. ['() '()]
  20795. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  20796. (unless (equal? name f)
  20797. (error 'type-check "name mismatch, ~a != ~a" name f))
  20798. (match type
  20799. [`(All ,xs (,ps ... -> ,rt))
  20800. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20801. (cons (Generic xs (Def name params^ rt info body))
  20802. (combine-decls-defs ds^))]
  20803. [`(,ps ... -> ,rt)
  20804. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20805. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  20806. [else (error 'type-check "expected a function type, not ~a" type) ])]
  20807. [`(,(Def f params rt info body) . ,ds^)
  20808. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  20809. \end{lstlisting}
  20810. \fi}
  20811. {\if\edition\pythonEd\pythonColor
  20812. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20813. def match_types(self, param_ty, arg_ty, deduced, e):
  20814. match (param_ty, arg_ty):
  20815. case (GenericVar(id), _):
  20816. if id in deduced:
  20817. self.check_type_equal(arg_ty, deduced[id], e)
  20818. else:
  20819. deduced[id] = arg_ty
  20820. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  20821. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  20822. new_arg_ty = self.substitute_type(arg_ty, rename)
  20823. self.match_types(ty, new_arg_ty, deduced, e)
  20824. case (TupleType(ps), TupleType(ts)):
  20825. for (p, a) in zip(ps, ts):
  20826. self.match_types(p, a, deduced, e)
  20827. case (ListType(p), ListType(a)):
  20828. self.match_types(p, a, deduced, e)
  20829. case (FunctionType(pps, prt), FunctionType(aps, art)):
  20830. for (pp, ap) in zip(pps, aps):
  20831. self.match_types(pp, ap, deduced, e)
  20832. self.match_types(prt, art, deduced, e)
  20833. case (IntType(), IntType()):
  20834. pass
  20835. case (BoolType(), BoolType()):
  20836. pass
  20837. case _:
  20838. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  20839. def substitute_type(self, ty, var_map):
  20840. match ty:
  20841. case GenericVar(id):
  20842. return var_map[id]
  20843. case AllType(ps, ty):
  20844. new_map = copy.deepcopy(var_map)
  20845. for p in ps:
  20846. new_map[p] = GenericVar(p)
  20847. return AllType(ps, self.substitute_type(ty, new_map))
  20848. case TupleType(ts):
  20849. return TupleType([self.substitute_type(t, var_map) for t in ts])
  20850. case ListType(ty):
  20851. return ListType(self.substitute_type(ty, var_map))
  20852. case FunctionType(pts, rt):
  20853. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  20854. self.substitute_type(rt, var_map))
  20855. case IntType():
  20856. return IntType()
  20857. case BoolType():
  20858. return BoolType()
  20859. case _:
  20860. raise Exception('substitute_type: unexpected ' + repr(ty))
  20861. def check_type_equal(self, t1, t2, e):
  20862. match (t1, t2):
  20863. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  20864. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  20865. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  20866. case (_, _):
  20867. return super().check_type_equal(t1, t2, e)
  20868. \end{lstlisting}
  20869. \fi}
  20870. \end{tcolorbox}
  20871. \caption{Auxiliary functions for type checking \LangPoly{}.}
  20872. \label{fig:type-check-Lpoly-aux}
  20873. \end{figure}
  20874. {\if\edition\racketEd
  20875. \begin{figure}[tbp]
  20876. \begin{tcolorbox}[colback=white]
  20877. \begin{lstlisting}
  20878. (define/public ((check_well_formed env) ty)
  20879. (match ty
  20880. ['Integer (void)]
  20881. ['Boolean (void)]
  20882. ['Void (void)]
  20883. [(? symbol? a)
  20884. (match (dict-ref env a (lambda () #f))
  20885. ['Type (void)]
  20886. [else (error 'type-check "undefined type variable ~a" a)])]
  20887. [`(Vector ,ts ...)
  20888. (for ([t ts]) ((check_well_formed env) t))]
  20889. [`(,ts ... -> ,t)
  20890. (for ([t ts]) ((check_well_formed env) t))
  20891. ((check_well_formed env) t)]
  20892. [`(All ,xs ,t)
  20893. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20894. ((check_well_formed env^) t)]
  20895. [else (error 'type-check "unrecognized type ~a" ty)]))
  20896. \end{lstlisting}
  20897. \end{tcolorbox}
  20898. \caption{Well-formed types.}
  20899. \label{fig:well-formed-types}
  20900. \end{figure}
  20901. \fi}
  20902. % TODO: interpreter for R'_10
  20903. \clearpage
  20904. \section{Compiling Generics}
  20905. \label{sec:compiling-poly}
  20906. Broadly speaking, there are four approaches to compiling generics, as
  20907. follows:
  20908. \begin{description}
  20909. \item[Monomorphization] generates a different version of a generic
  20910. function for each set of type arguments with which it is used,
  20911. producing type-specialized code. This approach results in the most
  20912. efficient code but requires whole-program compilation (no separate
  20913. compilation) and may increase code size. Unfortunately,
  20914. monomorphization is incompatible with first-class generics because
  20915. it is not always possible to determine which generic functions are
  20916. used with which type arguments during compilation. (It can be done
  20917. at runtime with just-in-time compilation.) Monomorphization is
  20918. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  20919. generic functions in NESL~\citep{Blelloch:1993aa} and
  20920. ML~\citep{Weeks:2006aa}.
  20921. \item[Uniform representation] generates one version of each generic
  20922. function and requires all values to have a common \emph{boxed} format,
  20923. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  20924. generic and monomorphic code is compiled similarly to code in a
  20925. dynamically typed language (like \LangDyn{}), in which primitive
  20926. operators require their arguments to be projected from \CANYTY{} and
  20927. their results to be injected into \CANYTY{}. (In object-oriented
  20928. languages, the projection is accomplished via virtual method
  20929. dispatch.) The uniform representation approach is compatible with
  20930. separate compilation and with first-class generics. However, it
  20931. produces the least efficient code because it introduces overhead in
  20932. the entire program. This approach is used in
  20933. Java~\citep{Bracha:1998fk},
  20934. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  20935. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  20936. \item[Mixed representation] generates one version of each generic
  20937. function, using a boxed representation for type variables. However,
  20938. monomorphic code is compiled as usual (as in \LangLam{}), and
  20939. conversions are performed at the boundaries between monomorphic code
  20940. and polymorphic code (for example, when a generic function is instantiated
  20941. and called). This approach is compatible with separate compilation
  20942. and first-class generics and maintains efficiency in monomorphic
  20943. code. The trade-off is increased overhead at the boundary between
  20944. monomorphic and generic code. This approach is used in
  20945. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  20946. Java 5 with the addition of autoboxing.
  20947. \item[Type passing] uses the unboxed representation in both
  20948. monomorphic and generic code. Each generic function is compiled to a
  20949. single function with extra parameters that describe the type
  20950. arguments. The type information is used by the generated code to
  20951. determine how to access the unboxed values at runtime. This approach is
  20952. used in implementation of Napier88~\citep{Morrison:1991aa} and
  20953. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  20954. compilation and first-class generics and maintains the
  20955. efficiency for monomorphic code. There is runtime overhead in
  20956. polymorphic code from dispatching on type information.
  20957. \end{description}
  20958. In this chapter we use the mixed representation approach, partly
  20959. because of its favorable attributes and partly because it is
  20960. straightforward to implement using the tools that we have already
  20961. built to support gradual typing. The work of compiling generic
  20962. functions is performed in two passes, \code{resolve} and
  20963. \code{erase\_types}, that we discuss next. The output of
  20964. \code{erase\_types} is \LangCast{}
  20965. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  20966. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  20967. \section{Resolve Instantiation}
  20968. \label{sec:generic-resolve}
  20969. Recall that the type checker for \LangPoly{} deduces the type
  20970. arguments at call sites to a generic function. The purpose of the
  20971. \code{resolve} pass is to turn this implicit instantiation into an
  20972. explicit one, by adding \code{inst} nodes to the syntax of the
  20973. intermediate language. An \code{inst} node records the mapping of
  20974. type parameters to type arguments. The semantics of the \code{inst}
  20975. node is to instantiate the result of its first argument, a generic
  20976. function, to produce a monomorphic function. However, because the
  20977. interpreter never analyzes type annotations, instantiation can be a
  20978. no-op and simply return the generic function.
  20979. %
  20980. The output language of the \code{resolve} pass is \LangInst{},
  20981. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  20982. {\if\edition\racketEd
  20983. The \code{resolve} pass combines the type declaration and polymorphic
  20984. function into a single definition, using the \code{Poly} form, to make
  20985. polymorphic functions more convenient to process in the next pass of the
  20986. compiler.
  20987. \fi}
  20988. \newcommand{\LinstASTRacket}{
  20989. \begin{array}{lcl}
  20990. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20991. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  20992. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  20993. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  20994. \end{array}
  20995. }
  20996. \newcommand{\LinstASTPython}{
  20997. \begin{array}{lcl}
  20998. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  20999. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21000. \end{array}
  21001. }
  21002. \begin{figure}[tp]
  21003. \centering
  21004. \begin{tcolorbox}[colback=white]
  21005. \small
  21006. {\if\edition\racketEd
  21007. \[
  21008. \begin{array}{l}
  21009. \gray{\LintOpAST} \\ \hline
  21010. \gray{\LvarASTRacket{}} \\ \hline
  21011. \gray{\LifASTRacket{}} \\ \hline
  21012. \gray{\LwhileASTRacket{}} \\ \hline
  21013. \gray{\LtupASTRacket{}} \\ \hline
  21014. \gray{\LfunASTRacket} \\ \hline
  21015. \gray{\LlambdaASTRacket} \\ \hline
  21016. \LinstASTRacket \\
  21017. \begin{array}{lcl}
  21018. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21019. \end{array}
  21020. \end{array}
  21021. \]
  21022. \fi}
  21023. {\if\edition\pythonEd\pythonColor
  21024. \[
  21025. \begin{array}{l}
  21026. \gray{\LintASTPython} \\ \hline
  21027. \gray{\LvarASTPython{}} \\ \hline
  21028. \gray{\LifASTPython{}} \\ \hline
  21029. \gray{\LwhileASTPython{}} \\ \hline
  21030. \gray{\LtupASTPython{}} \\ \hline
  21031. \gray{\LfunASTPython} \\ \hline
  21032. \gray{\LlambdaASTPython} \\ \hline
  21033. \LinstASTPython \\
  21034. \begin{array}{lcl}
  21035. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21036. \end{array}
  21037. \end{array}
  21038. \]
  21039. \fi}
  21040. \end{tcolorbox}
  21041. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21042. (figure~\ref{fig:Llam-syntax}).}
  21043. \label{fig:Lpoly-prime-syntax}
  21044. \end{figure}
  21045. The output of the \code{resolve} pass on the generic \code{map}
  21046. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21047. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21048. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21049. \begin{figure}[tbp]
  21050. % poly_test_2.rkt
  21051. \begin{tcolorbox}[colback=white]
  21052. {\if\edition\racketEd
  21053. \begin{lstlisting}
  21054. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21055. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21056. (define (inc [x : Integer]) : Integer (+ x 1))
  21057. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21058. (Integer))
  21059. inc (vector 0 41)) 1)
  21060. \end{lstlisting}
  21061. \fi}
  21062. {\if\edition\pythonEd\pythonColor
  21063. \begin{lstlisting}
  21064. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21065. return (f(tup[0]), f(tup[1]))
  21066. def add1(x : int) -> int:
  21067. return x + 1
  21068. t = inst(map, {T: int})(add1, (0, 41))
  21069. print(t[1])
  21070. \end{lstlisting}
  21071. \fi}
  21072. \end{tcolorbox}
  21073. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21074. \label{fig:map-resolve}
  21075. \end{figure}
  21076. \section{Erase Generic Types}
  21077. \label{sec:erase_types}
  21078. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21079. represent type variables. For example, figure~\ref{fig:map-erase}
  21080. shows the output of the \code{erase\_types} pass on the generic
  21081. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21082. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  21083. \code{All} types are removed from the type of \code{map}.
  21084. \begin{figure}[tbp]
  21085. \begin{tcolorbox}[colback=white]
  21086. {\if\edition\racketEd
  21087. \begin{lstlisting}
  21088. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21089. : (Vector Any Any)
  21090. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21091. (define (inc [x : Integer]) : Integer (+ x 1))
  21092. (vector-ref ((cast map
  21093. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21094. ((Integer -> Integer) (Vector Integer Integer)
  21095. -> (Vector Integer Integer)))
  21096. inc (vector 0 41)) 1)
  21097. \end{lstlisting}
  21098. \fi}
  21099. {\if\edition\pythonEd\pythonColor
  21100. \begin{lstlisting}
  21101. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21102. return (f(tup[0]), f(tup[1]))
  21103. def add1(x : int) -> int:
  21104. return (x + 1)
  21105. def main() -> int:
  21106. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21107. print(t[1])
  21108. return 0
  21109. \end{lstlisting}
  21110. {\small
  21111. where\\
  21112. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21113. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21114. }
  21115. \fi}
  21116. \end{tcolorbox}
  21117. \caption{The generic \code{map} example after type erasure.}
  21118. \label{fig:map-erase}
  21119. \end{figure}
  21120. This process of type erasure creates a challenge at points of
  21121. instantiation. For example, consider the instantiation of
  21122. \code{map} shown in figure~\ref{fig:map-resolve}.
  21123. The type of \code{map} is
  21124. %
  21125. {\if\edition\racketEd
  21126. \begin{lstlisting}
  21127. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21128. \end{lstlisting}
  21129. \fi}
  21130. {\if\edition\pythonEd\pythonColor
  21131. \begin{lstlisting}
  21132. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21133. \end{lstlisting}
  21134. \fi}
  21135. %
  21136. and it is instantiated to
  21137. %
  21138. {\if\edition\racketEd
  21139. \begin{lstlisting}
  21140. ((Integer -> Integer) (Vector Integer Integer)
  21141. -> (Vector Integer Integer))
  21142. \end{lstlisting}
  21143. \fi}
  21144. {\if\edition\pythonEd\pythonColor
  21145. \begin{lstlisting}
  21146. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21147. \end{lstlisting}
  21148. \fi}
  21149. %
  21150. After erasure, the type of \code{map} is
  21151. %
  21152. {\if\edition\racketEd
  21153. \begin{lstlisting}
  21154. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21155. \end{lstlisting}
  21156. \fi}
  21157. {\if\edition\pythonEd\pythonColor
  21158. \begin{lstlisting}
  21159. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21160. \end{lstlisting}
  21161. \fi}
  21162. %
  21163. but we need to convert it to the instantiated type. This is easy to
  21164. do in the language \LangCast{} with a single \code{cast}. In the
  21165. example shown in figure~\ref{fig:map-erase}, the instantiation of
  21166. \code{map} has been compiled to a \code{cast} from the type of
  21167. \code{map} to the instantiated type. The source and the target type of a
  21168. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  21169. the case because both the source and target are obtained from the same
  21170. generic type of \code{map}, replacing the type parameters with
  21171. \CANYTY{} in the former and with the deduced type arguments in the
  21172. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21173. To implement the \code{erase\_types} pass, we first recommend defining
  21174. a recursive function that translates types, named
  21175. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21176. follows.
  21177. %
  21178. {\if\edition\racketEd
  21179. \begin{lstlisting}
  21180. |$T$|
  21181. |$\Rightarrow$|
  21182. Any
  21183. \end{lstlisting}
  21184. \fi}
  21185. {\if\edition\pythonEd\pythonColor
  21186. \begin{lstlisting}
  21187. GenericVar(|$T$|)
  21188. |$\Rightarrow$|
  21189. Any
  21190. \end{lstlisting}
  21191. \fi}
  21192. %
  21193. \noindent The \code{erase\_type} function also removes the generic
  21194. \code{All} types.
  21195. %
  21196. {\if\edition\racketEd
  21197. \begin{lstlisting}
  21198. (All |$xs$| |$T_1$|)
  21199. |$\Rightarrow$|
  21200. |$T'_1$|
  21201. \end{lstlisting}
  21202. \fi}
  21203. {\if\edition\pythonEd\pythonColor
  21204. \begin{lstlisting}
  21205. AllType(|$xs$|, |$T_1$|)
  21206. |$\Rightarrow$|
  21207. |$T'_1$|
  21208. \end{lstlisting}
  21209. \fi}
  21210. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  21211. %
  21212. In this compiler pass, apply the \code{erase\_type} function to all
  21213. the type annotations in the program.
  21214. Regarding the translation of expressions, the case for \code{Inst} is
  21215. the interesting one. We translate it into a \code{Cast}, as shown
  21216. next.
  21217. The type of the subexpression $e$ is a generic type of the form
  21218. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21219. The source type of the cast is the erasure of $T$, the type $T_s$.
  21220. %
  21221. {\if\edition\racketEd
  21222. %
  21223. The target type $T_t$ is the result of substituting the argument types
  21224. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  21225. erasure.
  21226. %
  21227. \begin{lstlisting}
  21228. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21229. |$\Rightarrow$|
  21230. (Cast |$e'$| |$T_s$| |$T_t$|)
  21231. \end{lstlisting}
  21232. %
  21233. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21234. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21235. \fi}
  21236. {\if\edition\pythonEd\pythonColor
  21237. %
  21238. The target type $T_t$ is the result of substituting the deduced
  21239. argument types $d$ in $T$ followed by doing type erasure.
  21240. %
  21241. \begin{lstlisting}
  21242. Inst(|$e$|, |$d$|)
  21243. |$\Rightarrow$|
  21244. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21245. \end{lstlisting}
  21246. %
  21247. where
  21248. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21249. \fi}
  21250. Finally, each generic function is translated to a regular
  21251. function in which type erasure has been applied to all the type
  21252. annotations and the body.
  21253. %% \begin{lstlisting}
  21254. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21255. %% |$\Rightarrow$|
  21256. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21257. %% \end{lstlisting}
  21258. \begin{exercise}\normalfont\normalsize
  21259. Implement a compiler for the polymorphic language \LangPoly{} by
  21260. extending and adapting your compiler for \LangGrad{}. Create six new
  21261. test programs that use polymorphic functions. Some of them should
  21262. make use of first-class generics.
  21263. \end{exercise}
  21264. \begin{figure}[tbp]
  21265. \begin{tcolorbox}[colback=white]
  21266. {\if\edition\racketEd
  21267. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21268. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21269. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21270. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21271. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21272. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21273. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21274. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21275. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21276. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21277. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21278. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21279. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21280. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21281. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21282. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21283. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21284. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21285. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21286. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21287. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21288. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21289. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21290. \path[->,bend left=15] (Lpoly) edge [above] node
  21291. {\ttfamily\footnotesize resolve} (Lpolyp);
  21292. \path[->,bend left=15] (Lpolyp) edge [above] node
  21293. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21294. \path[->,bend left=15] (Lgradualp) edge [above] node
  21295. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21296. \path[->,bend left=15] (Llambdapp) edge [left] node
  21297. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21298. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21299. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21300. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21301. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21302. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21303. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21304. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21305. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21306. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21307. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21308. \path[->,bend left=15] (F1-1) edge [above] node
  21309. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21310. \path[->,bend left=15] (F1-2) edge [above] node
  21311. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21312. \path[->,bend left=15] (F1-3) edge [left] node
  21313. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21314. \path[->,bend left=15] (F1-4) edge [below] node
  21315. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21316. \path[->,bend right=15] (F1-5) edge [above] node
  21317. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21318. \path[->,bend right=15] (F1-6) edge [above] node
  21319. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21320. \path[->,bend right=15] (C3-2) edge [right] node
  21321. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21322. \path[->,bend right=15] (x86-2) edge [right] node
  21323. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21324. \path[->,bend right=15] (x86-2-1) edge [below] node
  21325. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21326. \path[->,bend right=15] (x86-2-2) edge [right] node
  21327. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21328. \path[->,bend left=15] (x86-3) edge [above] node
  21329. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21330. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21331. \end{tikzpicture}
  21332. \fi}
  21333. {\if\edition\pythonEd\pythonColor
  21334. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21335. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21336. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21337. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21338. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21339. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21340. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21341. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21342. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21343. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21344. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21345. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21346. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21347. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21348. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21349. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21350. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21351. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21352. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21353. \path[->,bend left=15] (Lgradual) edge [above] node
  21354. {\ttfamily\footnotesize shrink} (Lgradual2);
  21355. \path[->,bend left=15] (Lgradual2) edge [above] node
  21356. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21357. \path[->,bend left=15] (Lgradual3) edge [above] node
  21358. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21359. \path[->,bend left=15] (Lgradual4) edge [left] node
  21360. {\ttfamily\footnotesize resolve} (Lgradualr);
  21361. \path[->,bend left=15] (Lgradualr) edge [below] node
  21362. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21363. \path[->,bend right=15] (Llambdapp) edge [above] node
  21364. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21365. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21366. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21367. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21368. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21369. \path[->,bend right=15] (F1-1) edge [below] node
  21370. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21371. \path[->,bend right=15] (F1-2) edge [below] node
  21372. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21373. \path[->,bend left=15] (F1-3) edge [above] node
  21374. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21375. \path[->,bend left=15] (F1-5) edge [left] node
  21376. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21377. \path[->,bend left=5] (F1-6) edge [below] node
  21378. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21379. \path[->,bend right=15] (C3-2) edge [right] node
  21380. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21381. \path[->,bend right=15] (x86-2) edge [below] node
  21382. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21383. \path[->,bend right=15] (x86-3) edge [below] node
  21384. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21385. \path[->,bend left=15] (x86-4) edge [above] node
  21386. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21387. \end{tikzpicture}
  21388. \fi}
  21389. \end{tcolorbox}
  21390. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21391. \label{fig:Lpoly-passes}
  21392. \end{figure}
  21393. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21394. needed to compile \LangPoly{}.
  21395. % TODO: challenge problem: specialization of instantiations
  21396. % Further Reading
  21397. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21398. \clearpage
  21399. \appendix
  21400. \chapter{Appendix}
  21401. \setcounter{footnote}{0}
  21402. {\if\edition\racketEd
  21403. \section{Interpreters}
  21404. \label{appendix:interp}
  21405. \index{subject}{interpreter}
  21406. We provide interpreters for each of the source languages \LangInt{},
  21407. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21408. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21409. intermediate languages \LangCVar{} and \LangCIf{} are in
  21410. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21411. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21412. \key{interp.rkt} file.
  21413. \section{Utility Functions}
  21414. \label{appendix:utilities}
  21415. The utility functions described in this section are in the
  21416. \key{utilities.rkt} file of the support code.
  21417. \paragraph{\code{interp-tests}}
  21418. This function runs the compiler passes and the interpreters on each of
  21419. the specified tests to check whether each pass is correct. The
  21420. \key{interp-tests} function has the following parameters:
  21421. \begin{description}
  21422. \item[name (a string)] A name to identify the compiler.
  21423. \item[typechecker] A function of exactly one argument that either
  21424. raises an error using the \code{error} function when it encounters a
  21425. type error, or returns \code{\#f} when it encounters a type
  21426. error. If there is no type error, the type checker returns the
  21427. program.
  21428. \item[passes] A list with one entry per pass. An entry is a list
  21429. consisting of four things:
  21430. \begin{enumerate}
  21431. \item a string giving the name of the pass;
  21432. \item the function that implements the pass (a translator from AST
  21433. to AST);
  21434. \item a function that implements the interpreter (a function from
  21435. AST to result value) for the output language; and,
  21436. \item a type checker for the output language. Type checkers for
  21437. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21438. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21439. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21440. type checker entry is optional. The support code does not provide
  21441. type checkers for the x86 languages.
  21442. \end{enumerate}
  21443. \item[source-interp] An interpreter for the source language. The
  21444. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21445. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21446. \item[tests] A list of test numbers that specifies which tests to
  21447. run (explained next).
  21448. \end{description}
  21449. %
  21450. The \key{interp-tests} function assumes that the subdirectory
  21451. \key{tests} has a collection of Racket programs whose names all start
  21452. with the family name, followed by an underscore and then the test
  21453. number, and ending with the file extension \key{.rkt}. Also, for each test
  21454. program that calls \code{read} one or more times, there is a file with
  21455. the same name except that the file extension is \key{.in}, which
  21456. provides the input for the Racket program. If the test program is
  21457. expected to fail type checking, then there should be an empty file of
  21458. the same name with extension \key{.tyerr}.
  21459. \paragraph{\code{compiler-tests}}
  21460. This function runs the compiler passes to generate x86 (a \key{.s}
  21461. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21462. It runs the machine code and checks that the output is $42$. The
  21463. parameters to the \code{compiler-tests} function are similar to those
  21464. of the \code{interp-tests} function, and they consist of
  21465. \begin{itemize}
  21466. \item a compiler name (a string),
  21467. \item a type checker,
  21468. \item description of the passes,
  21469. \item name of a test-family, and
  21470. \item a list of test numbers.
  21471. \end{itemize}
  21472. \paragraph{\code{compile-file}}
  21473. This function takes a description of the compiler passes (see the
  21474. comment for \key{interp-tests}) and returns a function that, given a
  21475. program file name (a string ending in \key{.rkt}), applies all the
  21476. passes and writes the output to a file whose name is the same as the
  21477. program file name with extension \key{.rkt} replaced by \key{.s}.
  21478. \paragraph{\code{read-program}}
  21479. This function takes a file path and parses that file (it must be a
  21480. Racket program) into an abstract syntax tree.
  21481. \paragraph{\code{parse-program}}
  21482. This function takes an S-expression representation of an abstract
  21483. syntax tree and converts it into the struct-based representation.
  21484. \paragraph{\code{assert}}
  21485. This function takes two parameters, a string (\code{msg}) and Boolean
  21486. (\code{bool}), and displays the message \key{msg} if the Boolean
  21487. \key{bool} is false.
  21488. \paragraph{\code{lookup}}
  21489. % remove discussion of lookup? -Jeremy
  21490. This function takes a key and an alist and returns the first value that is
  21491. associated with the given key, if there is one. If not, an error is
  21492. triggered. The alist may contain both immutable pairs (built with
  21493. \key{cons}) and mutable pairs (built with \key{mcons}).
  21494. %The \key{map2} function ...
  21495. \fi} %\racketEd
  21496. \section{x86 Instruction Set Quick Reference}
  21497. \label{sec:x86-quick-reference}
  21498. \index{subject}{x86}
  21499. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21500. do. We write $A \to B$ to mean that the value of $A$ is written into
  21501. location $B$. Address offsets are given in bytes. The instruction
  21502. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21503. registers (such as \code{\%rax}), or memory references (such as
  21504. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21505. reference per instruction. Other operands must be immediates or
  21506. registers.
  21507. \begin{table}[tbp]
  21508. \centering
  21509. \begin{tabular}{l|l}
  21510. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21511. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21512. \texttt{negq} $A$ & $- A \to A$ \\
  21513. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21514. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  21515. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  21516. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$ \\
  21517. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  21518. \texttt{retq} & Pops the return address and jumps to it \\
  21519. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  21520. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  21521. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  21522. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21523. be an immediate) \\
  21524. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21525. matches the condition code of the instruction; otherwise go to the
  21526. next instructions. The condition codes are \key{e} for \emph{equal},
  21527. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21528. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21529. \texttt{jl} $L$ & \\
  21530. \texttt{jle} $L$ & \\
  21531. \texttt{jg} $L$ & \\
  21532. \texttt{jge} $L$ & \\
  21533. \texttt{jmp} $L$ & Jump to label $L$ \\
  21534. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21535. \texttt{movzbq} $A$, $B$ &
  21536. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21537. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21538. and the extra bytes of $B$ are set to zero.} \\
  21539. & \\
  21540. & \\
  21541. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  21542. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  21543. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  21544. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21545. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21546. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21547. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21548. description of the condition codes. $A$ must be a single byte register
  21549. (e.g., \texttt{al} or \texttt{cl}).} \\
  21550. \texttt{setl} $A$ & \\
  21551. \texttt{setle} $A$ & \\
  21552. \texttt{setg} $A$ & \\
  21553. \texttt{setge} $A$ &
  21554. \end{tabular}
  21555. \vspace{5pt}
  21556. \caption{Quick reference for the x86 instructions used in this book.}
  21557. \label{tab:x86-instr}
  21558. \end{table}
  21559. \backmatter
  21560. \addtocontents{toc}{\vspace{11pt}}
  21561. \cleardoublepage % needed for right page number in TOC for References
  21562. %% \nocite{*} is a way to get all the entries in the .bib file to
  21563. %% print in the bibliography:
  21564. \nocite{*}\let\bibname\refname
  21565. \addcontentsline{toc}{fmbm}{\refname}
  21566. \printbibliography
  21567. %\printindex{authors}{Author Index}
  21568. \printindex{subject}{Index}
  21569. \end{document}
  21570. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21571. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21572. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21573. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21574. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21575. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21576. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21577. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21578. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21579. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21580. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21581. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21582. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21583. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21584. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21585. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21586. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21587. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21588. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21589. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21590. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21591. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  21592. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21593. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21594. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21595. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21596. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21597. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21598. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21599. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21600. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21601. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21602. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21603. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21604. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21605. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21606. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21607. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21608. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21609. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21610. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21611. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21612. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21613. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21614. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21615. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21616. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21617. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21618. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21619. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21620. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21621. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21622. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21623. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21624. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21625. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21626. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21627. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21628. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21629. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21630. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21631. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21632. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21633. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21634. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21635. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21636. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21637. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21638. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21639. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21640. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21641. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21642. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21643. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21644. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21645. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21646. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21647. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21648. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21649. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21650. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21651. % LocalWords: pseudocode underapproximation underapproximations LALR
  21652. % LocalWords: semilattices overapproximate incrementing Earley docs
  21653. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21654. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21655. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21656. % LocalWords: LC partialevaluation pythonEd TOC