book.tex 824 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588
  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 environment. If
  2002. the variable is not in the environment (because the variable was not
  2003. defined) then the 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}).\footnote{In
  2006. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2007. prohibit access to undefined variables.}
  2008. %
  2009. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2010. initializing expression, extends the environment with the result
  2011. value bound to the variable, using \code{dict-set}, then evaluates
  2012. the body of the \key{Let}.}
  2013. %
  2014. \python{When the interpreter encounters an assignment, it evaluates
  2015. the initializing expression and then associates the resulting value
  2016. with the variable in the environment.}
  2017. \begin{figure}[tp]
  2018. \begin{tcolorbox}[colback=white]
  2019. {\if\edition\racketEd
  2020. \begin{lstlisting}
  2021. (define interp-Lint-class
  2022. (class object%
  2023. (super-new)
  2024. (define/public ((interp_exp env) e)
  2025. (match e
  2026. [(Int n) n]
  2027. [(Prim 'read '())
  2028. (define r (read))
  2029. (cond [(fixnum? r) r]
  2030. [else (error 'interp_exp "expected an integer" r)])]
  2031. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2032. [(Prim '+ (list e1 e2))
  2033. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2034. [(Prim '- (list e1 e2))
  2035. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2036. (define/public (interp_program p)
  2037. (match p
  2038. [(Program '() e) ((interp_exp '()) e)]))
  2039. ))
  2040. \end{lstlisting}
  2041. \fi}
  2042. {\if\edition\pythonEd\pythonColor
  2043. \begin{lstlisting}
  2044. class InterpLint:
  2045. def interp_exp(self, e, env):
  2046. match e:
  2047. case BinOp(left, Add(), right):
  2048. return self.interp_exp(left, env) + self.interp_exp(right, env)
  2049. case BinOp(left, Sub(), right):
  2050. return self.interp_exp(left, env) - self.interp_exp(right, env)
  2051. case UnaryOp(USub(), v):
  2052. return - self.interp_exp(v, env)
  2053. case Constant(value):
  2054. return value
  2055. case Call(Name('input_int'), []):
  2056. return int(input())
  2057. def interp_stmt(self, s, env, cont):
  2058. match s:
  2059. case Expr(Call(Name('print'), [arg])):
  2060. val = self.interp_exp(arg, env)
  2061. print(val, end='')
  2062. return self.interp_stmts(cont, env)
  2063. case Expr(value):
  2064. self.interp_exp(value, env)
  2065. return self.interp_stmts(cont, env)
  2066. case _:
  2067. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2068. def interp_stmts(self, ss, env):
  2069. if len(ss) == 0:
  2070. return None
  2071. else:
  2072. return self.interp_stmt(ss[0], env, ss[1:])
  2073. def interp(self, p):
  2074. match p:
  2075. case Module(body):
  2076. self.interp_stmts(body, {})
  2077. def interp_Lint(p):
  2078. return InterpLint().interp(p)
  2079. \end{lstlisting}
  2080. \fi}
  2081. \end{tcolorbox}
  2082. \caption{Interpreter for \LangInt{} as a class.}
  2083. \label{fig:interp-Lint-class}
  2084. \end{figure}
  2085. \begin{figure}[tp]
  2086. \begin{tcolorbox}[colback=white]
  2087. {\if\edition\racketEd
  2088. \begin{lstlisting}
  2089. (define interp-Lvar-class
  2090. (class interp-Lint-class
  2091. (super-new)
  2092. (define/override ((interp_exp env) e)
  2093. (match e
  2094. [(Var x) (dict-ref env x)]
  2095. [(Let x e body)
  2096. (define new-env (dict-set env x ((interp_exp env) e)))
  2097. ((interp_exp new-env) body)]
  2098. [else ((super interp_exp env) e)]))
  2099. ))
  2100. (define (interp_Lvar p)
  2101. (send (new interp-Lvar-class) interp_program p))
  2102. \end{lstlisting}
  2103. \fi}
  2104. {\if\edition\pythonEd\pythonColor
  2105. \begin{lstlisting}
  2106. class InterpLvar(InterpLint):
  2107. def interp_exp(self, e, env):
  2108. match e:
  2109. case Name(id):
  2110. return env[id]
  2111. case _:
  2112. return super().interp_exp(e, env)
  2113. def interp_stmt(self, s, env, cont):
  2114. match s:
  2115. case Assign([lhs], value):
  2116. env[lhs.id] = self.interp_exp(value, env)
  2117. return self.interp_stmts(cont, env)
  2118. case _:
  2119. return super().interp_stmt(s, env, cont)
  2120. def interp_Lvar(p):
  2121. return InterpLvar().interp(p)
  2122. \end{lstlisting}
  2123. \fi}
  2124. \end{tcolorbox}
  2125. \caption{Interpreter for the \LangVar{} language.}
  2126. \label{fig:interp-Lvar}
  2127. \end{figure}
  2128. {\if\edition\racketEd
  2129. \begin{figure}[tp]
  2130. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2131. \small
  2132. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2133. An \emph{association list} (called an alist) is a list of key-value pairs.
  2134. For example, we can map people to their ages with an alist
  2135. \index{subject}{alist}\index{subject}{association list}
  2136. \begin{lstlisting}[basicstyle=\ttfamily]
  2137. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2138. \end{lstlisting}
  2139. The \emph{dictionary} interface is for mapping keys to values.
  2140. Every alist implements this interface. \index{subject}{dictionary}
  2141. The package
  2142. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2143. provides many functions for working with dictionaries, such as
  2144. \begin{description}
  2145. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2146. returns the value associated with the given $\itm{key}$.
  2147. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2148. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2149. and otherwise is the same as $\itm{dict}$.
  2150. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2151. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2152. of keys and values in $\itm{dict}$. For example, the following
  2153. creates a new alist in which the ages are incremented:
  2154. \end{description}
  2155. \vspace{-10pt}
  2156. \begin{lstlisting}[basicstyle=\ttfamily]
  2157. (for/list ([(k v) (in-dict ages)])
  2158. (cons k (add1 v)))
  2159. \end{lstlisting}
  2160. \end{tcolorbox}
  2161. %\end{wrapfigure}
  2162. \caption{Association lists implement the dictionary interface.}
  2163. \label{fig:alist}
  2164. \end{figure}
  2165. \fi}
  2166. The goal for this chapter is to implement a compiler that translates
  2167. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2168. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2169. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2170. That is, they output the same integer $n$. We depict this correctness
  2171. criteria in the following diagram:
  2172. \[
  2173. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2174. \node (p1) at (0, 0) {$P_1$};
  2175. \node (p2) at (4, 0) {$P_2$};
  2176. \node (o) at (4, -2) {$n$};
  2177. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2178. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2179. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2180. \end{tikzpicture}
  2181. \]
  2182. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2183. compiling \LangVar{}.
  2184. \section{The \LangXInt{} Assembly Language}
  2185. \label{sec:x86}
  2186. \index{subject}{x86}
  2187. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2188. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2189. assembler.
  2190. %
  2191. A program begins with a \code{main} label followed by a sequence of
  2192. instructions. The \key{globl} directive makes the \key{main} procedure
  2193. externally visible so that the operating system can call it.
  2194. %
  2195. An x86 program is stored in the computer's memory. For our purposes,
  2196. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2197. values. The computer has a \emph{program counter}
  2198. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2199. \code{rip} register that points to the address of the next instruction
  2200. to be executed. For most instructions, the program counter is
  2201. incremented after the instruction is executed so that it points to the
  2202. next instruction in memory. Most x86 instructions take two operands,
  2203. each of which is an integer constant (called an \emph{immediate
  2204. value}\index{subject}{immediate value}), a
  2205. \emph{register}\index{subject}{register}, or a memory location.
  2206. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2207. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2208. && \key{r8} \MID \key{r9} \MID \key{r10}
  2209. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2210. \MID \key{r14} \MID \key{r15}}
  2211. \newcommand{\GrammarXInt}{
  2212. \begin{array}{rcl}
  2213. \Reg &::=& \allregisters{} \\
  2214. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2215. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2216. \key{subq} \; \Arg\key{,} \Arg \MID
  2217. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2218. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2219. \key{callq} \; \mathit{label} \MID
  2220. \key{retq} \MID
  2221. \key{jmp}\,\itm{label} \MID \\
  2222. && \itm{label}\key{:}\; \Instr
  2223. \end{array}
  2224. }
  2225. \begin{figure}[tp]
  2226. \begin{tcolorbox}[colback=white]
  2227. {\if\edition\racketEd
  2228. \[
  2229. \begin{array}{l}
  2230. \GrammarXInt \\
  2231. \begin{array}{lcl}
  2232. \LangXIntM{} &::= & \key{.globl main}\\
  2233. & & \key{main:} \; \Instr\ldots
  2234. \end{array}
  2235. \end{array}
  2236. \]
  2237. \fi}
  2238. {\if\edition\pythonEd\pythonColor
  2239. \[
  2240. \begin{array}{lcl}
  2241. \Reg &::=& \allregisters{} \\
  2242. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2243. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2244. \key{subq} \; \Arg\key{,} \Arg \MID
  2245. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2246. && \key{callq} \; \mathit{label} \MID
  2247. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2248. \LangXIntM{} &::= & \key{.globl main}\\
  2249. & & \key{main:} \; \Instr^{*}
  2250. \end{array}
  2251. \]
  2252. \fi}
  2253. \end{tcolorbox}
  2254. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2255. \label{fig:x86-int-concrete}
  2256. \end{figure}
  2257. A register is a special kind of variable that holds a 64-bit
  2258. value. There are 16 general-purpose registers in the computer; their
  2259. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2260. written with a percent sign, \key{\%}, followed by the register name,
  2261. for example \key{\%rax}.
  2262. An immediate value is written using the notation \key{\$}$n$ where $n$
  2263. is an integer.
  2264. %
  2265. %
  2266. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2267. which obtains the address stored in register $r$ and then adds $n$
  2268. bytes to the address. The resulting address is used to load or to store
  2269. to memory depending on whether it occurs as a source or destination
  2270. argument of an instruction.
  2271. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2272. the source $s$ and destination $d$, applies the arithmetic operation,
  2273. and then writes the result to the destination $d$. \index{subject}{instruction}
  2274. %
  2275. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2276. stores the result in $d$.
  2277. %
  2278. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2279. specified by the label, and $\key{retq}$ returns from a procedure to
  2280. its caller.
  2281. %
  2282. We discuss procedure calls in more detail further in this chapter and
  2283. in chapter~\ref{ch:Lfun}.
  2284. %
  2285. The last letter \key{q} indicates that these instructions operate on
  2286. quadwords, which are 64-bit values.
  2287. %
  2288. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2289. counter to the address of the instruction immediately after the
  2290. specified label.}
  2291. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2292. all the x86 instructions used in this book.
  2293. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2294. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2295. \lstinline{movq $10, %rax}
  2296. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2297. adds $32$ to the $10$ in \key{rax} and
  2298. puts the result, $42$, into \key{rax}.
  2299. %
  2300. The last instruction \key{retq} finishes the \key{main} function by
  2301. returning the integer in \key{rax} to the operating system. The
  2302. operating system interprets this integer as the program's exit
  2303. code. By convention, an exit code of 0 indicates that a program has
  2304. completed successfully, and all other exit codes indicate various
  2305. errors.
  2306. %
  2307. \racket{However, in this book we return the result of the program
  2308. as the exit code.}
  2309. \begin{figure}[tbp]
  2310. \begin{minipage}{0.45\textwidth}
  2311. \begin{tcolorbox}[colback=white]
  2312. \begin{lstlisting}
  2313. .globl main
  2314. main:
  2315. movq $10, %rax
  2316. addq $32, %rax
  2317. retq
  2318. \end{lstlisting}
  2319. \end{tcolorbox}
  2320. \end{minipage}
  2321. \caption{An x86 program that computes
  2322. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2323. \label{fig:p0-x86}
  2324. \end{figure}
  2325. We exhibit the use of memory for storing intermediate results in the
  2326. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2327. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2328. uses a region of memory called the \emph{procedure call stack}
  2329. (\emph{stack} for
  2330. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2331. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2332. for each procedure call. The memory layout for an individual frame is
  2333. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2334. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2335. address of the item at the top of the stack. In general, we use the
  2336. term \emph{pointer}\index{subject}{pointer} for something that
  2337. contains an address. The stack grows downward in memory, so we
  2338. increase the size of the stack by subtracting from the stack pointer.
  2339. In the context of a procedure call, the \emph{return
  2340. address}\index{subject}{return address} is the location of the
  2341. instruction that immediately follows the call instruction on the
  2342. caller side. The function call instruction, \code{callq}, pushes the
  2343. return address onto the stack prior to jumping to the procedure. The
  2344. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2345. pointer} and is used to access variables that are stored in the
  2346. frame of the current procedure call. The base pointer of the caller
  2347. is stored immediately after the return address.
  2348. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2349. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2350. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2351. $-16\key{(\%rbp)}$, and so on.
  2352. \begin{figure}[tbp]
  2353. \begin{minipage}{0.66\textwidth}
  2354. \begin{tcolorbox}[colback=white]
  2355. {\if\edition\racketEd
  2356. \begin{lstlisting}
  2357. start:
  2358. movq $10, -8(%rbp)
  2359. negq -8(%rbp)
  2360. movq -8(%rbp), %rax
  2361. addq $52, %rax
  2362. jmp conclusion
  2363. .globl main
  2364. main:
  2365. pushq %rbp
  2366. movq %rsp, %rbp
  2367. subq $16, %rsp
  2368. jmp start
  2369. conclusion:
  2370. addq $16, %rsp
  2371. popq %rbp
  2372. retq
  2373. \end{lstlisting}
  2374. \fi}
  2375. {\if\edition\pythonEd\pythonColor
  2376. \begin{lstlisting}
  2377. .globl main
  2378. main:
  2379. pushq %rbp
  2380. movq %rsp, %rbp
  2381. subq $16, %rsp
  2382. movq $10, -8(%rbp)
  2383. negq -8(%rbp)
  2384. movq -8(%rbp), %rax
  2385. addq $52, %rax
  2386. addq $16, %rsp
  2387. popq %rbp
  2388. retq
  2389. \end{lstlisting}
  2390. \fi}
  2391. \end{tcolorbox}
  2392. \end{minipage}
  2393. \caption{An x86 program that computes
  2394. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2395. \label{fig:p1-x86}
  2396. \end{figure}
  2397. \begin{figure}[tbp]
  2398. \begin{minipage}{0.66\textwidth}
  2399. \begin{tcolorbox}[colback=white]
  2400. \centering
  2401. \begin{tabular}{|r|l|} \hline
  2402. Position & Contents \\ \hline
  2403. $8$(\key{\%rbp}) & return address \\
  2404. $0$(\key{\%rbp}) & old \key{rbp} \\
  2405. $-8$(\key{\%rbp}) & variable $1$ \\
  2406. $-16$(\key{\%rbp}) & variable $2$ \\
  2407. \ldots & \ldots \\
  2408. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2409. \end{tabular}
  2410. \end{tcolorbox}
  2411. \end{minipage}
  2412. \caption{Memory layout of a frame.}
  2413. \label{fig:frame}
  2414. \end{figure}
  2415. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2416. is transferred from the operating system to the \code{main} function.
  2417. The operating system issues a \code{callq main} instruction that
  2418. pushes its return address on the stack and then jumps to
  2419. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2420. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2421. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2422. out of alignment (because the \code{callq} pushed the return address).
  2423. The first three instructions are the typical
  2424. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2425. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2426. pointer \code{rsp} and then saves the base pointer of the caller at
  2427. address \code{rsp} on the stack. The next instruction \code{movq
  2428. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2429. which is pointing to the location of the old base pointer. The
  2430. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2431. make enough room for storing variables. This program needs one
  2432. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2433. 16-byte-aligned, and then we are ready to make calls to other functions.
  2434. \racket{The last instruction of the prelude is \code{jmp start}, which
  2435. transfers control to the instructions that were generated from the
  2436. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2437. \racket{The first instruction under the \code{start} label is}
  2438. %
  2439. \python{The first instruction after the prelude is}
  2440. %
  2441. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2442. %
  2443. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2444. $1$ to $-10$.
  2445. %
  2446. The next instruction moves the $-10$ from variable $1$ into the
  2447. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2448. the value in \code{rax}, updating its contents to $42$.
  2449. \racket{The three instructions under the label \code{conclusion} are the
  2450. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2451. %
  2452. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2453. \code{main} function consists of the last three instructions.}
  2454. %
  2455. The first two restore the \code{rsp} and \code{rbp} registers to their
  2456. states at the beginning of the procedure. In particular,
  2457. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2458. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2459. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2460. \key{retq}, jumps back to the procedure that called this one and adds
  2461. $8$ to the stack pointer.
  2462. Our compiler needs a convenient representation for manipulating x86
  2463. programs, so we define an abstract syntax for x86, shown in
  2464. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2465. \LangXInt{}.
  2466. %
  2467. {\if\edition\pythonEd\pythonColor%
  2468. The main difference between this and the concrete syntax of \LangXInt{}
  2469. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2470. names, and register names are explicitly represented by strings.
  2471. \fi} %
  2472. {\if\edition\racketEd
  2473. The main difference between this and the concrete syntax of \LangXInt{}
  2474. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2475. front of every instruction. Instead instructions are grouped into
  2476. \emph{basic blocks}\index{subject}{basic block} with a
  2477. label associated with every basic block; this is why the \key{X86Program}
  2478. struct includes an alist mapping labels to basic blocks. The reason for this
  2479. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2480. introduce conditional branching. The \code{Block} structure includes
  2481. an $\itm{info}$ field that is not needed in this chapter but becomes
  2482. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2483. $\itm{info}$ field should contain an empty list.
  2484. \fi}
  2485. %
  2486. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2487. node includes an integer for representing the arity of the function,
  2488. that is, the number of arguments, which is helpful to know during
  2489. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2490. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2491. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2492. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2493. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2494. \MID \skey{r14} \MID \skey{r15}}
  2495. \newcommand{\ASTXIntRacket}{
  2496. \begin{array}{lcl}
  2497. \Reg &::=& \allregisters{} \\
  2498. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2499. \MID \DEREF{\Reg}{\Int} \\
  2500. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2501. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2502. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2503. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2504. &\MID& \PUSHQ{\Arg}
  2505. \MID \POPQ{\Arg} \\
  2506. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2507. \MID \RETQ{}
  2508. \MID \JMP{\itm{label}} \\
  2509. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2510. \end{array}
  2511. }
  2512. \begin{figure}[tp]
  2513. \begin{tcolorbox}[colback=white]
  2514. \small
  2515. {\if\edition\racketEd
  2516. \[\arraycolsep=3pt
  2517. \begin{array}{l}
  2518. \ASTXIntRacket \\
  2519. \begin{array}{lcl}
  2520. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2521. \end{array}
  2522. \end{array}
  2523. \]
  2524. \fi}
  2525. {\if\edition\pythonEd\pythonColor
  2526. \[
  2527. \begin{array}{lcl}
  2528. \Reg &::=& \allastregisters{} \\
  2529. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2530. \MID \DEREF{\Reg}{\Int} \\
  2531. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2532. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2533. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2534. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2535. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2536. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2537. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2538. \end{array}
  2539. \]
  2540. \fi}
  2541. \end{tcolorbox}
  2542. \caption{The abstract syntax of \LangXInt{} assembly.}
  2543. \label{fig:x86-int-ast}
  2544. \end{figure}
  2545. \section{Planning the Trip to x86}
  2546. \label{sec:plan-s0-x86}
  2547. To compile one language to another, it helps to focus on the
  2548. differences between the two languages because the compiler will need
  2549. to bridge those differences. What are the differences between \LangVar{}
  2550. and x86 assembly? Here are some of the most important ones:
  2551. \begin{enumerate}
  2552. \item x86 arithmetic instructions typically have two arguments and
  2553. update the second argument in place. In contrast, \LangVar{}
  2554. arithmetic operations take two arguments and produce a new value.
  2555. An x86 instruction may have at most one memory-accessing argument.
  2556. Furthermore, some x86 instructions place special restrictions on
  2557. their arguments.
  2558. \item An argument of an \LangVar{} operator can be a deeply nested
  2559. expression, whereas x86 instructions restrict their arguments to be
  2560. integer constants, registers, and memory locations.
  2561. {\if\edition\racketEd
  2562. \item The order of execution in x86 is explicit in the syntax, which
  2563. is a sequence of instructions and jumps to labeled positions,
  2564. whereas in \LangVar{} the order of evaluation is a left-to-right
  2565. depth-first traversal of the abstract syntax tree. \fi}
  2566. \item A program in \LangVar{} can have any number of variables,
  2567. whereas x86 has 16 registers and the procedure call stack.
  2568. {\if\edition\racketEd
  2569. \item Variables in \LangVar{} can shadow other variables with the
  2570. same name. In x86, registers have unique names, and memory locations
  2571. have unique addresses.
  2572. \fi}
  2573. \end{enumerate}
  2574. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2575. down the problem into several steps, which deal with these differences
  2576. one at a time. Each of these steps is called a \emph{pass} of the
  2577. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2578. %
  2579. This term indicates that each step passes over, or traverses, the AST
  2580. of the program.
  2581. %
  2582. Furthermore, we follow the nanopass approach, which means that we
  2583. strive for each pass to accomplish one clear objective rather than two
  2584. or three at the same time.
  2585. %
  2586. We begin by sketching how we might implement each pass and give each
  2587. pass a name. We then figure out an ordering of the passes and the
  2588. input/output language for each pass. The very first pass has
  2589. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2590. its output language. In between these two passes, we can choose
  2591. whichever language is most convenient for expressing the output of
  2592. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2593. \emph{intermediate language} of our own design. Finally, to
  2594. implement each pass we write one recursive function per nonterminal in
  2595. the grammar of the input language of the pass.
  2596. \index{subject}{intermediate language}
  2597. Our compiler for \LangVar{} consists of the following passes:
  2598. %
  2599. \begin{description}
  2600. {\if\edition\racketEd
  2601. \item[\key{uniquify}] deals with the shadowing of variables by
  2602. renaming every variable to a unique name.
  2603. \fi}
  2604. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2605. of a primitive operation or function call is a variable or integer,
  2606. that is, an \emph{atomic} expression. We refer to nonatomic
  2607. expressions as \emph{complex}. This pass introduces temporary
  2608. variables to hold the results of complex
  2609. subexpressions.\index{subject}{atomic
  2610. expression}\index{subject}{complex expression}%
  2611. {\if\edition\racketEd
  2612. \item[\key{explicate\_control}] makes the execution order of the
  2613. program explicit. It converts the abstract syntax tree
  2614. representation into a graph in which each node is a labeled sequence
  2615. of statements and the edges are \code{goto} statements.
  2616. \fi}
  2617. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2618. handles the difference between
  2619. \LangVar{} operations and x86 instructions. This pass converts each
  2620. \LangVar{} operation to a short sequence of instructions that
  2621. accomplishes the same task.
  2622. \item[\key{assign\_homes}] replaces variables with registers or stack
  2623. locations.
  2624. \end{description}
  2625. %
  2626. {\if\edition\racketEd
  2627. %
  2628. Our treatment of \code{remove\_complex\_operands} and
  2629. \code{explicate\_control} as separate passes is an example of the
  2630. nanopass approach.\footnote{For analogous decompositions of the
  2631. translation into continuation passing style, see the work of
  2632. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2633. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2634. %
  2635. \fi}
  2636. The next question is, in what order should we apply these passes? This
  2637. question can be challenging because it is difficult to know ahead of
  2638. time which orderings will be better (that is, will be easier to
  2639. implement, produce more efficient code, and so on), and therefore
  2640. ordering often involves trial and error. Nevertheless, we can plan
  2641. ahead and make educated choices regarding the ordering.
  2642. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2643. \key{uniquify}? The \key{uniquify} pass should come first because
  2644. \key{explicate\_control} changes all the \key{let}-bound variables to
  2645. become local variables whose scope is the entire program, which would
  2646. confuse variables with the same name.}
  2647. %
  2648. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2649. because the later removes the \key{let} form, but it is convenient to
  2650. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2651. %
  2652. \racket{The ordering of \key{uniquify} with respect to
  2653. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2654. \key{uniquify} to come first.}
  2655. The \key{select\_instructions} and \key{assign\_homes} passes are
  2656. intertwined.
  2657. %
  2658. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2659. passing arguments to functions and that it is preferable to assign
  2660. parameters to their corresponding registers. This suggests that it
  2661. would be better to start with the \key{select\_instructions} pass,
  2662. which generates the instructions for argument passing, before
  2663. performing register allocation.
  2664. %
  2665. On the other hand, by selecting instructions first we may run into a
  2666. dead end in \key{assign\_homes}. Recall that only one argument of an
  2667. x86 instruction may be a memory access, but \key{assign\_homes} might
  2668. be forced to assign both arguments to memory locations.
  2669. %
  2670. A sophisticated approach is to repeat the two passes until a solution
  2671. is found. However, to reduce implementation complexity we recommend
  2672. placing \key{select\_instructions} first, followed by the
  2673. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2674. that uses a reserved register to fix outstanding problems.
  2675. \begin{figure}[tbp]
  2676. \begin{tcolorbox}[colback=white]
  2677. {\if\edition\racketEd
  2678. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2679. \node (Lvar) at (0,2) {\large \LangVar{}};
  2680. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2681. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2682. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2683. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2684. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2685. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2686. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2687. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2688. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2689. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2690. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2691. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2692. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2693. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2694. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2695. \end{tikzpicture}
  2696. \fi}
  2697. {\if\edition\pythonEd\pythonColor
  2698. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2699. \node (Lvar) at (0,2) {\large \LangVar{}};
  2700. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2701. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2702. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2703. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2704. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2705. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2706. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2707. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2708. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2709. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2710. \end{tikzpicture}
  2711. \fi}
  2712. \end{tcolorbox}
  2713. \caption{Diagram of the passes for compiling \LangVar{}. }
  2714. \label{fig:Lvar-passes}
  2715. \end{figure}
  2716. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2717. passes and identifies the input and output language of each pass.
  2718. %
  2719. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2720. language, which extends \LangXInt{} with an unbounded number of
  2721. program-scope variables and removes the restrictions regarding
  2722. instruction arguments.
  2723. %
  2724. The last pass, \key{prelude\_and\_conclusion}, places the program
  2725. instructions inside a \code{main} function with instructions for the
  2726. prelude and conclusion.
  2727. %
  2728. \racket{In the next section we discuss the \LangCVar{} intermediate
  2729. language that serves as the output of \code{explicate\_control}.}
  2730. %
  2731. The remainder of this chapter provides guidance on the implementation
  2732. of each of the compiler passes represented in
  2733. figure~\ref{fig:Lvar-passes}.
  2734. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2735. %% are programs that are still in the \LangVar{} language, though the
  2736. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2737. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2738. %% %
  2739. %% The output of \code{explicate\_control} is in an intermediate language
  2740. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2741. %% syntax, which we introduce in the next section. The
  2742. %% \key{select-instruction} pass translates from \LangCVar{} to
  2743. %% \LangXVar{}. The \key{assign-homes} and
  2744. %% \key{patch-instructions}
  2745. %% passes input and output variants of x86 assembly.
  2746. \newcommand{\CvarGrammarRacket}{
  2747. \begin{array}{lcl}
  2748. \Atm &::=& \Int \MID \Var \\
  2749. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2750. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2751. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2752. \end{array}
  2753. }
  2754. \newcommand{\CvarASTRacket}{
  2755. \begin{array}{lcl}
  2756. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2757. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2758. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2759. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2760. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2761. \end{array}
  2762. }
  2763. {\if\edition\racketEd
  2764. \subsection{The \LangCVar{} Intermediate Language}
  2765. The output of \code{explicate\_control} is similar to the C
  2766. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2767. categories for expressions and statements, so we name it \LangCVar{}.
  2768. This style of intermediate language is also known as
  2769. \emph{three-address code}, to emphasize that the typical form of a
  2770. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2771. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2772. The concrete syntax for \LangCVar{} is shown in
  2773. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2774. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2775. %
  2776. The \LangCVar{} language supports the same operators as \LangVar{} but
  2777. the arguments of operators are restricted to atomic
  2778. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2779. assignment statements that can be executed in sequence using the
  2780. \key{Seq} form. A sequence of statements always ends with
  2781. \key{Return}, a guarantee that is baked into the grammar rules for
  2782. \itm{tail}. The naming of this nonterminal comes from the term
  2783. \emph{tail position}\index{subject}{tail position}, which refers to an
  2784. expression that is the last one to execute within a function or
  2785. program.
  2786. A \LangCVar{} program consists of an alist mapping labels to
  2787. tails. This is more general than necessary for the present chapter, as
  2788. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2789. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2790. there is just one label, \key{start}, and the whole program is
  2791. its tail.
  2792. %
  2793. The $\itm{info}$ field of the \key{CProgram} form, after the
  2794. \code{explicate\_control} pass, contains an alist that associates the
  2795. symbol \key{locals} with a list of all the variables used in the
  2796. program. At the start of the program, these variables are
  2797. uninitialized; they become initialized on their first assignment.
  2798. \begin{figure}[tbp]
  2799. \begin{tcolorbox}[colback=white]
  2800. \[
  2801. \begin{array}{l}
  2802. \CvarGrammarRacket \\
  2803. \begin{array}{lcl}
  2804. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2805. \end{array}
  2806. \end{array}
  2807. \]
  2808. \end{tcolorbox}
  2809. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2810. \label{fig:c0-concrete-syntax}
  2811. \end{figure}
  2812. \begin{figure}[tbp]
  2813. \begin{tcolorbox}[colback=white]
  2814. \[
  2815. \begin{array}{l}
  2816. \CvarASTRacket \\
  2817. \begin{array}{lcl}
  2818. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2819. \end{array}
  2820. \end{array}
  2821. \]
  2822. \end{tcolorbox}
  2823. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2824. \label{fig:c0-syntax}
  2825. \end{figure}
  2826. The definitional interpreter for \LangCVar{} is in the support code,
  2827. in the file \code{interp-Cvar.rkt}.
  2828. \fi}
  2829. {\if\edition\racketEd
  2830. \section{Uniquify Variables}
  2831. \label{sec:uniquify-Lvar}
  2832. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2833. with a unique name. Both the input and output of the \code{uniquify}
  2834. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2835. should translate the program on the left into the program on the
  2836. right.
  2837. \begin{transformation}
  2838. \begin{lstlisting}
  2839. (let ([x 32])
  2840. (+ (let ([x 10]) x) x))
  2841. \end{lstlisting}
  2842. \compilesto
  2843. \begin{lstlisting}
  2844. (let ([x.1 32])
  2845. (+ (let ([x.2 10]) x.2) x.1))
  2846. \end{lstlisting}
  2847. \end{transformation}
  2848. The following is another example translation, this time of a program
  2849. with a \key{let} nested inside the initializing expression of another
  2850. \key{let}.
  2851. \begin{transformation}
  2852. \begin{lstlisting}
  2853. (let ([x (let ([x 4])
  2854. (+ x 1))])
  2855. (+ x 2))
  2856. \end{lstlisting}
  2857. \compilesto
  2858. \begin{lstlisting}
  2859. (let ([x.2 (let ([x.1 4])
  2860. (+ x.1 1))])
  2861. (+ x.2 2))
  2862. \end{lstlisting}
  2863. \end{transformation}
  2864. We recommend implementing \code{uniquify} by creating a structurally
  2865. recursive function named \code{uniquify\_exp} that does little other
  2866. than copy an expression. However, when encountering a \key{let}, it
  2867. should generate a unique name for the variable and associate the old
  2868. name with the new name in an alist.\footnote{The Racket function
  2869. \code{gensym} is handy for generating unique variable names.} The
  2870. \code{uniquify\_exp} function needs to access this alist when it gets
  2871. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2872. for the alist.
  2873. The skeleton of the \code{uniquify\_exp} function is shown in
  2874. figure~\ref{fig:uniquify-Lvar}.
  2875. %% The function is curried so that it is
  2876. %% convenient to partially apply it to an alist and then apply it to
  2877. %% different expressions, as in the last case for primitive operations in
  2878. %% figure~\ref{fig:uniquify-Lvar}.
  2879. The
  2880. %
  2881. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2882. %
  2883. form of Racket is useful for transforming the element of a list to
  2884. produce a new list.\index{subject}{for/list}
  2885. \begin{figure}[tbp]
  2886. \begin{tcolorbox}[colback=white]
  2887. \begin{lstlisting}
  2888. (define (uniquify_exp env)
  2889. (lambda (e)
  2890. (match e
  2891. [(Var x) ___]
  2892. [(Int n) (Int n)]
  2893. [(Let x e body) ___]
  2894. [(Prim op es)
  2895. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2896. (define (uniquify p)
  2897. (match p
  2898. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2899. \end{lstlisting}
  2900. \end{tcolorbox}
  2901. \caption{Skeleton for the \key{uniquify} pass.}
  2902. \label{fig:uniquify-Lvar}
  2903. \end{figure}
  2904. \begin{exercise}
  2905. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2906. Complete the \code{uniquify} pass by filling in the blanks in
  2907. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2908. variables and for the \key{let} form in the file \code{compiler.rkt}
  2909. in the support code.
  2910. \end{exercise}
  2911. \begin{exercise}
  2912. \normalfont\normalsize
  2913. \label{ex:Lvar}
  2914. Create five \LangVar{} programs that exercise the most interesting
  2915. parts of the \key{uniquify} pass; that is, the programs should include
  2916. \key{let} forms, variables, and variables that shadow each other.
  2917. The five programs should be placed in the subdirectory named
  2918. \key{tests}, and the file names should start with \code{var\_test\_}
  2919. followed by a unique integer and end with the file extension
  2920. \key{.rkt}.
  2921. %
  2922. The \key{run-tests.rkt} script in the support code checks whether the
  2923. output programs produce the same result as the input programs. The
  2924. script uses the \key{interp-tests} function
  2925. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2926. your \key{uniquify} pass on the example programs. The \code{passes}
  2927. parameter of \key{interp-tests} is a list that should have one entry
  2928. for each pass in your compiler. For now, define \code{passes} to
  2929. contain just one entry for \code{uniquify} as follows:
  2930. \begin{lstlisting}
  2931. (define passes
  2932. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2933. \end{lstlisting}
  2934. Run the \key{run-tests.rkt} script in the support code to check
  2935. whether the output programs produce the same result as the input
  2936. programs.
  2937. \end{exercise}
  2938. \fi}
  2939. \section{Remove Complex Operands}
  2940. \label{sec:remove-complex-opera-Lvar}
  2941. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2942. into a restricted form in which the arguments of operations are atomic
  2943. expressions. Put another way, this pass removes complex
  2944. operands\index{subject}{complex operand}, such as the expression
  2945. \racket{\code{(- 10)}}\python{\code{-10}}
  2946. in the following program. This is accomplished by introducing a new
  2947. temporary variable, assigning the complex operand to the new
  2948. variable, and then using the new variable in place of the complex
  2949. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2950. right.
  2951. {\if\edition\racketEd
  2952. \begin{transformation}
  2953. % var_test_19.rkt
  2954. \begin{lstlisting}
  2955. (let ([x (+ 42 (- 10))])
  2956. (+ x 10))
  2957. \end{lstlisting}
  2958. \compilesto
  2959. \begin{lstlisting}
  2960. (let ([x (let ([tmp.1 (- 10)])
  2961. (+ 42 tmp.1))])
  2962. (+ x 10))
  2963. \end{lstlisting}
  2964. \end{transformation}
  2965. \fi}
  2966. {\if\edition\pythonEd\pythonColor
  2967. \begin{transformation}
  2968. \begin{lstlisting}
  2969. x = 42 + -10
  2970. print(x + 10)
  2971. \end{lstlisting}
  2972. \compilesto
  2973. \begin{lstlisting}
  2974. tmp_0 = -10
  2975. x = 42 + tmp_0
  2976. tmp_1 = x + 10
  2977. print(tmp_1)
  2978. \end{lstlisting}
  2979. \end{transformation}
  2980. \fi}
  2981. \newcommand{\LvarMonadASTRacket}{
  2982. \begin{array}{rcl}
  2983. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2984. \Exp &::=& \Atm \MID \READ{} \\
  2985. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2986. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2987. \end{array}
  2988. }
  2989. \newcommand{\LvarMonadASTPython}{
  2990. \begin{array}{rcl}
  2991. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2992. \Exp{} &::=& \Atm \MID \READ{} \\
  2993. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2994. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2995. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2996. \end{array}
  2997. }
  2998. \begin{figure}[tp]
  2999. \centering
  3000. \begin{tcolorbox}[colback=white]
  3001. {\if\edition\racketEd
  3002. \[
  3003. \begin{array}{l}
  3004. \LvarMonadASTRacket \\
  3005. \begin{array}{rcl}
  3006. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3007. \end{array}
  3008. \end{array}
  3009. \]
  3010. \fi}
  3011. {\if\edition\pythonEd\pythonColor
  3012. \[
  3013. \begin{array}{l}
  3014. \LvarMonadASTPython \\
  3015. \begin{array}{rcl}
  3016. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3017. \end{array}
  3018. \end{array}
  3019. \]
  3020. \fi}
  3021. \end{tcolorbox}
  3022. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3023. atomic expressions.}
  3024. \label{fig:Lvar-anf-syntax}
  3025. \end{figure}
  3026. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3027. of this pass, the language \LangVarANF{}. The only difference is that
  3028. operator arguments are restricted to be atomic expressions that are
  3029. defined by the \Atm{} nonterminal. In particular, integer constants
  3030. and variables are atomic.
  3031. The atomic expressions are pure (they do not cause or depend on side
  3032. effects) whereas complex expressions may have side effects, such as
  3033. \READ{}. A language with this separation between pure expressions
  3034. versus expressions with side effects is said to be in monadic normal
  3035. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3036. in the name \LangVarANF{}. An important invariant of the
  3037. \code{remove\_complex\_operands} pass is that the relative ordering
  3038. among complex expressions is not changed, but the relative ordering
  3039. between atomic expressions and complex expressions can change and
  3040. often does. The reason that these changes are behavior preserving is
  3041. that the atomic expressions are pure.
  3042. {\if\edition\racketEd
  3043. Another well-known form for intermediate languages is the
  3044. \emph{administrative normal form}
  3045. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3046. \index{subject}{administrative normal form} \index{subject}{ANF}
  3047. %
  3048. The \LangVarANF{} language is not quite in ANF because it allows the
  3049. right-hand side of a \code{let} to be a complex expression, such as
  3050. another \code{let}. The flattening of nested \code{let} expressions is
  3051. instead one of the responsibilities of the \code{explicate\_control}
  3052. pass.
  3053. \fi}
  3054. {\if\edition\racketEd
  3055. We recommend implementing this pass with two mutually recursive
  3056. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3057. \code{rco\_atom} to subexpressions that need to become atomic and to
  3058. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3059. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3060. returns an expression. The \code{rco\_atom} function returns two
  3061. things: an atomic expression and an alist mapping temporary variables to
  3062. complex subexpressions. You can return multiple things from a function
  3063. using Racket's \key{values} form, and you can receive multiple things
  3064. from a function call using the \key{define-values} form.
  3065. \fi}
  3066. %
  3067. {\if\edition\pythonEd\pythonColor
  3068. %
  3069. We recommend implementing this pass with an auxiliary method named
  3070. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3071. Boolean that specifies whether the expression needs to become atomic
  3072. or not. The \code{rco\_exp} method should return a pair consisting of
  3073. the new expression and a list of pairs, associating new temporary
  3074. variables with their initializing expressions.
  3075. %
  3076. \fi}
  3077. {\if\edition\racketEd
  3078. %
  3079. Returning to the example program with the expression \code{(+ 42 (-
  3080. 10))}, the subexpression \code{(- 10)} should be processed using the
  3081. \code{rco\_atom} function because it is an argument of the \code{+}
  3082. operator and therefore needs to become atomic. The output of
  3083. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3084. \begin{transformation}
  3085. \begin{lstlisting}
  3086. (- 10)
  3087. \end{lstlisting}
  3088. \compilesto
  3089. \begin{lstlisting}
  3090. tmp.1
  3091. ((tmp.1 . (- 10)))
  3092. \end{lstlisting}
  3093. \end{transformation}
  3094. \fi}
  3095. %
  3096. {\if\edition\pythonEd\pythonColor
  3097. %
  3098. Returning to the example program with the expression \code{42 + -10},
  3099. the subexpression \code{-10} should be processed using the
  3100. \code{rco\_exp} function with \code{True} as the second argument
  3101. because \code{-10} is an argument of the \code{+} operator and
  3102. therefore needs to become atomic. The output of \code{rco\_exp}
  3103. applied to \code{-10} is as follows.
  3104. \begin{transformation}
  3105. \begin{lstlisting}
  3106. -10
  3107. \end{lstlisting}
  3108. \compilesto
  3109. \begin{lstlisting}
  3110. tmp_1
  3111. [(tmp_1, -10)]
  3112. \end{lstlisting}
  3113. \end{transformation}
  3114. %
  3115. \fi}
  3116. Take special care of programs, such as the following, that
  3117. %
  3118. \racket{bind a variable to an atomic expression.}
  3119. %
  3120. \python{assign an atomic expression to a variable.}
  3121. %
  3122. You should leave such \racket{variable bindings}\python{assignments}
  3123. unchanged, as shown in the program on the right:\\
  3124. %
  3125. {\if\edition\racketEd
  3126. \begin{transformation}
  3127. % var_test_20.rkt
  3128. \begin{lstlisting}
  3129. (let ([a 42])
  3130. (let ([b a])
  3131. b))
  3132. \end{lstlisting}
  3133. \compilesto
  3134. \begin{lstlisting}
  3135. (let ([a 42])
  3136. (let ([b a])
  3137. b))
  3138. \end{lstlisting}
  3139. \end{transformation}
  3140. \fi}
  3141. {\if\edition\pythonEd\pythonColor
  3142. \begin{transformation}
  3143. \begin{lstlisting}
  3144. a = 42
  3145. b = a
  3146. print(b)
  3147. \end{lstlisting}
  3148. \compilesto
  3149. \begin{lstlisting}
  3150. a = 42
  3151. b = a
  3152. print(b)
  3153. \end{lstlisting}
  3154. \end{transformation}
  3155. \fi}
  3156. %
  3157. \noindent A careless implementation might produce the following output with
  3158. unnecessary temporary variables.
  3159. \begin{center}
  3160. \begin{minipage}{0.4\textwidth}
  3161. {\if\edition\racketEd
  3162. \begin{lstlisting}
  3163. (let ([tmp.1 42])
  3164. (let ([a tmp.1])
  3165. (let ([tmp.2 a])
  3166. (let ([b tmp.2])
  3167. b))))
  3168. \end{lstlisting}
  3169. \fi}
  3170. {\if\edition\pythonEd\pythonColor
  3171. \begin{lstlisting}
  3172. tmp_1 = 42
  3173. a = tmp_1
  3174. tmp_2 = a
  3175. b = tmp_2
  3176. print(b)
  3177. \end{lstlisting}
  3178. \fi}
  3179. \end{minipage}
  3180. \end{center}
  3181. \begin{exercise}
  3182. \normalfont\normalsize
  3183. {\if\edition\racketEd
  3184. Implement the \code{remove\_complex\_operands} function in
  3185. \code{compiler.rkt}.
  3186. %
  3187. Create three new \LangVar{} programs that exercise the interesting
  3188. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3189. regarding file names described in exercise~\ref{ex:Lvar}.
  3190. %
  3191. In the \code{run-tests.rkt} script, add the following entry to the
  3192. list of \code{passes}, and then run the script to test your compiler.
  3193. \begin{lstlisting}
  3194. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3195. \end{lstlisting}
  3196. In debugging your compiler, it is often useful to see the intermediate
  3197. programs that are output from each pass. To print the intermediate
  3198. programs, place \lstinline{(debug-level 1)} before the call to
  3199. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3200. %
  3201. {\if\edition\pythonEd\pythonColor
  3202. Implement the \code{remove\_complex\_operands} pass in
  3203. \code{compiler.py}, creating auxiliary functions for each
  3204. nonterminal in the grammar, i.e., \code{rco\_exp}
  3205. and \code{rco\_stmt}. We recommend you use the function
  3206. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3207. \fi}
  3208. \end{exercise}
  3209. {\if\edition\pythonEd\pythonColor
  3210. \begin{exercise}
  3211. \normalfont\normalsize
  3212. \label{ex:Lvar}
  3213. Create five \LangVar{} programs that exercise the most interesting
  3214. parts of the \code{remove\_complex\_operands} pass. The five programs
  3215. should be placed in the subdirectory named \key{tests}, and the file
  3216. names should start with \code{var\_test\_} followed by a unique
  3217. integer and end with the file extension \key{.py}.
  3218. %% The \key{run-tests.rkt} script in the support code checks whether the
  3219. %% output programs produce the same result as the input programs. The
  3220. %% script uses the \key{interp-tests} function
  3221. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3222. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3223. %% parameter of \key{interp-tests} is a list that should have one entry
  3224. %% for each pass in your compiler. For now, define \code{passes} to
  3225. %% contain just one entry for \code{uniquify} as shown below.
  3226. %% \begin{lstlisting}
  3227. %% (define passes
  3228. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3229. %% \end{lstlisting}
  3230. Run the \key{run-tests.py} script in the support code to check
  3231. whether the output programs produce the same result as the input
  3232. programs.
  3233. \end{exercise}
  3234. \fi}
  3235. {\if\edition\racketEd
  3236. \section{Explicate Control}
  3237. \label{sec:explicate-control-Lvar}
  3238. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3239. programs that make the order of execution explicit in their
  3240. syntax. For now this amounts to flattening \key{let} constructs into a
  3241. sequence of assignment statements. For example, consider the following
  3242. \LangVar{} program:\\
  3243. % var_test_11.rkt
  3244. \begin{minipage}{0.96\textwidth}
  3245. \begin{lstlisting}
  3246. (let ([y (let ([x 20])
  3247. (+ x (let ([x 22]) x)))])
  3248. y)
  3249. \end{lstlisting}
  3250. \end{minipage}\\
  3251. %
  3252. The output of the previous pass is shown next, on the left, and the
  3253. output of \code{explicate\_control} is on the right. Recall that the
  3254. right-hand side of a \key{let} executes before its body, so that the order
  3255. of evaluation for this program is to assign \code{20} to \code{x.1},
  3256. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3257. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3258. this ordering explicit.
  3259. \begin{transformation}
  3260. \begin{lstlisting}
  3261. (let ([y (let ([x.1 20])
  3262. (let ([x.2 22])
  3263. (+ x.1 x.2)))])
  3264. y)
  3265. \end{lstlisting}
  3266. \compilesto
  3267. \begin{lstlisting}[language=C]
  3268. start:
  3269. x.1 = 20;
  3270. x.2 = 22;
  3271. y = (+ x.1 x.2);
  3272. return y;
  3273. \end{lstlisting}
  3274. \end{transformation}
  3275. \begin{figure}[tbp]
  3276. \begin{tcolorbox}[colback=white]
  3277. \begin{lstlisting}
  3278. (define (explicate_tail e)
  3279. (match e
  3280. [(Var x) ___]
  3281. [(Int n) (Return (Int n))]
  3282. [(Let x rhs body) ___]
  3283. [(Prim op es) ___]
  3284. [else (error "explicate_tail unhandled case" e)]))
  3285. (define (explicate_assign e x cont)
  3286. (match e
  3287. [(Var x) ___]
  3288. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3289. [(Let y rhs body) ___]
  3290. [(Prim op es) ___]
  3291. [else (error "explicate_assign unhandled case" e)]))
  3292. (define (explicate_control p)
  3293. (match p
  3294. [(Program info body) ___]))
  3295. \end{lstlisting}
  3296. \end{tcolorbox}
  3297. \caption{Skeleton for the \code{explicate\_control} pass.}
  3298. \label{fig:explicate-control-Lvar}
  3299. \end{figure}
  3300. The organization of this pass depends on the notion of tail position
  3301. to which we have alluded. Here is the definition.
  3302. \begin{definition}\normalfont
  3303. The following rules define when an expression is in \emph{tail
  3304. position}\index{subject}{tail position} for the language \LangVar{}.
  3305. \begin{enumerate}
  3306. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3307. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3308. \end{enumerate}
  3309. \end{definition}
  3310. We recommend implementing \code{explicate\_control} using two
  3311. recursive functions, \code{explicate\_tail} and
  3312. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3313. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3314. function should be applied to expressions in tail position, whereas the
  3315. \code{explicate\_assign} should be applied to expressions that occur on
  3316. the right-hand side of a \key{let}.
  3317. %
  3318. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3319. input and produces a \Tail{} in \LangCVar{} (see
  3320. figure~\ref{fig:c0-syntax}).
  3321. %
  3322. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3323. the variable to which it is to be assigned, and a \Tail{} in
  3324. \LangCVar{} for the code that comes after the assignment. The
  3325. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3326. The \code{explicate\_assign} function is in accumulator-passing style:
  3327. the \code{cont} parameter is used for accumulating the output. This
  3328. accumulator-passing style plays an important role in the way that we
  3329. generate high-quality code for conditional expressions in
  3330. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3331. continuation because it contains the generated code that should come
  3332. after the current assignment. This code organization is also related
  3333. to continuation-passing style, except that \code{cont} is not what
  3334. happens next during compilation but is what happens next in the
  3335. generated code.
  3336. \begin{exercise}\normalfont\normalsize
  3337. %
  3338. Implement the \code{explicate\_control} function in
  3339. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3340. exercise the code in \code{explicate\_control}.
  3341. %
  3342. In the \code{run-tests.rkt} script, add the following entry to the
  3343. list of \code{passes} and then run the script to test your compiler.
  3344. \begin{lstlisting}
  3345. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3346. \end{lstlisting}
  3347. \end{exercise}
  3348. \fi}
  3349. \section{Select Instructions}
  3350. \label{sec:select-Lvar}
  3351. \index{subject}{select instructions}
  3352. In the \code{select\_instructions} pass we begin the work of
  3353. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3354. language of this pass is a variant of x86 that still uses variables,
  3355. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3356. nonterminal of the \LangXInt{} abstract syntax
  3357. (figure~\ref{fig:x86-int-ast}).
  3358. \racket{We recommend implementing the
  3359. \code{select\_instructions} with three auxiliary functions, one for
  3360. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3361. $\Tail$.}
  3362. \python{We recommend implementing an auxiliary function
  3363. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3364. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3365. same and integer constants change to immediates; that is, $\INT{n}$
  3366. changes to $\IMM{n}$.}
  3367. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3368. arithmetic operations. For example, consider the following addition
  3369. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3370. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3371. \key{addq} instruction in x86, but it performs an in-place update.
  3372. %
  3373. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3374. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into the
  3375. left-hand \itm{var}.
  3376. \begin{transformation}
  3377. {\if\edition\racketEd
  3378. \begin{lstlisting}
  3379. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3380. \end{lstlisting}
  3381. \fi}
  3382. {\if\edition\pythonEd\pythonColor
  3383. \begin{lstlisting}
  3384. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3385. \end{lstlisting}
  3386. \fi}
  3387. \compilesto
  3388. \begin{lstlisting}
  3389. movq |$\Arg_1$|, %rax
  3390. addq |$\Arg_2$|, %rax
  3391. movq %rax, |$\itm{var}$|
  3392. \end{lstlisting}
  3393. \end{transformation}
  3394. %
  3395. However, with some care we can generate shorter sequences of
  3396. instructions. Suppose that one or more of the arguments of the
  3397. addition is the same variable as the left-hand side of the assignment.
  3398. Then the assignment statement can be translated into a single
  3399. \key{addq} instruction, as follows.
  3400. \begin{transformation}
  3401. {\if\edition\racketEd
  3402. \begin{lstlisting}
  3403. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3404. \end{lstlisting}
  3405. \fi}
  3406. {\if\edition\pythonEd\pythonColor
  3407. \begin{lstlisting}
  3408. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3409. \end{lstlisting}
  3410. \fi}
  3411. \compilesto
  3412. \begin{lstlisting}
  3413. addq |$\Arg_1$|, |$\itm{var}$|
  3414. \end{lstlisting}
  3415. \end{transformation}
  3416. %
  3417. On the other hand, if $\Atm_1$ is not the same variable as the
  3418. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3419. and then add $\Arg_2$ to \itm{var}.
  3420. %
  3421. \begin{transformation}
  3422. {\if\edition\racketEd
  3423. \begin{lstlisting}
  3424. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3425. \end{lstlisting}
  3426. \fi}
  3427. {\if\edition\pythonEd\pythonColor
  3428. \begin{lstlisting}
  3429. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3430. \end{lstlisting}
  3431. \fi}
  3432. \compilesto
  3433. \begin{lstlisting}
  3434. movq |$\Arg_1$|, |$\itm{var}$|
  3435. addq |$\Arg_2$|, |$\itm{var}$|
  3436. \end{lstlisting}
  3437. \end{transformation}
  3438. The \READOP{} operation does not have a direct counterpart in x86
  3439. assembly, so we provide this functionality with the function
  3440. \code{read\_int} in the file \code{runtime.c}, written in
  3441. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3442. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3443. system}, or simply the \emph{runtime} for short. When compiling your
  3444. generated x86 assembly code, you need to compile \code{runtime.c} to
  3445. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3446. \code{-c}) and link it into the executable. For our purposes of code
  3447. generation, all you need to do is translate an assignment of
  3448. \READOP{} into a call to the \code{read\_int} function followed by a
  3449. move from \code{rax} to the left-hand side variable. (Recall that the
  3450. return value of a function goes into \code{rax}.)
  3451. \begin{transformation}
  3452. {\if\edition\racketEd
  3453. \begin{lstlisting}
  3454. |$\itm{var}$| = (read);
  3455. \end{lstlisting}
  3456. \fi}
  3457. {\if\edition\pythonEd\pythonColor
  3458. \begin{lstlisting}
  3459. |$\itm{var}$| = input_int();
  3460. \end{lstlisting}
  3461. \fi}
  3462. \compilesto
  3463. \begin{lstlisting}
  3464. callq read_int
  3465. movq %rax, |$\itm{var}$|
  3466. \end{lstlisting}
  3467. \end{transformation}
  3468. {\if\edition\pythonEd\pythonColor
  3469. %
  3470. Similarly, we translate the \code{print} operation, shown below, into
  3471. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3472. In x86, the first six arguments to functions are passed in registers,
  3473. with the first argument passed in register \code{rdi}. So we move the
  3474. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3475. \code{callq} instruction.
  3476. \begin{transformation}
  3477. \begin{lstlisting}
  3478. print(|$\Atm$|)
  3479. \end{lstlisting}
  3480. \compilesto
  3481. \begin{lstlisting}
  3482. movq |$\Arg$|, %rdi
  3483. callq print_int
  3484. \end{lstlisting}
  3485. \end{transformation}
  3486. %
  3487. \fi}
  3488. {\if\edition\racketEd
  3489. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3490. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3491. assignment to the \key{rax} register followed by a jump to the
  3492. conclusion of the program (so the conclusion needs to be labeled).
  3493. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3494. recursively and then append the resulting instructions.
  3495. \fi}
  3496. {\if\edition\pythonEd\pythonColor
  3497. We recommend that you use the function \code{utils.label\_name()} to
  3498. transform strings into labels, for example, in
  3499. the target of the \code{callq} instruction. This practice makes your
  3500. compiler portable across Linus and Mac OS X, which requires an underscore
  3501. prefixed to all labels.
  3502. \fi}
  3503. \begin{exercise}
  3504. \normalfont\normalsize
  3505. {\if\edition\racketEd
  3506. Implement the \code{select\_instructions} pass in
  3507. \code{compiler.rkt}. Create three new example programs that are
  3508. designed to exercise all the interesting cases in this pass.
  3509. %
  3510. In the \code{run-tests.rkt} script, add the following entry to the
  3511. list of \code{passes} and then run the script to test your compiler.
  3512. \begin{lstlisting}
  3513. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3514. \end{lstlisting}
  3515. \fi}
  3516. {\if\edition\pythonEd\pythonColor
  3517. Implement the \key{select\_instructions} pass in
  3518. \code{compiler.py}. Create three new example programs that are
  3519. designed to exercise all the interesting cases in this pass.
  3520. Run the \code{run-tests.py} script to to check
  3521. whether the output programs produce the same result as the input
  3522. programs.
  3523. \fi}
  3524. \end{exercise}
  3525. \section{Assign Homes}
  3526. \label{sec:assign-Lvar}
  3527. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3528. \LangXVar{} programs that no longer use program variables. Thus, the
  3529. \code{assign\_homes} pass is responsible for placing all the program
  3530. variables in registers or on the stack. For runtime efficiency, it is
  3531. better to place variables in registers, but because there are only
  3532. sixteen registers, some programs must necessarily resort to placing
  3533. some variables on the stack. In this chapter we focus on the mechanics
  3534. of placing variables on the stack. We study an algorithm for placing
  3535. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3536. Consider again the following \LangVar{} program from
  3537. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3538. % var_test_20.rkt
  3539. \begin{minipage}{0.96\textwidth}
  3540. {\if\edition\racketEd
  3541. \begin{lstlisting}
  3542. (let ([a 42])
  3543. (let ([b a])
  3544. b))
  3545. \end{lstlisting}
  3546. \fi}
  3547. {\if\edition\pythonEd\pythonColor
  3548. \begin{lstlisting}
  3549. a = 42
  3550. b = a
  3551. print(b)
  3552. \end{lstlisting}
  3553. \fi}
  3554. \end{minipage}\\
  3555. %
  3556. The output of \code{select\_instructions} is shown next, on the left,
  3557. and the output of \code{assign\_homes} is on the right. In this
  3558. example, we assign variable \code{a} to stack location
  3559. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3560. \begin{transformation}
  3561. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3562. movq $42, a
  3563. movq a, b
  3564. movq b, %rax
  3565. \end{lstlisting}
  3566. \compilesto
  3567. %stack-space: 16
  3568. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3569. movq $42, -8(%rbp)
  3570. movq -8(%rbp), -16(%rbp)
  3571. movq -16(%rbp), %rax
  3572. \end{lstlisting}
  3573. \end{transformation}
  3574. \racket{
  3575. The \code{assign\_homes} pass should replace all variables
  3576. with stack locations.
  3577. The list of variables can be obtained from
  3578. the \code{locals-types} entry in the $\itm{info}$ of the
  3579. \code{X86Program} node. The \code{locals-types} entry is an alist
  3580. mapping all the variables in the program to their types
  3581. (for now, just \code{Integer}).
  3582. As an aside, the \code{locals-types} entry is
  3583. computed by \code{type-check-Cvar} in the support code, which
  3584. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3585. which you should propagate to the \code{X86Program} node.}
  3586. %
  3587. \python{The \code{assign\_homes} pass should replace all uses of
  3588. variables with stack locations.}
  3589. %
  3590. In the process of assigning variables to stack locations, it is
  3591. convenient for you to compute and store the size of the frame (in
  3592. bytes) in
  3593. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3594. %
  3595. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3596. %
  3597. which is needed later to generate the conclusion of the \code{main}
  3598. procedure. The x86-64 standard requires the frame size to be a
  3599. multiple of 16 bytes.\index{subject}{frame}
  3600. % TODO: store the number of variables instead? -Jeremy
  3601. \begin{exercise}\normalfont\normalsize
  3602. Implement the \code{assign\_homes} pass in
  3603. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3604. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3605. grammar. We recommend that the auxiliary functions take an extra
  3606. parameter that maps variable names to homes (stack locations for now).
  3607. %
  3608. {\if\edition\racketEd
  3609. In the \code{run-tests.rkt} script, add the following entry to the
  3610. list of \code{passes} and then run the script to test your compiler.
  3611. \begin{lstlisting}
  3612. (list "assign homes" assign-homes interp_x86-0)
  3613. \end{lstlisting}
  3614. \fi}
  3615. {\if\edition\pythonEd\pythonColor
  3616. Run the \code{run-tests.py} script to to check
  3617. whether the output programs produce the same result as the input
  3618. programs.
  3619. \fi}
  3620. \end{exercise}
  3621. \section{Patch Instructions}
  3622. \label{sec:patch-s0}
  3623. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3624. \LangXInt{} by making sure that each instruction adheres to the
  3625. restriction that at most one argument of an instruction may be a
  3626. memory reference.
  3627. We return to the following example.\\
  3628. \begin{minipage}{0.5\textwidth}
  3629. % var_test_20.rkt
  3630. {\if\edition\racketEd
  3631. \begin{lstlisting}
  3632. (let ([a 42])
  3633. (let ([b a])
  3634. b))
  3635. \end{lstlisting}
  3636. \fi}
  3637. {\if\edition\pythonEd\pythonColor
  3638. \begin{lstlisting}
  3639. a = 42
  3640. b = a
  3641. print(b)
  3642. \end{lstlisting}
  3643. \fi}
  3644. \end{minipage}\\
  3645. The \code{assign\_homes} pass produces the following translation. \\
  3646. \begin{minipage}{0.5\textwidth}
  3647. {\if\edition\racketEd
  3648. \begin{lstlisting}
  3649. movq $42, -8(%rbp)
  3650. movq -8(%rbp), -16(%rbp)
  3651. movq -16(%rbp), %rax
  3652. \end{lstlisting}
  3653. \fi}
  3654. {\if\edition\pythonEd\pythonColor
  3655. \begin{lstlisting}
  3656. movq 42, -8(%rbp)
  3657. movq -8(%rbp), -16(%rbp)
  3658. movq -16(%rbp), %rdi
  3659. callq print_int
  3660. \end{lstlisting}
  3661. \fi}
  3662. \end{minipage}\\
  3663. The second \key{movq} instruction is problematic because both
  3664. arguments are stack locations. We suggest fixing this problem by
  3665. moving from the source location to the register \key{rax} and then
  3666. from \key{rax} to the destination location, as follows.
  3667. \begin{lstlisting}
  3668. movq -8(%rbp), %rax
  3669. movq %rax, -16(%rbp)
  3670. \end{lstlisting}
  3671. There is a similar corner case that also needs to be dealt with. If
  3672. one argument is an immediate integer larger than $2^{16}$ and the
  3673. other is a memory reference, then the instruction is invalid. One can
  3674. fix this, for example, by first moving the immediate integer into
  3675. \key{rax} and then using \key{rax} in place of the integer.
  3676. \begin{exercise}
  3677. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3678. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3679. Create three new example programs that are
  3680. designed to exercise all the interesting cases in this pass.
  3681. %
  3682. {\if\edition\racketEd
  3683. In the \code{run-tests.rkt} script, add the following entry to the
  3684. list of \code{passes} and then run the script to test your compiler.
  3685. \begin{lstlisting}
  3686. (list "patch instructions" patch_instructions interp_x86-0)
  3687. \end{lstlisting}
  3688. \fi}
  3689. {\if\edition\pythonEd\pythonColor
  3690. Run the \code{run-tests.py} script to to check
  3691. whether the output programs produce the same result as the input
  3692. programs.
  3693. \fi}
  3694. \end{exercise}
  3695. \section{Generate Prelude and Conclusion}
  3696. \label{sec:print-x86}
  3697. \index{subject}{prelude}\index{subject}{conclusion}
  3698. The last step of the compiler from \LangVar{} to x86 is to generate
  3699. the \code{main} function with a prelude and conclusion wrapped around
  3700. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3701. discussed in section~\ref{sec:x86}.
  3702. When running on Mac OS X, your compiler should prefix an underscore to
  3703. all labels (for example, changing \key{main} to \key{\_main}).
  3704. %
  3705. \racket{The Racket call \code{(system-type 'os)} is useful for
  3706. determining which operating system the compiler is running on. It
  3707. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3708. %
  3709. \python{The Python \code{platform} library includes a \code{system()}
  3710. function that returns \code{'Linux'}, \code{'Windows'}, or
  3711. \code{'Darwin'} (for Mac).}
  3712. \begin{exercise}\normalfont\normalsize
  3713. %
  3714. Implement the \key{prelude\_and\_conclusion} pass in
  3715. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3716. %
  3717. {\if\edition\racketEd
  3718. In the \code{run-tests.rkt} script, add the following entry to the
  3719. list of \code{passes} and then run the script to test your compiler.
  3720. \begin{lstlisting}
  3721. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3722. \end{lstlisting}
  3723. %
  3724. Uncomment the call to the \key{compiler-tests} function
  3725. (appendix~\ref{appendix:utilities}), which tests your complete
  3726. compiler by executing the generated x86 code. It translates the x86
  3727. AST that you produce into a string by invoking the \code{print-x86}
  3728. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3729. the provided \key{runtime.c} file to \key{runtime.o} using
  3730. \key{gcc}. Run the script to test your compiler.
  3731. %
  3732. \fi}
  3733. {\if\edition\pythonEd\pythonColor
  3734. %
  3735. Run the \code{run-tests.py} script to to check whether the output
  3736. programs produce the same result as the input programs. That script
  3737. translates the x86 AST that you produce into a string by invoking the
  3738. \code{repr} method that is implemented by the x86 AST classes in
  3739. \code{x86\_ast.py}.
  3740. %
  3741. \fi}
  3742. \end{exercise}
  3743. \section{Challenge: Partial Evaluator for \LangVar{}}
  3744. \label{sec:pe-Lvar}
  3745. \index{subject}{partialevaluation@partial evaluation}
  3746. This section describes two optional challenge exercises that involve
  3747. adapting and improving the partial evaluator for \LangInt{} that was
  3748. introduced in section~\ref{sec:partial-evaluation}.
  3749. \begin{exercise}\label{ex:pe-Lvar}
  3750. \normalfont\normalsize
  3751. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3752. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3753. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3754. %
  3755. \racket{\key{let} binding}\python{assignment}
  3756. %
  3757. to the \LangInt{} language, so you will need to add cases for them in
  3758. the \code{pe\_exp}
  3759. %
  3760. \racket{function.}
  3761. %
  3762. \python{and \code{pe\_stmt} functions.}
  3763. %
  3764. Once complete, add the partial evaluation pass to the front of your
  3765. compiler, and make sure that your compiler still passes all the
  3766. tests.
  3767. \end{exercise}
  3768. \begin{exercise}
  3769. \normalfont\normalsize
  3770. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3771. \code{pe\_add} auxiliary functions with functions that know more about
  3772. arithmetic. For example, your partial evaluator should translate
  3773. {\if\edition\racketEd
  3774. \[
  3775. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3776. \code{(+ 2 (read))}
  3777. \]
  3778. \fi}
  3779. {\if\edition\pythonEd\pythonColor
  3780. \[
  3781. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3782. \code{2 + input\_int()}
  3783. \]
  3784. \fi}
  3785. %
  3786. To accomplish this, the \code{pe\_exp} function should produce output
  3787. in the form of the $\itm{residual}$ nonterminal of the following
  3788. grammar. The idea is that when processing an addition expression, we
  3789. can always produce one of the following: (1) an integer constant, (2)
  3790. an addition expression with an integer constant on the left-hand side
  3791. but not the right-hand side, or (3) an addition expression in which
  3792. neither subexpression is a constant.
  3793. %
  3794. {\if\edition\racketEd
  3795. \[
  3796. \begin{array}{lcl}
  3797. \itm{inert} &::=& \Var
  3798. \MID \LP\key{read}\RP
  3799. \MID \LP\key{-} ~\Var\RP
  3800. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3801. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3802. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3803. \itm{residual} &::=& \Int
  3804. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3805. \MID \itm{inert}
  3806. \end{array}
  3807. \]
  3808. \fi}
  3809. {\if\edition\pythonEd\pythonColor
  3810. \[
  3811. \begin{array}{lcl}
  3812. \itm{inert} &::=& \Var
  3813. \MID \key{input\_int}\LP\RP
  3814. \MID \key{-} \Var
  3815. \MID \key{-} \key{input\_int}\LP\RP
  3816. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3817. \itm{residual} &::=& \Int
  3818. \MID \Int ~ \key{+} ~ \itm{inert}
  3819. \MID \itm{inert}
  3820. \end{array}
  3821. \]
  3822. \fi}
  3823. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3824. inputs are $\itm{residual}$ expressions and they should return
  3825. $\itm{residual}$ expressions. Once the improvements are complete,
  3826. make sure that your compiler still passes all the tests. After
  3827. all, fast code is useless if it produces incorrect results!
  3828. \end{exercise}
  3829. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3830. {\if\edition\pythonEd\pythonColor
  3831. \chapter{Parsing}
  3832. \label{ch:parsing}
  3833. \setcounter{footnote}{0}
  3834. \index{subject}{parsing}
  3835. In this chapter we learn how to use the Lark parser
  3836. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3837. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3838. You will then be asked to use Lark to create a parser for \LangVar{}.
  3839. We also describe the parsing algorithms used inside Lark, studying the
  3840. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3841. A parser framework such as Lark takes in a specification of the
  3842. concrete syntax and an input program and produces a parse tree. Even
  3843. though a parser framework does most of the work for us, using one
  3844. properly requires some knowledge. In particular, we must learn about
  3845. its specification languages and we must learn how to deal with
  3846. ambiguity in our language specifications. Also, some algorithms, such
  3847. as LALR(1) place restrictions on the grammars they can handle, in
  3848. which case it helps to know the algorithm when trying to decipher the
  3849. error messages.
  3850. The process of parsing is traditionally subdivided into two phases:
  3851. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3852. analysis} (also called parsing). The lexical analysis phase
  3853. translates the sequence of characters into a sequence of
  3854. \emph{tokens}, that is, words consisting of several characters. The
  3855. parsing phase organizes the tokens into a \emph{parse tree} that
  3856. captures how the tokens were matched by rules in the grammar of the
  3857. language. The reason for the subdivision into two phases is to enable
  3858. the use of a faster but less powerful algorithm for lexical analysis
  3859. and the use of a slower but more powerful algorithm for parsing.
  3860. %
  3861. %% Likewise, parser generators typical come in pairs, with separate
  3862. %% generators for the lexical analyzer (or lexer for short) and for the
  3863. %% parser. A particularly influential pair of generators were
  3864. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3865. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3866. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3867. %% Compiler Compiler.
  3868. %
  3869. The Lark parser framework that we use in this chapter includes both
  3870. lexical analyzers and parsers. The next section discusses lexical
  3871. analysis and the remainder of the chapter discusses parsing.
  3872. \section{Lexical Analysis and Regular Expressions}
  3873. \label{sec:lex}
  3874. The lexical analyzers produced by Lark turn a sequence of characters
  3875. (a string) into a sequence of token objects. For example, a Lark
  3876. generated lexer for \LangInt{} converts the string
  3877. \begin{lstlisting}
  3878. 'print(1 + 3)'
  3879. \end{lstlisting}
  3880. \noindent into the following sequence of token objects
  3881. \begin{center}
  3882. \begin{minipage}{0.95\textwidth}
  3883. \begin{lstlisting}
  3884. Token('PRINT', 'print')
  3885. Token('LPAR', '(')
  3886. Token('INT', '1')
  3887. Token('PLUS', '+')
  3888. Token('INT', '3')
  3889. Token('RPAR', ')')
  3890. Token('NEWLINE', '\n')
  3891. \end{lstlisting}
  3892. \end{minipage}
  3893. \end{center}
  3894. Each token includes a field for its \code{type}, such as \code{'INT'},
  3895. and a field for its \code{value}, such as \code{'1'}.
  3896. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3897. specification language for Lark's lexer is one regular expression for
  3898. each type of token. The term \emph{regular} comes from the term
  3899. \emph{regular languages}, which are the languages that can be
  3900. recognized by a finite state machine. A \emph{regular expression} is a
  3901. pattern formed of the following core elements:\index{subject}{regular
  3902. expression}\footnote{Regular expressions traditionally include the
  3903. empty regular expression that matches any zero-length part of a
  3904. string, but Lark does not support the empty regular expression.}
  3905. \begin{itemize}
  3906. \item A single character $c$ is a regular expression and it only
  3907. matches itself. For example, the regular expression \code{a} only
  3908. matches with the string \code{'a'}.
  3909. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3910. R_2$ form a regular expression that matches any string that matches
  3911. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3912. matches the string \code{'a'} and the string \code{'c'}.
  3913. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3914. expression that matches any string that can be formed by
  3915. concatenating two strings, where the first string matches $R_1$ and
  3916. the second string matches $R_2$. For example, the regular expression
  3917. \code{(a|c)b} matches the strings \code{'ab'} and \code{'cb'}.
  3918. (Parentheses can be used to control the grouping of operators within
  3919. a regular expression.)
  3920. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3921. Kleene closure) is a regular expression that matches any string that
  3922. can be formed by concatenating zero or more strings that each match
  3923. the regular expression $R$. For example, the regular expression
  3924. \code{"((a|c)b)*"} matches the strings \code{'abcbab'} but not
  3925. \code{'abc'}.
  3926. \end{itemize}
  3927. For our convenience, Lark also accepts the following extended set of
  3928. regular expressions that are automatically translated into the core
  3929. regular expressions.
  3930. \begin{itemize}
  3931. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3932. c_n]$ is a regular expression that matches any one of the
  3933. characters. So $[c_1 c_2 \ldots c_n]$ is equivalent to
  3934. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3935. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3936. a regular expression that matches any character between $c_1$ and
  3937. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3938. letter in the alphabet.
  3939. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3940. is a regular expression that matches any string that can
  3941. be formed by concatenating one or more strings that each match $R$.
  3942. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3943. matches \code{'b'} and \code{'bzca'}.
  3944. \item A regular expression followed by a question mark $R\ttm{?}$
  3945. is a regular expression that matches any string that either
  3946. matches $R$ or that is the empty string.
  3947. For example, \code{a?b} matches both \code{'ab'} and \code{'b'}.
  3948. \item A string, such as \code{"hello"}, which matches itself,
  3949. that is, \code{'hello'}.
  3950. \end{itemize}
  3951. In a Lark grammar file, specify a name for each type of token followed
  3952. by a colon and then a regular expression surrounded by \code{/}
  3953. characters. For example, the \code{DIGIT}, \code{INT}, and
  3954. \code{NEWLINE} types of tokens are specified in the following way.
  3955. \begin{center}
  3956. \begin{minipage}{0.95\textwidth}
  3957. \begin{lstlisting}
  3958. DIGIT: /[0-9]/
  3959. INT: "-"? DIGIT+
  3960. NEWLINE: (/\r/? /\n/)+
  3961. \end{lstlisting}
  3962. \end{minipage}
  3963. \end{center}
  3964. \noindent In Lark, the regular expression operators can be used both
  3965. inside a regular expression, that is, between the \code{/} characters,
  3966. and they can be used to combine regular expressions, outside the
  3967. \code{/} characters.
  3968. \section{Grammars and Parse Trees}
  3969. \label{sec:CFG}
  3970. In section~\ref{sec:grammar} we learned how to use grammar rules to
  3971. specify the abstract syntax of a language. We now take a closer look
  3972. at using grammar rules to specify the concrete syntax. Recall that
  3973. each rule has a left-hand side and a right-hand side where the
  3974. left-hand side is a nonterminal and the right-hand side is a pattern
  3975. that defines what can be parsed as that nonterminal.
  3976. For concrete syntax, each right-hand side expresses a pattern for a
  3977. string, instead of a pattern for an abstract syntax tree. In
  3978. particular, each right-hand side is a sequence of
  3979. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  3980. terminal or nonterminal. A \emph{terminal}\index{subject}{terminal} is
  3981. a string. The nonterminals play the same role as in the abstract
  3982. syntax, defining categories of syntax. The nonterminals of a grammar
  3983. include the tokens defined in the lexer and all the nonterminals
  3984. defined by the grammar rules.
  3985. As an example, let us take a closer look at the concrete syntax of the
  3986. \LangInt{} language, repeated here.
  3987. \[
  3988. \begin{array}{l}
  3989. \LintGrammarPython \\
  3990. \begin{array}{rcl}
  3991. \LangInt{} &::=& \Stmt^{*}
  3992. \end{array}
  3993. \end{array}
  3994. \]
  3995. The Lark syntax for grammar rules differs slightly from the variant of
  3996. BNF that we use in this book. In particular, the notation $::=$ is
  3997. replaced by a single colon and the use of typewriter font for string
  3998. literals is replaced by quotation marks. The following grammar serves
  3999. as a first draft of a Lark grammar for \LangInt{}.
  4000. \begin{center}
  4001. \begin{minipage}{0.95\textwidth}
  4002. \begin{lstlisting}[escapechar=$]
  4003. exp: INT
  4004. | "input_int" "(" ")"
  4005. | "-" exp
  4006. | exp "+" exp
  4007. | exp "-" exp
  4008. | "(" exp ")"
  4009. stmt_list:
  4010. | stmt NEWLINE stmt_list
  4011. lang_int: stmt_list
  4012. \end{lstlisting}
  4013. \end{minipage}
  4014. \end{center}
  4015. Let us begin by discussing the rule \code{exp: INT} which says that if
  4016. the lexer matches a string to \code{INT}, then the parser also
  4017. categorizes the string as an \code{exp}. Recall that in
  4018. Section~\ref{sec:grammar} we defined the corresponding \Int{}
  4019. nonterminal with an English sentence. Here we specify \code{INT} more
  4020. formally using a type of token \code{INT} and its regular expression
  4021. \code{"-"? DIGIT+}.
  4022. The rule \code{exp: exp "+" exp} says that any string that matches
  4023. \code{exp}, followed by the \code{+} character, followed by another
  4024. string that matches \code{exp}, is itself an \code{exp}. For example,
  4025. the string \code{'1+3'} is an \code{exp} because \code{'1'} and
  4026. \code{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4027. the rule for addition applies to categorize \code{'1+3'} as an
  4028. \code{exp}. We can visualize the application of grammar rules to parse
  4029. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4030. internal node in the tree is an application of a grammar rule and is
  4031. labeled with its left-hand side nonterminal. Each leaf node is a
  4032. substring of the input program. The parse tree for \code{'1+3'} is
  4033. shown in figure~\ref{fig:simple-parse-tree}.
  4034. \begin{figure}[tbp]
  4035. \begin{tcolorbox}[colback=white]
  4036. \centering
  4037. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4038. \end{tcolorbox}
  4039. \caption{The parse tree for \code{'1+3'}.}
  4040. \label{fig:simple-parse-tree}
  4041. \end{figure}
  4042. The result of parsing \code{'1+3'} with this Lark grammar is the
  4043. following parse tree as represented by \code{Tree} and \code{Token}
  4044. objects.
  4045. \begin{lstlisting}
  4046. Tree('lang_int',
  4047. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4048. Tree('exp', [Token('INT', '3')])])]),
  4049. Token('NEWLINE', '\n')])
  4050. \end{lstlisting}
  4051. The nodes that come from the lexer are \code{Token} objects whereas
  4052. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4053. object has a \code{data} field containing the name of the nonterminal
  4054. for the grammar rule that was applied. Each \code{Tree} object also
  4055. has a \code{children} field that is a list containing trees and/or
  4056. tokens. Note that Lark does not produce nodes for string literals in
  4057. the grammar. For example, the \code{Tree} node for the addition
  4058. expression has only two children for the two integers but is missing
  4059. its middle child for the \code{"+"} terminal. This would be
  4060. problematic except that Lark provides a mechanism for customizing the
  4061. \code{data} field of each \code{Tree} node based on which rule was
  4062. applied. Next to each alternative in a grammar rule, write \code{->}
  4063. followed by a string that you would like to appear in the \code{data}
  4064. field. The following is a second draft of a Lark grammar for
  4065. \LangInt{}, this time with more specific labels on the \code{Tree}
  4066. nodes.
  4067. \begin{center}
  4068. \begin{minipage}{0.95\textwidth}
  4069. \begin{lstlisting}[escapechar=$]
  4070. exp: INT -> int
  4071. | "input_int" "(" ")" -> input_int
  4072. | "-" exp -> usub
  4073. | exp "+" exp -> add
  4074. | exp "-" exp -> sub
  4075. | "(" exp ")" -> paren
  4076. stmt: "print" "(" exp ")" -> print
  4077. | exp -> expr
  4078. stmt_list: -> empty_stmt
  4079. | stmt NEWLINE stmt_list -> add_stmt
  4080. lang_int: stmt_list -> module
  4081. \end{lstlisting}
  4082. \end{minipage}
  4083. \end{center}
  4084. Here is the resulting parse tree.
  4085. \begin{lstlisting}
  4086. Tree('module',
  4087. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4088. Tree('int', [Token('INT', '3')])])]),
  4089. Token('NEWLINE', '\n')])
  4090. \end{lstlisting}
  4091. \section{Ambiguous Grammars}
  4092. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4093. can be parsed in more than one way. For example, consider the string
  4094. \code{'1-2+3'}. This string can parsed in two different ways using
  4095. our draft grammar, resulting in the two parse trees shown in
  4096. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4097. interpreting the second parse tree would yield \code{-4} even through
  4098. the correct answer is \code{2}.
  4099. \begin{figure}[tbp]
  4100. \begin{tcolorbox}[colback=white]
  4101. \centering
  4102. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4103. \end{tcolorbox}
  4104. \caption{The two parse trees for \code{'1-2+3'}.}
  4105. \label{fig:ambig-parse-tree}
  4106. \end{figure}
  4107. To deal with this problem we can change the grammar by categorizing
  4108. the syntax in a more fine grained fashion. In this case we want to
  4109. disallow the application of the rule \code{exp: exp "-" exp} when the
  4110. child on the right is an addition. To do this we can replace the
  4111. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4112. the expressions except for addition, as in the following.
  4113. \begin{center}
  4114. \begin{minipage}{0.95\textwidth}
  4115. \begin{lstlisting}[escapechar=$]
  4116. exp: exp "-" exp_no_add -> sub
  4117. | exp "+" exp -> add
  4118. | exp_no_add
  4119. exp_no_add: INT -> int
  4120. | "input_int" "(" ")" -> input_int
  4121. | "-" exp -> usub
  4122. | exp "-" exp_no_add -> sub
  4123. | "(" exp ")" -> paren
  4124. \end{lstlisting}
  4125. \end{minipage}
  4126. \end{center}
  4127. However, there remains some ambiguity in the grammar. For example, the
  4128. string \code{'1-2-3'} can still be parsed in two different ways, as
  4129. \code{'(1-2)-3'} (correct) or \code{'1-(2-3)'} (incorrect). That is
  4130. to say, subtraction is left associative. Likewise, addition in Python
  4131. is left associative. We also need to consider the interaction of unary
  4132. subtraction with both addition and subtraction. How should we parse
  4133. \code{'-1+2'}? Unary subtraction has higher
  4134. \emph{precendence}\index{subject}{precedence} than addition and
  4135. subtraction, so \code{'-1+2'} should parse the same as \code{'(-1)+2'}
  4136. and not \code{'-(1+2)'}. The grammar in
  4137. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4138. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4139. all the other expressions, and uses \code{exp\_hi} for the second
  4140. child in the rules for addition and subtraction. Furthermore, unary
  4141. subtraction uses \code{exp\_hi} for its child.
  4142. For languages with more operators and more precedence levels, one must
  4143. refine the \code{exp} nonterminal into several nonterminals, one for
  4144. each precedence level.
  4145. \begin{figure}[tbp]
  4146. \begin{tcolorbox}[colback=white]
  4147. \centering
  4148. \begin{lstlisting}[escapechar=$]
  4149. exp: exp "+" exp_hi -> add
  4150. | exp "-" exp_hi -> sub
  4151. | exp_hi
  4152. exp_hi: INT -> int
  4153. | "input_int" "(" ")" -> input_int
  4154. | "-" exp_hi -> usub
  4155. | "(" exp ")" -> paren
  4156. stmt: "print" "(" exp ")" -> print
  4157. | exp -> expr
  4158. stmt_list: -> empty_stmt
  4159. | stmt NEWLINE stmt_list -> add_stmt
  4160. lang_int: stmt_list -> module
  4161. \end{lstlisting}
  4162. \end{tcolorbox}
  4163. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4164. \label{fig:Lint-lark-grammar}
  4165. \end{figure}
  4166. \section{From Parse Trees to Abstract Syntax Trees}
  4167. As we have seen, the output of a Lark parser is a parse tree, that is,
  4168. a tree consisting of \code{Tree} and \code{Token} nodes. So the next
  4169. step is to convert the parse tree to an abstract syntax tree. This can
  4170. be accomplished with a recursive function that inspects the
  4171. \code{data} field of each node and then constructs the corresponding
  4172. AST node, using recursion to handle its children. The following is an
  4173. excerpt of the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4174. \begin{center}
  4175. \begin{minipage}{0.95\textwidth}
  4176. \begin{lstlisting}
  4177. def parse_tree_to_ast(e):
  4178. if e.data == 'int':
  4179. return Constant(int(e.children[0].value))
  4180. elif e.data == 'input_int':
  4181. return Call(Name('input_int'), [])
  4182. elif e.data == 'add':
  4183. e1, e2 = e.children
  4184. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4185. ...
  4186. else:
  4187. raise Exception('unhandled parse tree', e)
  4188. \end{lstlisting}
  4189. \end{minipage}
  4190. \end{center}
  4191. \begin{exercise}
  4192. \normalfont\normalsize
  4193. %
  4194. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4195. default parsing algorithm (Earley) with the \code{ambiguity} option
  4196. set to \code{'explicit'} so that if your grammar is ambiguous, the
  4197. output will include multiple parse trees which will indicate to you
  4198. that there is a problem with your grammar. Your parser should ignore
  4199. white space so we recommend using Lark's \code{\%ignore} directive
  4200. as follows.
  4201. \begin{lstlisting}
  4202. WS: /[ \t\f\r\n]/+
  4203. %ignore WS
  4204. \end{lstlisting}
  4205. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4206. Lark parser instead of using the \code{parse} function from
  4207. the \code{ast} module. Test your compiler on all of the \LangVar{}
  4208. programs that you have created and create four additional programs
  4209. that test for ambiguities in your grammar.
  4210. \end{exercise}
  4211. \section{The Earley Algorithm}
  4212. \label{sec:earley}
  4213. In this section we discuss the parsing algorithm of
  4214. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4215. algorithm is powerful in that it can handle any context-free grammar,
  4216. which makes it easy to use. However, it is not the most efficient
  4217. parsing algorithm: it is $O(n^3)$ for ambiguous grammars and $O(n^2)$
  4218. for unambiguous grammars, where $n$ is the number of tokens in the
  4219. input string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr}
  4220. we learn about the LALR(1) algorithm, which is more efficient but
  4221. cannot handle all context-free grammars.
  4222. The Earley algorithm can be viewed as an interpreter; it treats the
  4223. grammar as the program being interpreted and it treats the concrete
  4224. syntax of the program-to-be-parsed as its input. The Earley algorithm
  4225. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4226. keep track of its progress and to memoize its results. The chart is an
  4227. array with one slot for each position in the input string, where
  4228. position $0$ is before the first character and position $n$ is
  4229. immediately after the last character. So the array has length $n+1$
  4230. for an input string of length $n$. Each slot in the chart contains a
  4231. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4232. with a period indicating how much of its right-hand side has already
  4233. been parsed. For example, the dotted rule
  4234. \begin{lstlisting}
  4235. exp: exp "+" . exp_hi
  4236. \end{lstlisting}
  4237. represents a partial parse that has matched an \code{exp} followed by
  4238. \code{+}, but has not yet parsed an \code{exp} to the right of
  4239. \code{+}.
  4240. %
  4241. The Earley algorithm starts with an initialization phase, and then
  4242. repeats three actions---prediction, scanning, and completion---for as
  4243. long as opportunities arise. We demonstrate the Earley algorithm on a
  4244. running example, parsing the following program:
  4245. \begin{lstlisting}
  4246. print(1 + 3)
  4247. \end{lstlisting}
  4248. The algorithm's initialization phase creates dotted rules for all the
  4249. grammar rules whose left-hand side is the start symbol and places them
  4250. in slot $0$ of the chart. We also record the starting position of the
  4251. dotted rule in parentheses on the right. For example, given the
  4252. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4253. \begin{lstlisting}
  4254. lang_int: . stmt_list (0)
  4255. \end{lstlisting}
  4256. in slot $0$ of the chart. The algorithm then proceeds with
  4257. \emph{prediction} actions in which it adds more dotted rules to the
  4258. chart based on which nonterminals come immediately after a period. In
  4259. the above, the nonterminal \code{stmt\_list} appears after a period,
  4260. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4261. period at the beginning of their right-hand sides, as follows:
  4262. \begin{lstlisting}
  4263. stmt_list: . (0)
  4264. stmt_list: . stmt NEWLINE stmt_list (0)
  4265. \end{lstlisting}
  4266. We continue to perform prediction actions as more opportunities
  4267. arise. For example, the \code{stmt} nonterminal now appears after a
  4268. period, so we add all the rules for \code{stmt}.
  4269. \begin{lstlisting}
  4270. stmt: . "print" "(" exp ")" (0)
  4271. stmt: . exp (0)
  4272. \end{lstlisting}
  4273. This reveals yet more opportunities for prediction, so we add the grammar
  4274. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4275. \begin{lstlisting}[escapechar=$]
  4276. exp: . exp "+" exp_hi (0)
  4277. exp: . exp "-" exp_hi (0)
  4278. exp: . exp_hi (0)
  4279. exp_hi: . INT (0)
  4280. exp_hi: . "input_int" "(" ")" (0)
  4281. exp_hi: . "-" exp_hi (0)
  4282. exp_hi: . "(" exp ")" (0)
  4283. \end{lstlisting}
  4284. We have exhausted the opportunities for prediction, so the algorithm
  4285. proceeds to \emph{scanning}, in which we inspect the next input token
  4286. and look for a dotted rule at the current position that has a matching
  4287. terminal immediately following the period. In our running example, the
  4288. first input token is \code{"print"} so we identify the rule in slot
  4289. $0$ of the chart where \code{"print"} follows the period:
  4290. \begin{lstlisting}
  4291. stmt: . "print" "(" exp ")" (0)
  4292. \end{lstlisting}
  4293. We advance the period past \code{"print"} and add the resulting rule
  4294. to slot $1$ of the chart:
  4295. \begin{lstlisting}
  4296. stmt: "print" . "(" exp ")" (0)
  4297. \end{lstlisting}
  4298. If the new dotted rule had a nonterminal after the period, we would
  4299. need to carry out a prediction action, adding more dotted rules into
  4300. slot $1$. That is not the case, so we continue scanning. The next
  4301. input token is \code{"("}, so we add the following to slot $2$ of the
  4302. chart.
  4303. \begin{lstlisting}
  4304. stmt: "print" "(" . exp ")" (0)
  4305. \end{lstlisting}
  4306. Now we have a nonterminal after the period, so we carry out several
  4307. prediction actions, adding dotted rules for \code{exp} and
  4308. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4309. starting position $2$.
  4310. \begin{lstlisting}[escapechar=$]
  4311. exp: . exp "+" exp_hi (2)
  4312. exp: . exp "-" exp_hi (2)
  4313. exp: . exp_hi (2)
  4314. exp_hi: . INT (2)
  4315. exp_hi: . "input_int" "(" ")" (2)
  4316. exp_hi: . "-" exp_hi (2)
  4317. exp_hi: . "(" exp ")" (2)
  4318. \end{lstlisting}
  4319. With this prediction complete, we return to scanning, noting that the
  4320. next input token is \code{"1"} which the lexer parses as an
  4321. \code{INT}. There is a matching rule in slot $2$:
  4322. \begin{lstlisting}
  4323. exp_hi: . INT (2)
  4324. \end{lstlisting}
  4325. so we advance the period and put the following rule is slot $3$.
  4326. \begin{lstlisting}
  4327. exp_hi: INT . (2)
  4328. \end{lstlisting}
  4329. This brings us to \emph{completion} actions. When the period reaches
  4330. the end of a dotted rule, we recognize that the substring
  4331. has matched the nonterminal on the left-hand side of the rule, in this case
  4332. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4333. rules in slot $2$ (the starting position for the finished rule) if
  4334. the period is immediately followed by \code{exp\_hi}. So we identify
  4335. \begin{lstlisting}
  4336. exp: . exp_hi (2)
  4337. \end{lstlisting}
  4338. and add the following dotted rule to slot $3$
  4339. \begin{lstlisting}
  4340. exp: exp_hi . (2)
  4341. \end{lstlisting}
  4342. This triggers another completion step for the nonterminal \code{exp},
  4343. adding two more dotted rules to slot $3$.
  4344. \begin{lstlisting}[escapechar=$]
  4345. exp: exp . "+" exp_hi (2)
  4346. exp: exp . "-" exp_hi (2)
  4347. \end{lstlisting}
  4348. Returning to scanning, the next input token is \code{"+"}, so
  4349. we add the following to slot $4$.
  4350. \begin{lstlisting}[escapechar=$]
  4351. exp: exp "+" . exp_hi (2)
  4352. \end{lstlisting}
  4353. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4354. the following dotted rules to slot $4$ of the chart.
  4355. \begin{lstlisting}[escapechar=$]
  4356. exp_hi: . INT (4)
  4357. exp_hi: . "input_int" "(" ")" (4)
  4358. exp_hi: . "-" exp_hi (4)
  4359. exp_hi: . "(" exp ")" (4)
  4360. \end{lstlisting}
  4361. The next input token is \code{"3"} which the lexer categorized as an
  4362. \code{INT}, so we advance the period past \code{INT} for the rules in
  4363. slot $4$, of which there is just one, and put the following in slot $5$.
  4364. \begin{lstlisting}[escapechar=$]
  4365. exp_hi: INT . (4)
  4366. \end{lstlisting}
  4367. The period at the end of the rule triggers a completion action for the
  4368. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4369. So we advance the period and put the following in slot $5$.
  4370. \begin{lstlisting}[escapechar=$]
  4371. exp: exp "+" exp_hi . (2)
  4372. \end{lstlisting}
  4373. This triggers another completion action for the rules in slot $2$ that
  4374. have a period before \code{exp}.
  4375. \begin{lstlisting}[escapechar=$]
  4376. stmt: "print" "(" exp . ")" (0)
  4377. exp: exp . "+" exp_hi (2)
  4378. exp: exp . "-" exp_hi (2)
  4379. \end{lstlisting}
  4380. We scan the next input token \code{")"}, placing the following dotted
  4381. rule in slot $6$.
  4382. \begin{lstlisting}[escapechar=$]
  4383. stmt: "print" "(" exp ")" . (0)
  4384. \end{lstlisting}
  4385. This triggers the completion of \code{stmt} in slot $0$
  4386. \begin{lstlisting}
  4387. stmt_list: stmt . NEWLINE stmt_list (0)
  4388. \end{lstlisting}
  4389. The last input token is a \code{NEWLINE}, so we advance the period
  4390. and place the new dotted rule in slot $7$.
  4391. \begin{lstlisting}
  4392. stmt_list: stmt NEWLINE . stmt_list (0)
  4393. \end{lstlisting}
  4394. We are close to the end of parsing the input!
  4395. The period is before the \code{stmt\_list} nonterminal, so we
  4396. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4397. \begin{lstlisting}
  4398. stmt_list: . (7)
  4399. stmt_list: . stmt NEWLINE stmt_list (7)
  4400. stmt: . "print" "(" exp ")" (7)
  4401. stmt: . exp (7)
  4402. \end{lstlisting}
  4403. There is immediately an opportunity for completion of \code{stmt\_list},
  4404. so we add the following to slot $7$.
  4405. \begin{lstlisting}
  4406. stmt_list: stmt NEWLINE stmt_list . (0)
  4407. \end{lstlisting}
  4408. This triggers another completion action for \code{stmt\_list} in slot $0$
  4409. \begin{lstlisting}
  4410. lang_int: stmt_list . (0)
  4411. \end{lstlisting}
  4412. which in turn completes \code{lang\_int}, the start symbol of the
  4413. grammar, so the parsing of the input is complete.
  4414. For reference, we now give a general description of the Earley
  4415. algorithm.
  4416. \begin{enumerate}
  4417. \item The algorithm begins by initializing slot $0$ of the chart with the
  4418. grammar rule for the start symbol, placing a period at the beginning
  4419. of the right-hand side, and recording its starting position as $0$.
  4420. \item The algorithm repeatedly applies the following three kinds of
  4421. actions for as long as there are opportunities to do so.
  4422. \begin{itemize}
  4423. \item Prediction: if there is a rule in slot $k$ whose period comes
  4424. before a nonterminal, add the rules for that nonterminal into slot
  4425. $k$, placing a period at the beginning of their right-hand sides
  4426. and recording their starting position as $k$.
  4427. \item Scanning: If the token at position $k$ of the input string
  4428. matches the symbol after the period in a dotted rule in slot $k$
  4429. of the chart, advance the period in the dotted rule, adding
  4430. the result to slot $k+1$.
  4431. \item Completion: If a dotted rule in slot $k$ has a period at the
  4432. end, inspect the rules in the slot corresponding to the starting
  4433. position of the completed rule. If any of those rules have a
  4434. nonterminal following their period that matches the left-hand side
  4435. of the completed rule, then advance their period, placing the new
  4436. dotted rule in slot $k$.
  4437. \end{itemize}
  4438. While repeating these three actions, take care to never add
  4439. duplicate dotted rules to the chart.
  4440. \end{enumerate}
  4441. We have described how the Earley algorithm recognizes that an input
  4442. string matches a grammar, but we have not described how it builds a
  4443. parse tree. The basic idea is simple, but building parse trees in an
  4444. efficient way is more complex, requiring a data structure called a
  4445. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4446. to attach a partial parse tree to every dotted rule in the chart.
  4447. Initially, the tree node associated with a dotted rule has no
  4448. children. As the period moves to the right, the nodes from the
  4449. subparses are added as children to the tree node.
  4450. As mentioned at the beginning of this section, the Earley algorithm is
  4451. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4452. files that contain thousands of tokens in a reasonable amount of time,
  4453. but not millions.
  4454. %
  4455. In the next section we discuss the LALR(1) parsing algorithm, which is
  4456. efficient enough to use with even the largest of input files.
  4457. \section{The LALR(1) Algorithm}
  4458. \label{sec:lalr}
  4459. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4460. two phase approach in which it first compiles the grammar into a state
  4461. machine and then runs the state machine to parse an input string. The
  4462. second phase has time complexity $O(n)$ where $n$ is the number of
  4463. tokens in the input, so LALR(1) is the best one could hope for with
  4464. respect to efficiency.
  4465. %
  4466. A particularly influential implementation of LALR(1) is the
  4467. \texttt{yacc} parser generator by \citet{Johnson:1979qy}, which stands
  4468. for Yet Another Compiler Compiler.
  4469. %
  4470. The LALR(1) state machine uses a stack to record its progress in
  4471. parsing the input string. Each element of the stack is a pair: a
  4472. state number and a grammar symbol (a terminal or nonterminal). The
  4473. symbol characterizes the input that has been parsed so-far and the
  4474. state number is used to remember how to proceed once the next
  4475. symbol-worth of input has been parsed. Each state in the machine
  4476. represents where the parser stands in the parsing process with respect
  4477. to certain grammar rules. In particular, each state is associated with
  4478. a set of dotted rules.
  4479. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4480. (also called parse table) for the following simple but ambiguous
  4481. grammar:
  4482. \begin{lstlisting}[escapechar=$]
  4483. exp: INT
  4484. | exp "+" exp
  4485. stmt: "print" exp
  4486. start: stmt
  4487. \end{lstlisting}
  4488. Consider state 1 in Figure~\ref{fig:shift-reduce}. The parser has just
  4489. read in a \lstinline{"print"} token, so the top of the stack is
  4490. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4491. the input according to grammar rule 1, which is signified by showing
  4492. rule 1 with a period after the \code{"print"} token and before the
  4493. \code{exp} nonterminal. There are several rules that could apply next,
  4494. both rule 2 and 3, so state 1 also shows those rules with a period at
  4495. the beginning of their right-hand sides. The edges between states
  4496. indicate which transitions the machine should make depending on the
  4497. next input token. So, for example, if the next input token is
  4498. \code{INT} then the parser will push \code{INT} and the target state 4
  4499. on the stack and transition to state 4. Suppose we are now at the end
  4500. of the input. In state 4 it says we should reduce by rule 3, so we pop
  4501. from the stack the same number of items as the number of symbols in
  4502. the right-hand side of the rule, in this case just one. We then
  4503. momentarily jump to the state at the top of the stack (state 1) and
  4504. then follow the goto edge that corresponds to the left-hand side of
  4505. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4506. state 3. (A slightly longer example parse is shown in
  4507. Figure~\ref{fig:shift-reduce}.)
  4508. \begin{figure}[htbp]
  4509. \centering
  4510. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4511. \caption{An LALR(1) parse table and a trace of an example run.}
  4512. \label{fig:shift-reduce}
  4513. \end{figure}
  4514. In general, the algorithm works as follows. Set the current state to
  4515. state $0$. Then repeat the following, looking at the next input token.
  4516. \begin{itemize}
  4517. \item If there there is a shift edge for the input token in the
  4518. current state, push the edge's target state and the input token on
  4519. the stack and proceed to the edge's target state.
  4520. \item If there is a reduce action for the input token in the current
  4521. state, pop $k$ elements from the stack, where $k$ is the number of
  4522. symbols in the right-hand side of the rule being reduced. Jump to
  4523. the state at the top of the stack and then follow the goto edge for
  4524. the nonterminal that matches the left-hand side of the rule that we
  4525. reducing by. Push the edge's target state and the nonterminal on the
  4526. stack.
  4527. \end{itemize}
  4528. Notice that in state 6 of Figure~\ref{fig:shift-reduce} there is both
  4529. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4530. algorithm does not know which action to take in this case. When a
  4531. state has both a shift and a reduce action for the same token, we say
  4532. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4533. will arise, for example, when trying to parse the input
  4534. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2}
  4535. the parser will be in state 6, and it will not know whether to
  4536. reduce to form an \code{exp} of \lstinline{1 + 2}, or whether it
  4537. should proceed by shifting the next \lstinline{+} from the input.
  4538. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4539. arises when there are two reduce actions in a state for the same
  4540. token. To understand which grammars gives rise to shift/reduce and
  4541. reduce/reduce conflicts, it helps to know how the parse table is
  4542. generated from the grammar, which we discuss next.
  4543. The parse table is generated one state at a time. State 0 represents
  4544. the start of the parser. We add the grammar rule for the start symbol
  4545. to this state with a period at the beginning of the right-hand side,
  4546. similar to the initialization phase of the Earley parser. If the
  4547. period appears immediately before another nonterminal, we add all the
  4548. rules with that nonterminal on the left-hand side. Again, we place a
  4549. period at the beginning of the right-hand side of each the new
  4550. rules. This process, called \emph{state closure}, is continued
  4551. until there are no more rules to add (similar to the prediction
  4552. actions of an Earley parser). We then examine each dotted rule in the
  4553. current state $I$. Suppose a dotted rule has the form $A ::=
  4554. s_1.\,X s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4555. are sequences of symbols. We create a new state, call it $J$. If $X$
  4556. is a terminal, we create a shift edge from $I$ to $J$ (analogous to
  4557. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4558. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4559. state $J$. We start by adding all dotted rules from state $I$ that
  4560. have the form $B ::= s_1.\,Xs_2$ (where $B$ is any nonterminal and
  4561. $s_1$ and $s_2$ are arbitrary sequences of symbols), but with
  4562. the period moved past the $X$. (This is analogous to completion in
  4563. the Earley algorithm.) We then perform state closure on $J$. This
  4564. process repeats until there are no more states or edges to add.
  4565. We then mark states as accepting states if they have a dotted rule
  4566. that is the start rule with a period at the end. Also, to add
  4567. in the reduce actions, we look for any state containing a dotted rule
  4568. with a period at the end. Let $n$ be the rule number for this dotted
  4569. rule. We then put a reduce $n$ action into that state for every token
  4570. $Y$. For example, in Figure~\ref{fig:shift-reduce} state 4 has an
  4571. dotted rule with a period at the end. We therefore put a reduce by
  4572. rule 3 action into state 4 for every
  4573. token.
  4574. When inserting reduce actions, take care to spot any shift/reduce or
  4575. reduce/reduce conflicts. If there are any, abort the construction of
  4576. the parse table.
  4577. \begin{exercise}
  4578. \normalfont\normalsize
  4579. %
  4580. On a piece of paper, walk through the parse table generation process
  4581. for the grammar at the top of figure~\ref{fig:shift-reduce} and check
  4582. your results against parse table in figure~\ref{fig:shift-reduce}.
  4583. \end{exercise}
  4584. \begin{exercise}
  4585. \normalfont\normalsize
  4586. %
  4587. Change the parser in your compiler for \LangVar{} to set the
  4588. \code{parser} option of Lark to \code{'lalr'}. Test your compiler on
  4589. all the \LangVar{} programs that you have created. In doing so, Lark
  4590. may signal an error due to shift/reduce or reduce/reduce conflicts
  4591. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4592. remove those conflicts.
  4593. \end{exercise}
  4594. \section{Further Reading}
  4595. In this chapter we have just scratched the surface of the field of
  4596. parsing, with the study of a very general but less efficient algorithm
  4597. (Earley) and with a more limited but highly efficient algorithm
  4598. (LALR). There are many more algorithms, and classes of grammars, that
  4599. fall between these two ends of the spectrum. We recommend the reader
  4600. to \citet{Aho:2006wb} for a thorough treatment of parsing.
  4601. Regarding lexical analysis, we described the specification language,
  4602. the regular expressions, but not the algorithms for recognizing them.
  4603. In short, regular expressions can be translated to nondeterministic
  4604. finite automata, which in turn are translated to finite automata. We
  4605. refer the reader again to \citet{Aho:2006wb} for all the details on
  4606. lexical analysis.
  4607. \fi}
  4608. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4609. \chapter{Register Allocation}
  4610. \label{ch:register-allocation-Lvar}
  4611. \setcounter{footnote}{0}
  4612. \index{subject}{register allocation}
  4613. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4614. storing variables on the procedure call stack. The CPU may require tens
  4615. to hundreds of cycles to access a location on the stack, whereas
  4616. accessing a register takes only a single cycle. In this chapter we
  4617. improve the efficiency of our generated code by storing some variables
  4618. in registers. The goal of register allocation is to fit as many
  4619. variables into registers as possible. Some programs have more
  4620. variables than registers, so we cannot always map each variable to a
  4621. different register. Fortunately, it is common for different variables
  4622. to be in use during different periods of time during program
  4623. execution, and in those cases we can map multiple variables to the
  4624. same register.
  4625. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4626. example. The source program is on the left and the output of
  4627. instruction selection\index{subject}{instruction selection}
  4628. is on the right. The program is almost
  4629. completely in the x86 assembly language, but it still uses variables.
  4630. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4631. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4632. the other hand, is used only after this point, so \code{x} and
  4633. \code{z} could share the same register.
  4634. \begin{figure}
  4635. \begin{tcolorbox}[colback=white]
  4636. \begin{minipage}{0.45\textwidth}
  4637. Example \LangVar{} program:
  4638. % var_test_28.rkt
  4639. {\if\edition\racketEd
  4640. \begin{lstlisting}
  4641. (let ([v 1])
  4642. (let ([w 42])
  4643. (let ([x (+ v 7)])
  4644. (let ([y x])
  4645. (let ([z (+ x w)])
  4646. (+ z (- y)))))))
  4647. \end{lstlisting}
  4648. \fi}
  4649. {\if\edition\pythonEd\pythonColor
  4650. \begin{lstlisting}
  4651. v = 1
  4652. w = 42
  4653. x = v + 7
  4654. y = x
  4655. z = x + w
  4656. print(z + (- y))
  4657. \end{lstlisting}
  4658. \fi}
  4659. \end{minipage}
  4660. \begin{minipage}{0.45\textwidth}
  4661. After instruction selection:
  4662. {\if\edition\racketEd
  4663. \begin{lstlisting}
  4664. locals-types:
  4665. x : Integer, y : Integer,
  4666. z : Integer, t : Integer,
  4667. v : Integer, w : Integer
  4668. start:
  4669. movq $1, v
  4670. movq $42, w
  4671. movq v, x
  4672. addq $7, x
  4673. movq x, y
  4674. movq x, z
  4675. addq w, z
  4676. movq y, t
  4677. negq t
  4678. movq z, %rax
  4679. addq t, %rax
  4680. jmp conclusion
  4681. \end{lstlisting}
  4682. \fi}
  4683. {\if\edition\pythonEd\pythonColor
  4684. \begin{lstlisting}
  4685. movq $1, v
  4686. movq $42, w
  4687. movq v, x
  4688. addq $7, x
  4689. movq x, y
  4690. movq x, z
  4691. addq w, z
  4692. movq y, tmp_0
  4693. negq tmp_0
  4694. movq z, tmp_1
  4695. addq tmp_0, tmp_1
  4696. movq tmp_1, %rdi
  4697. callq print_int
  4698. \end{lstlisting}
  4699. \fi}
  4700. \end{minipage}
  4701. \end{tcolorbox}
  4702. \caption{A running example for register allocation.}
  4703. \label{fig:reg-eg}
  4704. \end{figure}
  4705. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4706. compute where a variable is in use. Once we have that information, we
  4707. compute which variables are in use at the same time, that is, which ones
  4708. \emph{interfere}\index{subject}{interfere} with each other, and
  4709. represent this relation as an undirected graph whose vertices are
  4710. variables and edges indicate when two variables interfere
  4711. (section~\ref{sec:build-interference}). We then model register
  4712. allocation as a graph coloring problem
  4713. (section~\ref{sec:graph-coloring}).
  4714. If we run out of registers despite these efforts, we place the
  4715. remaining variables on the stack, similarly to how we handled
  4716. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4717. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4718. location. The decision to spill a variable is handled as part of the
  4719. graph coloring process.
  4720. We make the simplifying assumption that each variable is assigned to
  4721. one location (a register or stack address). A more sophisticated
  4722. approach is to assign a variable to one or more locations in different
  4723. regions of the program. For example, if a variable is used many times
  4724. in short sequence and then used again only after many other
  4725. instructions, it could be more efficient to assign the variable to a
  4726. register during the initial sequence and then move it to the stack for
  4727. the rest of its lifetime. We refer the interested reader to
  4728. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4729. approach.
  4730. % discuss prioritizing variables based on how much they are used.
  4731. \section{Registers and Calling Conventions}
  4732. \label{sec:calling-conventions}
  4733. \index{subject}{calling conventions}
  4734. As we perform register allocation, we must be aware of the
  4735. \emph{calling conventions} \index{subject}{calling conventions} that
  4736. govern how function calls are performed in x86.
  4737. %
  4738. Even though \LangVar{} does not include programmer-defined functions,
  4739. our generated code includes a \code{main} function that is called by
  4740. the operating system and our generated code contains calls to the
  4741. \code{read\_int} function.
  4742. Function calls require coordination between two pieces of code that
  4743. may be written by different programmers or generated by different
  4744. compilers. Here we follow the System V calling conventions that are
  4745. used by the GNU C compiler on Linux and
  4746. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4747. %
  4748. The calling conventions include rules about how functions share the
  4749. use of registers. In particular, the caller is responsible for freeing
  4750. some registers prior to the function call for use by the callee.
  4751. These are called the \emph{caller-saved registers}
  4752. \index{subject}{caller-saved registers}
  4753. and they are
  4754. \begin{lstlisting}
  4755. rax rcx rdx rsi rdi r8 r9 r10 r11
  4756. \end{lstlisting}
  4757. On the other hand, the callee is responsible for preserving the values
  4758. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4759. which are
  4760. \begin{lstlisting}
  4761. rsp rbp rbx r12 r13 r14 r15
  4762. \end{lstlisting}
  4763. We can think about this caller/callee convention from two points of
  4764. view, the caller view and the callee view, as follows:
  4765. \begin{itemize}
  4766. \item The caller should assume that all the caller-saved registers get
  4767. overwritten with arbitrary values by the callee. On the other hand,
  4768. the caller can safely assume that all the callee-saved registers
  4769. retain their original values.
  4770. \item The callee can freely use any of the caller-saved registers.
  4771. However, if the callee wants to use a callee-saved register, the
  4772. callee must arrange to put the original value back in the register
  4773. prior to returning to the caller. This can be accomplished by saving
  4774. the value to the stack in the prelude of the function and restoring
  4775. the value in the conclusion of the function.
  4776. \end{itemize}
  4777. In x86, registers are also used for passing arguments to a function
  4778. and for the return value. In particular, the first six arguments of a
  4779. function are passed in the following six registers, in this order.
  4780. \begin{lstlisting}
  4781. rdi rsi rdx rcx r8 r9
  4782. \end{lstlisting}
  4783. We refer to these six registers are the argument-passing registers
  4784. \index{subject}{argument-passing registers}.
  4785. If there are more than six arguments, the convention is to use space
  4786. on the frame of the caller for the rest of the arguments. In
  4787. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4788. argument and the rest of the arguments, which simplifies the treatment
  4789. of efficient tail calls.
  4790. %
  4791. \racket{For now, the only function we care about is \code{read\_int},
  4792. which takes zero arguments.}
  4793. %
  4794. \python{For now, the only functions we care about are \code{read\_int}
  4795. and \code{print\_int}, which take zero and one argument, respectively.}
  4796. %
  4797. The register \code{rax} is used for the return value of a function.
  4798. The next question is how these calling conventions impact register
  4799. allocation. Consider the \LangVar{} program presented in
  4800. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4801. example from the caller point of view and then from the callee point
  4802. of view. We refer to a variable that is in use during a function call
  4803. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4804. The program makes two calls to \READOP{}. The variable \code{x} is
  4805. call-live because it is in use during the second call to \READOP{}; we
  4806. must ensure that the value in \code{x} does not get overwritten during
  4807. the call to \READOP{}. One obvious approach is to save all the values
  4808. that reside in caller-saved registers to the stack prior to each
  4809. function call and to restore them after each call. That way, if the
  4810. register allocator chooses to assign \code{x} to a caller-saved
  4811. register, its value will be preserved across the call to \READOP{}.
  4812. However, saving and restoring to the stack is relatively slow. If
  4813. \code{x} is not used many times, it may be better to assign \code{x}
  4814. to a stack location in the first place. Or better yet, if we can
  4815. arrange for \code{x} to be placed in a callee-saved register, then it
  4816. won't need to be saved and restored during function calls.
  4817. We recommend an approach that captures these issues in the
  4818. interference graph, without complicating the graph coloring algorithm.
  4819. During liveness analysis we know which variables are call-live because
  4820. we compute which variables are in use at every instruction
  4821. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4822. interference graph (section~\ref{sec:build-interference}), we can
  4823. place an edge in the interference graph between each call-live
  4824. variable and the caller-saved registers. This will prevent the graph
  4825. coloring algorithm from assigning call-live variables to caller-saved
  4826. registers.
  4827. On the other hand, for variables that are not call-live, we prefer
  4828. placing them in caller-saved registers to leave more room for
  4829. call-live variables in the callee-saved registers. This can also be
  4830. implemented without complicating the graph coloring algorithm. We
  4831. recommend that the graph coloring algorithm assign variables to
  4832. natural numbers, choosing the lowest number for which there is no
  4833. interference. After the coloring is complete, we map the numbers to
  4834. registers and stack locations: mapping the lowest numbers to
  4835. caller-saved registers, the next lowest to callee-saved registers, and
  4836. the largest numbers to stack locations. This ordering gives preference
  4837. to registers over stack locations and to caller-saved registers over
  4838. callee-saved registers.
  4839. Returning to the example in
  4840. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4841. generated x86 code on the right-hand side. Variable \code{x} is
  4842. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4843. in a safe place during the second call to \code{read\_int}. Next,
  4844. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4845. because \code{y} is not a call-live variable.
  4846. We have completed the analysis from the caller point of view, so now
  4847. we switch to the callee point of view, focusing on the prelude and
  4848. conclusion of the \code{main} function. As usual, the prelude begins
  4849. with saving the \code{rbp} register to the stack and setting the
  4850. \code{rbp} to the current stack pointer. We now know why it is
  4851. necessary to save the \code{rbp}: it is a callee-saved register. The
  4852. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4853. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4854. (\code{x}). The other callee-saved registers are not saved in the
  4855. prelude because they are not used. The prelude subtracts 8 bytes from
  4856. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4857. conclusion, we see that \code{rbx} is restored from the stack with a
  4858. \code{popq} instruction.
  4859. \index{subject}{prelude}\index{subject}{conclusion}
  4860. \begin{figure}[tp]
  4861. \begin{tcolorbox}[colback=white]
  4862. \begin{minipage}{0.45\textwidth}
  4863. Example \LangVar{} program:
  4864. %var_test_14.rkt
  4865. {\if\edition\racketEd
  4866. \begin{lstlisting}
  4867. (let ([x (read)])
  4868. (let ([y (read)])
  4869. (+ (+ x y) 42)))
  4870. \end{lstlisting}
  4871. \fi}
  4872. {\if\edition\pythonEd\pythonColor
  4873. \begin{lstlisting}
  4874. x = input_int()
  4875. y = input_int()
  4876. print((x + y) + 42)
  4877. \end{lstlisting}
  4878. \fi}
  4879. \end{minipage}
  4880. \begin{minipage}{0.45\textwidth}
  4881. Generated x86 assembly:
  4882. {\if\edition\racketEd
  4883. \begin{lstlisting}
  4884. start:
  4885. callq read_int
  4886. movq %rax, %rbx
  4887. callq read_int
  4888. movq %rax, %rcx
  4889. addq %rcx, %rbx
  4890. movq %rbx, %rax
  4891. addq $42, %rax
  4892. jmp _conclusion
  4893. .globl main
  4894. main:
  4895. pushq %rbp
  4896. movq %rsp, %rbp
  4897. pushq %rbx
  4898. subq $8, %rsp
  4899. jmp start
  4900. conclusion:
  4901. addq $8, %rsp
  4902. popq %rbx
  4903. popq %rbp
  4904. retq
  4905. \end{lstlisting}
  4906. \fi}
  4907. {\if\edition\pythonEd\pythonColor
  4908. \begin{lstlisting}
  4909. .globl main
  4910. main:
  4911. pushq %rbp
  4912. movq %rsp, %rbp
  4913. pushq %rbx
  4914. subq $8, %rsp
  4915. callq read_int
  4916. movq %rax, %rbx
  4917. callq read_int
  4918. movq %rax, %rcx
  4919. movq %rbx, %rdx
  4920. addq %rcx, %rdx
  4921. movq %rdx, %rcx
  4922. addq $42, %rcx
  4923. movq %rcx, %rdi
  4924. callq print_int
  4925. addq $8, %rsp
  4926. popq %rbx
  4927. popq %rbp
  4928. retq
  4929. \end{lstlisting}
  4930. \fi}
  4931. \end{minipage}
  4932. \end{tcolorbox}
  4933. \caption{An example with function calls.}
  4934. \label{fig:example-calling-conventions}
  4935. \end{figure}
  4936. %\clearpage
  4937. \section{Liveness Analysis}
  4938. \label{sec:liveness-analysis-Lvar}
  4939. \index{subject}{liveness analysis}
  4940. The \code{uncover\_live} \racket{pass}\python{function} performs
  4941. \emph{liveness analysis}; that is, it discovers which variables are
  4942. in use in different regions of a program.
  4943. %
  4944. A variable or register is \emph{live} at a program point if its
  4945. current value is used at some later point in the program. We refer to
  4946. variables, stack locations, and registers collectively as
  4947. \emph{locations}.
  4948. %
  4949. Consider the following code fragment in which there are two writes to
  4950. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4951. time?
  4952. \begin{center}
  4953. \begin{minipage}{0.96\textwidth}
  4954. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4955. movq $5, a
  4956. movq $30, b
  4957. movq a, c
  4958. movq $10, b
  4959. addq b, c
  4960. \end{lstlisting}
  4961. \end{minipage}
  4962. \end{center}
  4963. The answer is no, because \code{a} is live from line 1 to 3 and
  4964. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4965. line 2 is never used because it is overwritten (line 4) before the
  4966. next read (line 5).
  4967. The live locations for each instruction can be computed by traversing
  4968. the instruction sequence back to front (i.e., backward in execution
  4969. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4970. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4971. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4972. locations before instruction $I_k$. \racket{We recommend representing
  4973. these sets with the Racket \code{set} data structure described in
  4974. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4975. with the Python
  4976. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4977. data structure.}
  4978. {\if\edition\racketEd
  4979. \begin{figure}[tp]
  4980. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4981. \small
  4982. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4983. A \emph{set} is an unordered collection of elements without duplicates.
  4984. Here are some of the operations defined on sets.
  4985. \index{subject}{set}
  4986. \begin{description}
  4987. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4988. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4989. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4990. difference of the two sets.
  4991. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4992. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4993. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4994. \end{description}
  4995. \end{tcolorbox}
  4996. %\end{wrapfigure}
  4997. \caption{The \code{set} data structure.}
  4998. \label{fig:set}
  4999. \end{figure}
  5000. \fi}
  5001. The locations that are live after an instruction are its
  5002. \emph{live-after}\index{subject}{live-after} set, and the locations
  5003. that are live before an instruction are its
  5004. \emph{live-before}\index{subject}{live-before} set. The live-after
  5005. set of an instruction is always the same as the live-before set of the
  5006. next instruction.
  5007. \begin{equation} \label{eq:live-after-before-next}
  5008. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5009. \end{equation}
  5010. To start things off, there are no live locations after the last
  5011. instruction, so
  5012. \begin{equation}\label{eq:live-last-empty}
  5013. L_{\mathsf{after}}(n) = \emptyset
  5014. \end{equation}
  5015. We then apply the following rule repeatedly, traversing the
  5016. instruction sequence back to front.
  5017. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5018. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5019. \end{equation}
  5020. where $W(k)$ are the locations written to by instruction $I_k$, and
  5021. $R(k)$ are the locations read by instruction $I_k$.
  5022. {\if\edition\racketEd
  5023. %
  5024. There is a special case for \code{jmp} instructions. The locations
  5025. that are live before a \code{jmp} should be the locations in
  5026. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5027. maintaining an alist named \code{label->live} that maps each label to
  5028. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5029. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5030. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5031. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5032. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5033. %
  5034. \fi}
  5035. Let us walk through the previous example, applying these formulas
  5036. starting with the instruction on line 5 of the code fragment. We
  5037. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5038. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5039. $\emptyset$ because it is the last instruction
  5040. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5041. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5042. variables \code{b} and \code{c}
  5043. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5044. \[
  5045. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5046. \]
  5047. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5048. the live-before set from line 5 to be the live-after set for this
  5049. instruction (formula~\eqref{eq:live-after-before-next}).
  5050. \[
  5051. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5052. \]
  5053. This move instruction writes to \code{b} and does not read from any
  5054. variables, so we have the following live-before set
  5055. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5056. \[
  5057. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5058. \]
  5059. The live-before for instruction \code{movq a, c}
  5060. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5061. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5062. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5063. variable that is not live and does not read from a variable.
  5064. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5065. because it writes to variable \code{a}.
  5066. \begin{figure}[tbp]
  5067. \centering
  5068. \begin{tcolorbox}[colback=white]
  5069. \hspace{10pt}
  5070. \begin{minipage}{0.4\textwidth}
  5071. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5072. movq $5, a
  5073. movq $30, b
  5074. movq a, c
  5075. movq $10, b
  5076. addq b, c
  5077. \end{lstlisting}
  5078. \end{minipage}
  5079. \vrule\hspace{10pt}
  5080. \begin{minipage}{0.45\textwidth}
  5081. \begin{align*}
  5082. L_{\mathsf{before}}(1)= \emptyset,
  5083. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5084. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5085. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5086. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5087. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5088. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5089. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5090. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5091. L_{\mathsf{after}}(5)= \emptyset
  5092. \end{align*}
  5093. \end{minipage}
  5094. \end{tcolorbox}
  5095. \caption{Example output of liveness analysis on a short example.}
  5096. \label{fig:liveness-example-0}
  5097. \end{figure}
  5098. \begin{exercise}\normalfont\normalsize
  5099. Perform liveness analysis by hand on the running example in
  5100. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5101. sets for each instruction. Compare your answers to the solution
  5102. shown in figure~\ref{fig:live-eg}.
  5103. \end{exercise}
  5104. \begin{figure}[tp]
  5105. \hspace{20pt}
  5106. \begin{minipage}{0.55\textwidth}
  5107. \begin{tcolorbox}[colback=white]
  5108. {\if\edition\racketEd
  5109. \begin{lstlisting}
  5110. |$\{\ttm{rsp}\}$|
  5111. movq $1, v
  5112. |$\{\ttm{v},\ttm{rsp}\}$|
  5113. movq $42, w
  5114. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5115. movq v, x
  5116. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5117. addq $7, x
  5118. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5119. movq x, y
  5120. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5121. movq x, z
  5122. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5123. addq w, z
  5124. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5125. movq y, t
  5126. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5127. negq t
  5128. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5129. movq z, %rax
  5130. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5131. addq t, %rax
  5132. |$\{\ttm{rax},\ttm{rsp}\}$|
  5133. jmp conclusion
  5134. \end{lstlisting}
  5135. \fi}
  5136. {\if\edition\pythonEd\pythonColor
  5137. \begin{lstlisting}
  5138. movq $1, v
  5139. |$\{\ttm{v}\}$|
  5140. movq $42, w
  5141. |$\{\ttm{w}, \ttm{v}\}$|
  5142. movq v, x
  5143. |$\{\ttm{w}, \ttm{x}\}$|
  5144. addq $7, x
  5145. |$\{\ttm{w}, \ttm{x}\}$|
  5146. movq x, y
  5147. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5148. movq x, z
  5149. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5150. addq w, z
  5151. |$\{\ttm{y}, \ttm{z}\}$|
  5152. movq y, tmp_0
  5153. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5154. negq tmp_0
  5155. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5156. movq z, tmp_1
  5157. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5158. addq tmp_0, tmp_1
  5159. |$\{\ttm{tmp\_1}\}$|
  5160. movq tmp_1, %rdi
  5161. |$\{\ttm{rdi}\}$|
  5162. callq print_int
  5163. |$\{\}$|
  5164. \end{lstlisting}
  5165. \fi}
  5166. \end{tcolorbox}
  5167. \end{minipage}
  5168. \caption{The running example annotated with live-after sets.}
  5169. \label{fig:live-eg}
  5170. \end{figure}
  5171. \begin{exercise}\normalfont\normalsize
  5172. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5173. %
  5174. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5175. field of the \code{Block} structure.}
  5176. %
  5177. \python{Return a dictionary that maps each instruction to its
  5178. live-after set.}
  5179. %
  5180. \racket{We recommend creating an auxiliary function that takes a list
  5181. of instructions and an initial live-after set (typically empty) and
  5182. returns the list of live-after sets.}
  5183. %
  5184. We recommend creating auxiliary functions to (1) compute the set
  5185. of locations that appear in an \Arg{}, (2) compute the locations read
  5186. by an instruction (the $R$ function), and (3) the locations written by
  5187. an instruction (the $W$ function). The \code{callq} instruction should
  5188. include all the caller-saved registers in its write set $W$ because
  5189. the calling convention says that those registers may be written to
  5190. during the function call. Likewise, the \code{callq} instruction
  5191. should include the appropriate argument-passing registers in its
  5192. read set $R$, depending on the arity of the function being
  5193. called. (This is why the abstract syntax for \code{callq} includes the
  5194. arity.)
  5195. \end{exercise}
  5196. %\clearpage
  5197. \section{Build the Interference Graph}
  5198. \label{sec:build-interference}
  5199. {\if\edition\racketEd
  5200. \begin{figure}[tp]
  5201. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5202. \small
  5203. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5204. A \emph{graph} is a collection of vertices and edges where each
  5205. edge connects two vertices. A graph is \emph{directed} if each
  5206. edge points from a source to a target. Otherwise the graph is
  5207. \emph{undirected}.
  5208. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5209. \begin{description}
  5210. %% We currently don't use directed graphs. We instead use
  5211. %% directed multi-graphs. -Jeremy
  5212. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5213. directed graph from a list of edges. Each edge is a list
  5214. containing the source and target vertex.
  5215. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5216. undirected graph from a list of edges. Each edge is represented by
  5217. a list containing two vertices.
  5218. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5219. inserts a vertex into the graph.
  5220. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5221. inserts an edge between the two vertices.
  5222. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5223. returns a sequence of vertices adjacent to the vertex.
  5224. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5225. returns a sequence of all vertices in the graph.
  5226. \end{description}
  5227. \end{tcolorbox}
  5228. %\end{wrapfigure}
  5229. \caption{The Racket \code{graph} package.}
  5230. \label{fig:graph}
  5231. \end{figure}
  5232. \fi}
  5233. On the basis of the liveness analysis, we know where each location is
  5234. live. However, during register allocation, we need to answer
  5235. questions of the specific form: are locations $u$ and $v$ live at the
  5236. same time? (If so, they cannot be assigned to the same register.) To
  5237. make this question more efficient to answer, we create an explicit
  5238. data structure, an \emph{interference
  5239. graph}\index{subject}{interference graph}. An interference graph is
  5240. an undirected graph that has a node for every variable and register
  5241. and has an edge between two nodes if they are
  5242. live at the same time, that is, if they interfere with each other.
  5243. %
  5244. \racket{We recommend using the Racket \code{graph} package
  5245. (figure~\ref{fig:graph}) to represent the interference graph.}
  5246. %
  5247. \python{We provide implementations of directed and undirected graph
  5248. data structures in the file \code{graph.py} of the support code.}
  5249. A straightforward way to compute the interference graph is to look at
  5250. the set of live locations between each instruction and add an edge to
  5251. the graph for every pair of variables in the same set. This approach
  5252. is less than ideal for two reasons. First, it can be expensive because
  5253. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5254. locations. Second, in the special case in which two locations hold the
  5255. same value (because one was assigned to the other), they can be live
  5256. at the same time without interfering with each other.
  5257. A better way to compute the interference graph is to focus on
  5258. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5259. must not overwrite something in a live location. So for each
  5260. instruction, we create an edge between the locations being written to
  5261. and the live locations. (However, a location never interferes with
  5262. itself.) For the \key{callq} instruction, we consider all the
  5263. caller-saved registers to have been written to, so an edge is added
  5264. between every live variable and every caller-saved register. Also, for
  5265. \key{movq} there is the special case of two variables holding the same
  5266. value. If a live variable $v$ is the same as the source of the
  5267. \key{movq}, then there is no need to add an edge between $v$ and the
  5268. destination, because they both hold the same value.
  5269. %
  5270. Hence we have the following two rules:
  5271. \begin{enumerate}
  5272. \item If instruction $I_k$ is a move instruction of the form
  5273. \key{movq} $s$\key{,} $d$, then for every $v \in
  5274. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5275. $(d,v)$.
  5276. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5277. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5278. $(d,v)$.
  5279. \end{enumerate}
  5280. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5281. these rules to each instruction. We highlight a few of the
  5282. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5283. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5284. so \code{v} interferes with \code{rsp}.}
  5285. %
  5286. \python{The first instruction is \lstinline{movq $1, v}, and the
  5287. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  5288. no interference because $\ttm{v}$ is the destination of the move.}
  5289. %
  5290. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5291. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  5292. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5293. %
  5294. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5295. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  5296. $\ttm{x}$ interferes with \ttm{w}.}
  5297. %
  5298. \racket{The next instruction is \lstinline{movq x, y}, and the
  5299. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5300. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5301. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5302. \ttm{x} and \ttm{y} hold the same value.}
  5303. %
  5304. \python{The next instruction is \lstinline{movq x, y}, and the
  5305. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5306. applies, so \ttm{y} interferes with \ttm{w} but not
  5307. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5308. \ttm{x} and \ttm{y} hold the same value.}
  5309. %
  5310. Figure~\ref{fig:interference-results} lists the interference results
  5311. for all the instructions, and the resulting interference graph is
  5312. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5313. the interference graph in figure~\ref{fig:interfere} because there
  5314. were no interference edges involving registers and we did not wish to
  5315. clutter the graph, but in general one needs to include all the
  5316. registers in the interference graph.
  5317. \begin{figure}[tbp]
  5318. \begin{tcolorbox}[colback=white]
  5319. \begin{quote}
  5320. {\if\edition\racketEd
  5321. \begin{tabular}{ll}
  5322. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5323. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5324. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5325. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5326. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5327. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5328. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5329. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5330. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5331. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5332. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5333. \lstinline!jmp conclusion!& no interference.
  5334. \end{tabular}
  5335. \fi}
  5336. {\if\edition\pythonEd\pythonColor
  5337. \begin{tabular}{ll}
  5338. \lstinline!movq $1, v!& no interference\\
  5339. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5340. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5341. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5342. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5343. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5344. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5345. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5346. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5347. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5348. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5349. \lstinline!movq tmp_1, %rdi! & no interference \\
  5350. \lstinline!callq print_int!& no interference.
  5351. \end{tabular}
  5352. \fi}
  5353. \end{quote}
  5354. \end{tcolorbox}
  5355. \caption{Interference results for the running example.}
  5356. \label{fig:interference-results}
  5357. \end{figure}
  5358. \begin{figure}[tbp]
  5359. \begin{tcolorbox}[colback=white]
  5360. \large
  5361. {\if\edition\racketEd
  5362. \[
  5363. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5364. \node (rax) at (0,0) {$\ttm{rax}$};
  5365. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5366. \node (t1) at (0,2) {$\ttm{t}$};
  5367. \node (z) at (3,2) {$\ttm{z}$};
  5368. \node (x) at (6,2) {$\ttm{x}$};
  5369. \node (y) at (3,0) {$\ttm{y}$};
  5370. \node (w) at (6,0) {$\ttm{w}$};
  5371. \node (v) at (9,0) {$\ttm{v}$};
  5372. \draw (t1) to (rax);
  5373. \draw (t1) to (z);
  5374. \draw (z) to (y);
  5375. \draw (z) to (w);
  5376. \draw (x) to (w);
  5377. \draw (y) to (w);
  5378. \draw (v) to (w);
  5379. \draw (v) to (rsp);
  5380. \draw (w) to (rsp);
  5381. \draw (x) to (rsp);
  5382. \draw (y) to (rsp);
  5383. \path[-.,bend left=15] (z) edge node {} (rsp);
  5384. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5385. \draw (rax) to (rsp);
  5386. \end{tikzpicture}
  5387. \]
  5388. \fi}
  5389. {\if\edition\pythonEd\pythonColor
  5390. \[
  5391. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5392. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5393. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5394. \node (z) at (3,2) {$\ttm{z}$};
  5395. \node (x) at (6,2) {$\ttm{x}$};
  5396. \node (y) at (3,0) {$\ttm{y}$};
  5397. \node (w) at (6,0) {$\ttm{w}$};
  5398. \node (v) at (9,0) {$\ttm{v}$};
  5399. \draw (t0) to (t1);
  5400. \draw (t0) to (z);
  5401. \draw (z) to (y);
  5402. \draw (z) to (w);
  5403. \draw (x) to (w);
  5404. \draw (y) to (w);
  5405. \draw (v) to (w);
  5406. \end{tikzpicture}
  5407. \]
  5408. \fi}
  5409. \end{tcolorbox}
  5410. \caption{The interference graph of the example program.}
  5411. \label{fig:interfere}
  5412. \end{figure}
  5413. \begin{exercise}\normalfont\normalsize
  5414. \racket{Implement the compiler pass named \code{build\_interference} according
  5415. to the algorithm suggested here. We recommend using the Racket
  5416. \code{graph} package to create and inspect the interference graph.
  5417. The output graph of this pass should be stored in the $\itm{info}$ field of
  5418. the program, under the key \code{conflicts}.}
  5419. %
  5420. \python{Implement a function named \code{build\_interference}
  5421. according to the algorithm suggested above that
  5422. returns the interference graph.}
  5423. \end{exercise}
  5424. \section{Graph Coloring via Sudoku}
  5425. \label{sec:graph-coloring}
  5426. \index{subject}{graph coloring}
  5427. \index{subject}{sudoku}
  5428. \index{subject}{color}
  5429. We come to the main event discussed in this chapter, mapping variables
  5430. to registers and stack locations. Variables that interfere with each
  5431. other must be mapped to different locations. In terms of the
  5432. interference graph, this means that adjacent vertices must be mapped
  5433. to different locations. If we think of locations as colors, the
  5434. register allocation problem becomes the graph coloring
  5435. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5436. The reader may be more familiar with the graph coloring problem than he
  5437. or she realizes; the popular game of sudoku is an instance of the
  5438. graph coloring problem. The following describes how to build a graph
  5439. out of an initial sudoku board.
  5440. \begin{itemize}
  5441. \item There is one vertex in the graph for each sudoku square.
  5442. \item There is an edge between two vertices if the corresponding squares
  5443. are in the same row, in the same column, or in the same $3\times 3$ region.
  5444. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5445. \item On the basis of the initial assignment of numbers to squares on the
  5446. sudoku board, assign the corresponding colors to the corresponding
  5447. vertices in the graph.
  5448. \end{itemize}
  5449. If you can color the remaining vertices in the graph with the nine
  5450. colors, then you have also solved the corresponding game of sudoku.
  5451. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5452. the corresponding graph with colored vertices. Here we use a
  5453. monochrome representation of colors, mapping the sudoku number 1 to
  5454. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5455. of the vertices (the colored ones) because showing edges for all the
  5456. vertices would make the graph unreadable.
  5457. \begin{figure}[tbp]
  5458. \begin{tcolorbox}[colback=white]
  5459. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5460. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5461. \end{tcolorbox}
  5462. \caption{A sudoku game board and the corresponding colored graph.}
  5463. \label{fig:sudoku-graph}
  5464. \end{figure}
  5465. Some techniques for playing sudoku correspond to heuristics used in
  5466. graph coloring algorithms. For example, one of the basic techniques
  5467. for sudoku is called Pencil Marks. The idea is to use a process of
  5468. elimination to determine what numbers are no longer available for a
  5469. square and to write those numbers in the square (writing very
  5470. small). For example, if the number $1$ is assigned to a square, then
  5471. write the pencil mark $1$ in all the squares in the same row, column,
  5472. and region to indicate that $1$ is no longer an option for those other
  5473. squares.
  5474. %
  5475. The Pencil Marks technique corresponds to the notion of
  5476. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5477. saturation of a vertex, in sudoku terms, is the set of numbers that
  5478. are no longer available. In graph terminology, we have the following
  5479. definition:
  5480. \begin{equation*}
  5481. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5482. \text{ and } \mathrm{color}(v) = c \}
  5483. \end{equation*}
  5484. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5485. edge with $u$.
  5486. The Pencil Marks technique leads to a simple strategy for filling in
  5487. numbers: if there is a square with only one possible number left, then
  5488. choose that number! But what if there are no squares with only one
  5489. possibility left? One brute-force approach is to try them all: choose
  5490. the first one, and if that ultimately leads to a solution, great. If
  5491. not, backtrack and choose the next possibility. One good thing about
  5492. Pencil Marks is that it reduces the degree of branching in the search
  5493. tree. Nevertheless, backtracking can be terribly time consuming. One
  5494. way to reduce the amount of backtracking is to use the
  5495. most-constrained-first heuristic (aka minimum remaining
  5496. values)~\citep{Russell2003}. That is, in choosing a square, always
  5497. choose one with the fewest possibilities left (the vertex with the
  5498. highest saturation). The idea is that choosing highly constrained
  5499. squares earlier rather than later is better, because later on there may
  5500. not be any possibilities left in the highly saturated squares.
  5501. However, register allocation is easier than sudoku, because the
  5502. register allocator can fall back to assigning variables to stack
  5503. locations when the registers run out. Thus, it makes sense to replace
  5504. backtracking with greedy search: make the best choice at the time and
  5505. keep going. We still wish to minimize the number of colors needed, so
  5506. we use the most-constrained-first heuristic in the greedy search.
  5507. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5508. algorithm for register allocation based on saturation and the
  5509. most-constrained-first heuristic. It is roughly equivalent to the
  5510. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5511. sudoku, the algorithm represents colors with integers. The integers
  5512. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5513. register allocation. In particular, we recommend the following
  5514. correspondence, with $k=11$.
  5515. \begin{lstlisting}
  5516. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5517. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5518. \end{lstlisting}
  5519. The integers $k$ and larger correspond to stack locations. The
  5520. registers that are not used for register allocation, such as
  5521. \code{rax}, are assigned to negative integers. In particular, we
  5522. recommend the following correspondence.
  5523. \begin{lstlisting}
  5524. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5525. \end{lstlisting}
  5526. %% One might wonder why we include registers at all in the liveness
  5527. %% analysis and interference graph. For example, we never allocate a
  5528. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5529. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5530. %% to use register for passing arguments to functions, it will be
  5531. %% necessary for those registers to appear in the interference graph
  5532. %% because those registers will also be assigned to variables, and we
  5533. %% don't want those two uses to encroach on each other. Regarding
  5534. %% registers such as \code{rax} and \code{rsp} that are not used for
  5535. %% variables, we could omit them from the interference graph but that
  5536. %% would require adding special cases to our algorithm, which would
  5537. %% complicate the logic for little gain.
  5538. \begin{figure}[btp]
  5539. \begin{tcolorbox}[colback=white]
  5540. \centering
  5541. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5542. Algorithm: DSATUR
  5543. Input: A graph |$G$|
  5544. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5545. |$W \gets \mathrm{vertices}(G)$|
  5546. while |$W \neq \emptyset$| do
  5547. pick a vertex |$u$| from |$W$| with the highest saturation,
  5548. breaking ties randomly
  5549. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5550. |$\mathrm{color}[u] \gets c$|
  5551. |$W \gets W - \{u\}$|
  5552. \end{lstlisting}
  5553. \end{tcolorbox}
  5554. \caption{The saturation-based greedy graph coloring algorithm.}
  5555. \label{fig:satur-algo}
  5556. \end{figure}
  5557. {\if\edition\racketEd
  5558. With the DSATUR algorithm in hand, let us return to the running
  5559. example and consider how to color the interference graph shown in
  5560. figure~\ref{fig:interfere}.
  5561. %
  5562. We start by assigning each register node to its own color. For
  5563. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5564. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5565. (To reduce clutter in the interference graph, we elide nodes
  5566. that do not have interference edges, such as \code{rcx}.)
  5567. The variables are not yet colored, so they are annotated with a dash. We
  5568. then update the saturation for vertices that are adjacent to a
  5569. register, obtaining the following annotated graph. For example, the
  5570. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5571. \code{rax} and \code{rsp}.
  5572. \[
  5573. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5574. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5575. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5576. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5577. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5578. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5579. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5580. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5581. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5582. \draw (t1) to (rax);
  5583. \draw (t1) to (z);
  5584. \draw (z) to (y);
  5585. \draw (z) to (w);
  5586. \draw (x) to (w);
  5587. \draw (y) to (w);
  5588. \draw (v) to (w);
  5589. \draw (v) to (rsp);
  5590. \draw (w) to (rsp);
  5591. \draw (x) to (rsp);
  5592. \draw (y) to (rsp);
  5593. \path[-.,bend left=15] (z) edge node {} (rsp);
  5594. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5595. \draw (rax) to (rsp);
  5596. \end{tikzpicture}
  5597. \]
  5598. The algorithm says to select a maximally saturated vertex. So, we pick
  5599. $\ttm{t}$ and color it with the first available integer, which is
  5600. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5601. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5602. \[
  5603. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5604. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5605. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5606. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5607. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5608. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5609. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5610. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5611. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5612. \draw (t1) to (rax);
  5613. \draw (t1) to (z);
  5614. \draw (z) to (y);
  5615. \draw (z) to (w);
  5616. \draw (x) to (w);
  5617. \draw (y) to (w);
  5618. \draw (v) to (w);
  5619. \draw (v) to (rsp);
  5620. \draw (w) to (rsp);
  5621. \draw (x) to (rsp);
  5622. \draw (y) to (rsp);
  5623. \path[-.,bend left=15] (z) edge node {} (rsp);
  5624. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5625. \draw (rax) to (rsp);
  5626. \end{tikzpicture}
  5627. \]
  5628. We repeat the process, selecting a maximally saturated vertex,
  5629. choosing \code{z}, and coloring it with the first available number, which
  5630. is $1$. We add $1$ to the saturation for the neighboring vertices
  5631. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5632. \[
  5633. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5634. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5635. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5636. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5637. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5638. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5639. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5640. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5641. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5642. \draw (t1) to (rax);
  5643. \draw (t1) to (z);
  5644. \draw (z) to (y);
  5645. \draw (z) to (w);
  5646. \draw (x) to (w);
  5647. \draw (y) to (w);
  5648. \draw (v) to (w);
  5649. \draw (v) to (rsp);
  5650. \draw (w) to (rsp);
  5651. \draw (x) to (rsp);
  5652. \draw (y) to (rsp);
  5653. \path[-.,bend left=15] (z) edge node {} (rsp);
  5654. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5655. \draw (rax) to (rsp);
  5656. \end{tikzpicture}
  5657. \]
  5658. The most saturated vertices are now \code{w} and \code{y}. We color
  5659. \code{w} with the first available color, which is $0$.
  5660. \[
  5661. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5662. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5663. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5664. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5665. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5666. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5667. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5668. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5669. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5670. \draw (t1) to (rax);
  5671. \draw (t1) to (z);
  5672. \draw (z) to (y);
  5673. \draw (z) to (w);
  5674. \draw (x) to (w);
  5675. \draw (y) to (w);
  5676. \draw (v) to (w);
  5677. \draw (v) to (rsp);
  5678. \draw (w) to (rsp);
  5679. \draw (x) to (rsp);
  5680. \draw (y) to (rsp);
  5681. \path[-.,bend left=15] (z) edge node {} (rsp);
  5682. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5683. \draw (rax) to (rsp);
  5684. \end{tikzpicture}
  5685. \]
  5686. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5687. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5688. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5689. and \code{z}, whose colors are $0$ and $1$ respectively.
  5690. \[
  5691. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5692. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5693. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5694. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5695. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5696. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5697. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5698. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5699. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5700. \draw (t1) to (rax);
  5701. \draw (t1) to (z);
  5702. \draw (z) to (y);
  5703. \draw (z) to (w);
  5704. \draw (x) to (w);
  5705. \draw (y) to (w);
  5706. \draw (v) to (w);
  5707. \draw (v) to (rsp);
  5708. \draw (w) to (rsp);
  5709. \draw (x) to (rsp);
  5710. \draw (y) to (rsp);
  5711. \path[-.,bend left=15] (z) edge node {} (rsp);
  5712. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5713. \draw (rax) to (rsp);
  5714. \end{tikzpicture}
  5715. \]
  5716. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5717. \[
  5718. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5719. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5720. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5721. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5722. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5723. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5724. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5725. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5726. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5727. \draw (t1) to (rax);
  5728. \draw (t1) to (z);
  5729. \draw (z) to (y);
  5730. \draw (z) to (w);
  5731. \draw (x) to (w);
  5732. \draw (y) to (w);
  5733. \draw (v) to (w);
  5734. \draw (v) to (rsp);
  5735. \draw (w) to (rsp);
  5736. \draw (x) to (rsp);
  5737. \draw (y) to (rsp);
  5738. \path[-.,bend left=15] (z) edge node {} (rsp);
  5739. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5740. \draw (rax) to (rsp);
  5741. \end{tikzpicture}
  5742. \]
  5743. In the last step of the algorithm, we color \code{x} with $1$.
  5744. \[
  5745. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5746. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5747. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5748. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5749. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5750. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5751. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5752. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5753. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5754. \draw (t1) to (rax);
  5755. \draw (t1) to (z);
  5756. \draw (z) to (y);
  5757. \draw (z) to (w);
  5758. \draw (x) to (w);
  5759. \draw (y) to (w);
  5760. \draw (v) to (w);
  5761. \draw (v) to (rsp);
  5762. \draw (w) to (rsp);
  5763. \draw (x) to (rsp);
  5764. \draw (y) to (rsp);
  5765. \path[-.,bend left=15] (z) edge node {} (rsp);
  5766. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5767. \draw (rax) to (rsp);
  5768. \end{tikzpicture}
  5769. \]
  5770. So, we obtain the following coloring:
  5771. \[
  5772. \{
  5773. \ttm{rax} \mapsto -1,
  5774. \ttm{rsp} \mapsto -2,
  5775. \ttm{t} \mapsto 0,
  5776. \ttm{z} \mapsto 1,
  5777. \ttm{x} \mapsto 1,
  5778. \ttm{y} \mapsto 2,
  5779. \ttm{w} \mapsto 0,
  5780. \ttm{v} \mapsto 1
  5781. \}
  5782. \]
  5783. \fi}
  5784. %
  5785. {\if\edition\pythonEd\pythonColor
  5786. %
  5787. With the DSATUR algorithm in hand, let us return to the running
  5788. example and consider how to color the interference graph in
  5789. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5790. to indicate that it has not yet been assigned a color. Each register
  5791. node (not shown) should be assigned the number that the register
  5792. corresponds to, for example, color \code{rcx} with the number \code{0}
  5793. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5794. each node; all of them start as the empty set. We do not show the
  5795. register nodes in the graph below because there were no interference
  5796. edges involving registers in this program, but in general there can
  5797. be.
  5798. %
  5799. \[
  5800. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5801. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5802. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5803. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5804. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5805. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5806. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5807. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5808. \draw (t0) to (t1);
  5809. \draw (t0) to (z);
  5810. \draw (z) to (y);
  5811. \draw (z) to (w);
  5812. \draw (x) to (w);
  5813. \draw (y) to (w);
  5814. \draw (v) to (w);
  5815. \end{tikzpicture}
  5816. \]
  5817. The algorithm says to select a maximally saturated vertex, but they
  5818. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5819. then color it with the first available integer, which is $0$. We mark
  5820. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5821. they interfere with $\ttm{tmp\_0}$.
  5822. \[
  5823. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5824. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5825. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5826. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5827. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5828. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5829. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5830. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5831. \draw (t0) to (t1);
  5832. \draw (t0) to (z);
  5833. \draw (z) to (y);
  5834. \draw (z) to (w);
  5835. \draw (x) to (w);
  5836. \draw (y) to (w);
  5837. \draw (v) to (w);
  5838. \end{tikzpicture}
  5839. \]
  5840. We repeat the process. The most saturated vertices are \code{z} and
  5841. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5842. available number, which is $1$. We add $1$ to the saturation for the
  5843. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5844. \[
  5845. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5846. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5847. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5848. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5849. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5850. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5851. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5852. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5853. \draw (t0) to (t1);
  5854. \draw (t0) to (z);
  5855. \draw (z) to (y);
  5856. \draw (z) to (w);
  5857. \draw (x) to (w);
  5858. \draw (y) to (w);
  5859. \draw (v) to (w);
  5860. \end{tikzpicture}
  5861. \]
  5862. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5863. \code{y}. We color \code{w} with the first available color, which
  5864. is $0$.
  5865. \[
  5866. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5867. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5868. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5869. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5870. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5871. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5872. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5873. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5874. \draw (t0) to (t1);
  5875. \draw (t0) to (z);
  5876. \draw (z) to (y);
  5877. \draw (z) to (w);
  5878. \draw (x) to (w);
  5879. \draw (y) to (w);
  5880. \draw (v) to (w);
  5881. \end{tikzpicture}
  5882. \]
  5883. Now \code{y} is the most saturated, so we color it with $2$.
  5884. \[
  5885. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5886. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5887. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5888. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5889. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5890. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5891. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5892. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5893. \draw (t0) to (t1);
  5894. \draw (t0) to (z);
  5895. \draw (z) to (y);
  5896. \draw (z) to (w);
  5897. \draw (x) to (w);
  5898. \draw (y) to (w);
  5899. \draw (v) to (w);
  5900. \end{tikzpicture}
  5901. \]
  5902. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5903. We choose to color \code{v} with $1$.
  5904. \[
  5905. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5906. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5907. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5908. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5909. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5910. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5911. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5912. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5913. \draw (t0) to (t1);
  5914. \draw (t0) to (z);
  5915. \draw (z) to (y);
  5916. \draw (z) to (w);
  5917. \draw (x) to (w);
  5918. \draw (y) to (w);
  5919. \draw (v) to (w);
  5920. \end{tikzpicture}
  5921. \]
  5922. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5923. \[
  5924. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5925. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5926. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5927. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5928. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5929. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5930. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5931. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5932. \draw (t0) to (t1);
  5933. \draw (t0) to (z);
  5934. \draw (z) to (y);
  5935. \draw (z) to (w);
  5936. \draw (x) to (w);
  5937. \draw (y) to (w);
  5938. \draw (v) to (w);
  5939. \end{tikzpicture}
  5940. \]
  5941. So, we obtain the following coloring:
  5942. \[
  5943. \{ \ttm{tmp\_0} \mapsto 0,
  5944. \ttm{tmp\_1} \mapsto 1,
  5945. \ttm{z} \mapsto 1,
  5946. \ttm{x} \mapsto 1,
  5947. \ttm{y} \mapsto 2,
  5948. \ttm{w} \mapsto 0,
  5949. \ttm{v} \mapsto 1 \}
  5950. \]
  5951. \fi}
  5952. We recommend creating an auxiliary function named \code{color\_graph}
  5953. that takes an interference graph and a list of all the variables in
  5954. the program. This function should return a mapping of variables to
  5955. their colors (represented as natural numbers). By creating this helper
  5956. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5957. when we add support for functions.
  5958. To prioritize the processing of highly saturated nodes inside the
  5959. \code{color\_graph} function, we recommend using the priority queue
  5960. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5961. addition, you will need to maintain a mapping from variables to their
  5962. handles in the priority queue so that you can notify the priority
  5963. queue when their saturation changes.}
  5964. {\if\edition\racketEd
  5965. \begin{figure}[tp]
  5966. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5967. \small
  5968. \begin{tcolorbox}[title=Priority Queue]
  5969. A \emph{priority queue}\index{subject}{priority queue}
  5970. is a collection of items in which the
  5971. removal of items is governed by priority. In a \emph{min} queue,
  5972. lower priority items are removed first. An implementation is in
  5973. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  5974. \begin{description}
  5975. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5976. priority queue that uses the $\itm{cmp}$ predicate to determine
  5977. whether its first argument has lower or equal priority to its
  5978. second argument.
  5979. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5980. items in the queue.
  5981. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5982. the item into the queue and returns a handle for the item in the
  5983. queue.
  5984. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5985. the lowest priority.
  5986. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5987. notifies the queue that the priority has decreased for the item
  5988. associated with the given handle.
  5989. \end{description}
  5990. \end{tcolorbox}
  5991. %\end{wrapfigure}
  5992. \caption{The priority queue data structure.}
  5993. \label{fig:priority-queue}
  5994. \end{figure}
  5995. \fi}
  5996. With the coloring complete, we finalize the assignment of variables to
  5997. registers and stack locations. We map the first $k$ colors to the $k$
  5998. registers and the rest of the colors to stack locations. Suppose for
  5999. the moment that we have just one register to use for register
  6000. allocation, \key{rcx}. Then we have the following map from colors to
  6001. locations.
  6002. \[
  6003. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6004. \]
  6005. Composing this mapping with the coloring, we arrive at the following
  6006. assignment of variables to locations.
  6007. {\if\edition\racketEd
  6008. \begin{gather*}
  6009. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6010. \ttm{w} \mapsto \key{\%rcx}, \,
  6011. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6012. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6013. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6014. \ttm{t} \mapsto \key{\%rcx} \}
  6015. \end{gather*}
  6016. \fi}
  6017. {\if\edition\pythonEd\pythonColor
  6018. \begin{gather*}
  6019. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6020. \ttm{w} \mapsto \key{\%rcx}, \,
  6021. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6022. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6023. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6024. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6025. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6026. \end{gather*}
  6027. \fi}
  6028. Adapt the code from the \code{assign\_homes} pass
  6029. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6030. assigned location. Applying this assignment to our running
  6031. example shown next, on the left, yields the program on the right.
  6032. % why frame size of 32? -JGS
  6033. \begin{center}
  6034. {\if\edition\racketEd
  6035. \begin{minipage}{0.35\textwidth}
  6036. \begin{lstlisting}
  6037. movq $1, v
  6038. movq $42, w
  6039. movq v, x
  6040. addq $7, x
  6041. movq x, y
  6042. movq x, z
  6043. addq w, z
  6044. movq y, t
  6045. negq t
  6046. movq z, %rax
  6047. addq t, %rax
  6048. jmp conclusion
  6049. \end{lstlisting}
  6050. \end{minipage}
  6051. $\Rightarrow\qquad$
  6052. \begin{minipage}{0.45\textwidth}
  6053. \begin{lstlisting}
  6054. movq $1, -8(%rbp)
  6055. movq $42, %rcx
  6056. movq -8(%rbp), -8(%rbp)
  6057. addq $7, -8(%rbp)
  6058. movq -8(%rbp), -16(%rbp)
  6059. movq -8(%rbp), -8(%rbp)
  6060. addq %rcx, -8(%rbp)
  6061. movq -16(%rbp), %rcx
  6062. negq %rcx
  6063. movq -8(%rbp), %rax
  6064. addq %rcx, %rax
  6065. jmp conclusion
  6066. \end{lstlisting}
  6067. \end{minipage}
  6068. \fi}
  6069. {\if\edition\pythonEd\pythonColor
  6070. \begin{minipage}{0.35\textwidth}
  6071. \begin{lstlisting}
  6072. movq $1, v
  6073. movq $42, w
  6074. movq v, x
  6075. addq $7, x
  6076. movq x, y
  6077. movq x, z
  6078. addq w, z
  6079. movq y, tmp_0
  6080. negq tmp_0
  6081. movq z, tmp_1
  6082. addq tmp_0, tmp_1
  6083. movq tmp_1, %rdi
  6084. callq print_int
  6085. \end{lstlisting}
  6086. \end{minipage}
  6087. $\Rightarrow\qquad$
  6088. \begin{minipage}{0.45\textwidth}
  6089. \begin{lstlisting}
  6090. movq $1, -8(%rbp)
  6091. movq $42, %rcx
  6092. movq -8(%rbp), -8(%rbp)
  6093. addq $7, -8(%rbp)
  6094. movq -8(%rbp), -16(%rbp)
  6095. movq -8(%rbp), -8(%rbp)
  6096. addq %rcx, -8(%rbp)
  6097. movq -16(%rbp), %rcx
  6098. negq %rcx
  6099. movq -8(%rbp), -8(%rbp)
  6100. addq %rcx, -8(%rbp)
  6101. movq -8(%rbp), %rdi
  6102. callq print_int
  6103. \end{lstlisting}
  6104. \end{minipage}
  6105. \fi}
  6106. \end{center}
  6107. \begin{exercise}\normalfont\normalsize
  6108. Implement the \code{allocate\_registers} pass.
  6109. Create five programs that exercise all aspects of the register
  6110. allocation algorithm, including spilling variables to the stack.
  6111. %
  6112. {\if\edition\racketEd
  6113. Replace \code{assign\_homes} in the list of \code{passes} in the
  6114. \code{run-tests.rkt} script with the three new passes:
  6115. \code{uncover\_live}, \code{build\_interference}, and
  6116. \code{allocate\_registers}.
  6117. Temporarily remove the call to \code{compiler-tests}.
  6118. Run the script to test the register allocator.
  6119. \fi}
  6120. %
  6121. {\if\edition\pythonEd\pythonColor
  6122. Run the \code{run-tests.py} script to to check whether the
  6123. output programs produce the same result as the input programs.
  6124. \fi}
  6125. \end{exercise}
  6126. \section{Patch Instructions}
  6127. \label{sec:patch-instructions}
  6128. The remaining step in the compilation to x86 is to ensure that the
  6129. instructions have at most one argument that is a memory access.
  6130. %
  6131. In the running example, the instruction \code{movq -8(\%rbp),
  6132. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6133. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6134. then move \code{rax} into \code{-16(\%rbp)}.
  6135. %
  6136. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6137. problematic, but they can simply be deleted. In general, we recommend
  6138. deleting all the trivial moves whose source and destination are the
  6139. same location.
  6140. %
  6141. The following is the output of \code{patch\_instructions} on the
  6142. running example.
  6143. \begin{center}
  6144. {\if\edition\racketEd
  6145. \begin{minipage}{0.35\textwidth}
  6146. \begin{lstlisting}
  6147. movq $1, -8(%rbp)
  6148. movq $42, %rcx
  6149. movq -8(%rbp), -8(%rbp)
  6150. addq $7, -8(%rbp)
  6151. movq -8(%rbp), -16(%rbp)
  6152. movq -8(%rbp), -8(%rbp)
  6153. addq %rcx, -8(%rbp)
  6154. movq -16(%rbp), %rcx
  6155. negq %rcx
  6156. movq -8(%rbp), %rax
  6157. addq %rcx, %rax
  6158. jmp conclusion
  6159. \end{lstlisting}
  6160. \end{minipage}
  6161. $\Rightarrow\qquad$
  6162. \begin{minipage}{0.45\textwidth}
  6163. \begin{lstlisting}
  6164. movq $1, -8(%rbp)
  6165. movq $42, %rcx
  6166. addq $7, -8(%rbp)
  6167. movq -8(%rbp), %rax
  6168. movq %rax, -16(%rbp)
  6169. addq %rcx, -8(%rbp)
  6170. movq -16(%rbp), %rcx
  6171. negq %rcx
  6172. movq -8(%rbp), %rax
  6173. addq %rcx, %rax
  6174. jmp conclusion
  6175. \end{lstlisting}
  6176. \end{minipage}
  6177. \fi}
  6178. {\if\edition\pythonEd\pythonColor
  6179. \begin{minipage}{0.35\textwidth}
  6180. \begin{lstlisting}
  6181. movq $1, -8(%rbp)
  6182. movq $42, %rcx
  6183. movq -8(%rbp), -8(%rbp)
  6184. addq $7, -8(%rbp)
  6185. movq -8(%rbp), -16(%rbp)
  6186. movq -8(%rbp), -8(%rbp)
  6187. addq %rcx, -8(%rbp)
  6188. movq -16(%rbp), %rcx
  6189. negq %rcx
  6190. movq -8(%rbp), -8(%rbp)
  6191. addq %rcx, -8(%rbp)
  6192. movq -8(%rbp), %rdi
  6193. callq print_int
  6194. \end{lstlisting}
  6195. \end{minipage}
  6196. $\Rightarrow\qquad$
  6197. \begin{minipage}{0.45\textwidth}
  6198. \begin{lstlisting}
  6199. movq $1, -8(%rbp)
  6200. movq $42, %rcx
  6201. addq $7, -8(%rbp)
  6202. movq -8(%rbp), %rax
  6203. movq %rax, -16(%rbp)
  6204. addq %rcx, -8(%rbp)
  6205. movq -16(%rbp), %rcx
  6206. negq %rcx
  6207. addq %rcx, -8(%rbp)
  6208. movq -8(%rbp), %rdi
  6209. callq print_int
  6210. \end{lstlisting}
  6211. \end{minipage}
  6212. \fi}
  6213. \end{center}
  6214. \begin{exercise}\normalfont\normalsize
  6215. %
  6216. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6217. %
  6218. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6219. %in the \code{run-tests.rkt} script.
  6220. %
  6221. Run the script to test the \code{patch\_instructions} pass.
  6222. \end{exercise}
  6223. \section{Prelude and Conclusion}
  6224. \label{sec:print-x86-reg-alloc}
  6225. \index{subject}{calling conventions}
  6226. \index{subject}{prelude}\index{subject}{conclusion}
  6227. Recall that this pass generates the prelude and conclusion
  6228. instructions to satisfy the x86 calling conventions
  6229. (section~\ref{sec:calling-conventions}). With the addition of the
  6230. register allocator, the callee-saved registers used by the register
  6231. allocator must be saved in the prelude and restored in the conclusion.
  6232. In the \code{allocate\_registers} pass,
  6233. %
  6234. \racket{add an entry to the \itm{info}
  6235. of \code{X86Program} named \code{used\_callee}}
  6236. %
  6237. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6238. %
  6239. that stores the set of callee-saved registers that were assigned to
  6240. variables. The \code{prelude\_and\_conclusion} pass can then access
  6241. this information to decide which callee-saved registers need to be
  6242. saved and restored.
  6243. %
  6244. When calculating the amount to adjust the \code{rsp} in the prelude,
  6245. make sure to take into account the space used for saving the
  6246. callee-saved registers. Also, remember that the frame needs to be a
  6247. multiple of 16 bytes! We recommend using the following equation for
  6248. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6249. of stack locations used by spilled variables\footnote{Sometimes two or
  6250. more spilled variables are assigned to the same stack location, so
  6251. $S$ can be less than the number of spilled variables.} and $C$ be
  6252. the number of callee-saved registers that were
  6253. allocated\index{subject}{allocate} to
  6254. variables. The $\itm{align}$ function rounds a number up to the
  6255. nearest 16 bytes.
  6256. \[
  6257. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6258. \]
  6259. The reason we subtract $8\itm{C}$ in this equation is that the
  6260. prelude uses \code{pushq} to save each of the callee-saved registers,
  6261. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6262. \racket{An overview of all the passes involved in register
  6263. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6264. {\if\edition\racketEd
  6265. \begin{figure}[tbp]
  6266. \begin{tcolorbox}[colback=white]
  6267. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6268. \node (Lvar) at (0,2) {\large \LangVar{}};
  6269. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6270. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6271. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6272. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6273. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6274. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6275. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6276. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6277. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6278. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6279. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6280. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6281. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6282. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6283. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6284. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6285. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6286. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6287. \end{tikzpicture}
  6288. \end{tcolorbox}
  6289. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6290. \label{fig:reg-alloc-passes}
  6291. \end{figure}
  6292. \fi}
  6293. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6294. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6295. use of registers and the stack, we limit the register allocator for
  6296. this example to use just two registers: \code{rcx} (color $0$) and
  6297. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6298. \code{main} function, we push \code{rbx} onto the stack because it is
  6299. a callee-saved register and it was assigned to a variable by the
  6300. register allocator. We subtract \code{8} from the \code{rsp} at the
  6301. end of the prelude to reserve space for the one spilled variable.
  6302. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6303. Moving on to the program proper, we see how the registers were
  6304. allocated.
  6305. %
  6306. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6307. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6308. %
  6309. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6310. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  6311. were assigned to \code{rbx}.}
  6312. %
  6313. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6314. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6315. callee-save register \code{rbx} onto the stack. The spilled variables
  6316. must be placed lower on the stack than the saved callee-save
  6317. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6318. \code{-16(\%rbp)}.
  6319. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6320. done in the prelude. We move the stack pointer up by \code{8} bytes
  6321. (the room for spilled variables), then pop the old values of
  6322. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6323. \code{retq} to return control to the operating system.
  6324. \begin{figure}[tbp]
  6325. \begin{minipage}{0.55\textwidth}
  6326. \begin{tcolorbox}[colback=white]
  6327. % var_test_28.rkt
  6328. % (use-minimal-set-of-registers! #t)
  6329. % 0 -> rcx
  6330. % 1 -> rbx
  6331. %
  6332. % t 0 rcx
  6333. % z 1 rbx
  6334. % w 0 rcx
  6335. % y 2 rbp -16
  6336. % v 1 rbx
  6337. % x 1 rbx
  6338. {\if\edition\racketEd
  6339. \begin{lstlisting}
  6340. start:
  6341. movq $1, %rbx
  6342. movq $42, %rcx
  6343. addq $7, %rbx
  6344. movq %rbx, -16(%rbp)
  6345. addq %rcx, %rbx
  6346. movq -16(%rbp), %rcx
  6347. negq %rcx
  6348. movq %rbx, %rax
  6349. addq %rcx, %rax
  6350. jmp conclusion
  6351. .globl main
  6352. main:
  6353. pushq %rbp
  6354. movq %rsp, %rbp
  6355. pushq %rbx
  6356. subq $8, %rsp
  6357. jmp start
  6358. conclusion:
  6359. addq $8, %rsp
  6360. popq %rbx
  6361. popq %rbp
  6362. retq
  6363. \end{lstlisting}
  6364. \fi}
  6365. {\if\edition\pythonEd\pythonColor
  6366. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6367. \begin{lstlisting}
  6368. .globl main
  6369. main:
  6370. pushq %rbp
  6371. movq %rsp, %rbp
  6372. pushq %rbx
  6373. subq $8, %rsp
  6374. movq $1, %rcx
  6375. movq $42, %rbx
  6376. addq $7, %rcx
  6377. movq %rcx, -16(%rbp)
  6378. addq %rbx, -16(%rbp)
  6379. negq %rcx
  6380. movq -16(%rbp), %rbx
  6381. addq %rcx, %rbx
  6382. movq %rbx, %rdi
  6383. callq print_int
  6384. addq $8, %rsp
  6385. popq %rbx
  6386. popq %rbp
  6387. retq
  6388. \end{lstlisting}
  6389. \fi}
  6390. \end{tcolorbox}
  6391. \end{minipage}
  6392. \caption{The x86 output from the running example
  6393. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6394. and \code{rcx}.}
  6395. \label{fig:running-example-x86}
  6396. \end{figure}
  6397. \begin{exercise}\normalfont\normalsize
  6398. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6399. %
  6400. \racket{
  6401. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6402. list of passes and the call to \code{compiler-tests}.}
  6403. %
  6404. Run the script to test the complete compiler for \LangVar{} that
  6405. performs register allocation.
  6406. \end{exercise}
  6407. \section{Challenge: Move Biasing}
  6408. \label{sec:move-biasing}
  6409. \index{subject}{move biasing}
  6410. This section describes an enhancement to the register allocator,
  6411. called move biasing, for students who are looking for an extra
  6412. challenge.
  6413. {\if\edition\racketEd
  6414. To motivate the need for move biasing we return to the running example,
  6415. but this time we use all the general purpose registers. So, we have
  6416. the following mapping of color numbers to registers.
  6417. \[
  6418. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6419. \]
  6420. Using the same assignment of variables to color numbers that was
  6421. produced by the register allocator described in the last section, we
  6422. get the following program.
  6423. \begin{center}
  6424. \begin{minipage}{0.35\textwidth}
  6425. \begin{lstlisting}
  6426. movq $1, v
  6427. movq $42, w
  6428. movq v, x
  6429. addq $7, x
  6430. movq x, y
  6431. movq x, z
  6432. addq w, z
  6433. movq y, t
  6434. negq t
  6435. movq z, %rax
  6436. addq t, %rax
  6437. jmp conclusion
  6438. \end{lstlisting}
  6439. \end{minipage}
  6440. $\Rightarrow\qquad$
  6441. \begin{minipage}{0.45\textwidth}
  6442. \begin{lstlisting}
  6443. movq $1, %rdx
  6444. movq $42, %rcx
  6445. movq %rdx, %rdx
  6446. addq $7, %rdx
  6447. movq %rdx, %rsi
  6448. movq %rdx, %rdx
  6449. addq %rcx, %rdx
  6450. movq %rsi, %rcx
  6451. negq %rcx
  6452. movq %rdx, %rax
  6453. addq %rcx, %rax
  6454. jmp conclusion
  6455. \end{lstlisting}
  6456. \end{minipage}
  6457. \end{center}
  6458. In this output code there are two \key{movq} instructions that
  6459. can be removed because their source and target are the same. However,
  6460. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6461. register, we could instead remove three \key{movq} instructions. We
  6462. can accomplish this by taking into account which variables appear in
  6463. \key{movq} instructions with which other variables.
  6464. \fi}
  6465. {\if\edition\pythonEd\pythonColor
  6466. %
  6467. To motivate the need for move biasing we return to the running example
  6468. and recall that in section~\ref{sec:patch-instructions} we were able to
  6469. remove three trivial move instructions from the running
  6470. example. However, we could remove another trivial move if we were able
  6471. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6472. We say that two variables $p$ and $q$ are \emph{move
  6473. related}\index{subject}{move related} if they participate together in
  6474. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6475. \key{movq} $q$\key{,} $p$.
  6476. %
  6477. Recall that we color variables that are more saturated before coloring
  6478. variables that are less saturated, and in the case of equally
  6479. saturated variables, we choose randomly. Now we break such ties by
  6480. giving preference to variables that have an available color that is
  6481. the same as the color of a move-related variable.
  6482. %
  6483. Furthermore, when the register allocator chooses a color for a
  6484. variable, it should prefer a color that has already been used for a
  6485. move-related variable if one exists (and assuming that they do not
  6486. interfere). This preference should not override the preference for
  6487. registers over stack locations. So, this preference should be used as
  6488. a tie breaker in choosing between two registers or in choosing between
  6489. two stack locations.
  6490. We recommend representing the move relationships in a graph, similarly
  6491. to how we represented interference. The following is the \emph{move
  6492. graph} for our running example.
  6493. {\if\edition\racketEd
  6494. \[
  6495. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6496. \node (rax) at (0,0) {$\ttm{rax}$};
  6497. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6498. \node (t) at (0,2) {$\ttm{t}$};
  6499. \node (z) at (3,2) {$\ttm{z}$};
  6500. \node (x) at (6,2) {$\ttm{x}$};
  6501. \node (y) at (3,0) {$\ttm{y}$};
  6502. \node (w) at (6,0) {$\ttm{w}$};
  6503. \node (v) at (9,0) {$\ttm{v}$};
  6504. \draw (v) to (x);
  6505. \draw (x) to (y);
  6506. \draw (x) to (z);
  6507. \draw (y) to (t);
  6508. \end{tikzpicture}
  6509. \]
  6510. \fi}
  6511. %
  6512. {\if\edition\pythonEd\pythonColor
  6513. \[
  6514. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6515. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6516. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6517. \node (z) at (3,2) {$\ttm{z}$};
  6518. \node (x) at (6,2) {$\ttm{x}$};
  6519. \node (y) at (3,0) {$\ttm{y}$};
  6520. \node (w) at (6,0) {$\ttm{w}$};
  6521. \node (v) at (9,0) {$\ttm{v}$};
  6522. \draw (y) to (t0);
  6523. \draw (z) to (x);
  6524. \draw (z) to (t1);
  6525. \draw (x) to (y);
  6526. \draw (x) to (v);
  6527. \end{tikzpicture}
  6528. \]
  6529. \fi}
  6530. {\if\edition\racketEd
  6531. Now we replay the graph coloring, pausing to see the coloring of
  6532. \code{y}. Recall the following configuration. The most saturated vertices
  6533. were \code{w} and \code{y}.
  6534. \[
  6535. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6536. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6537. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6538. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6539. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6540. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6541. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6542. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6543. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6544. \draw (t1) to (rax);
  6545. \draw (t1) to (z);
  6546. \draw (z) to (y);
  6547. \draw (z) to (w);
  6548. \draw (x) to (w);
  6549. \draw (y) to (w);
  6550. \draw (v) to (w);
  6551. \draw (v) to (rsp);
  6552. \draw (w) to (rsp);
  6553. \draw (x) to (rsp);
  6554. \draw (y) to (rsp);
  6555. \path[-.,bend left=15] (z) edge node {} (rsp);
  6556. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6557. \draw (rax) to (rsp);
  6558. \end{tikzpicture}
  6559. \]
  6560. %
  6561. The last time, we chose to color \code{w} with $0$. This time, we see
  6562. that \code{w} is not move-related to any vertex, but \code{y} is
  6563. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6564. the same color as \code{t}.
  6565. \[
  6566. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6567. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6568. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6569. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6570. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6571. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6572. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6573. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6574. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6575. \draw (t1) to (rax);
  6576. \draw (t1) to (z);
  6577. \draw (z) to (y);
  6578. \draw (z) to (w);
  6579. \draw (x) to (w);
  6580. \draw (y) to (w);
  6581. \draw (v) to (w);
  6582. \draw (v) to (rsp);
  6583. \draw (w) to (rsp);
  6584. \draw (x) to (rsp);
  6585. \draw (y) to (rsp);
  6586. \path[-.,bend left=15] (z) edge node {} (rsp);
  6587. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6588. \draw (rax) to (rsp);
  6589. \end{tikzpicture}
  6590. \]
  6591. Now \code{w} is the most saturated, so we color it $2$.
  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 (t1) 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}:-,\{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}:-,\{2,-2\}$};
  6602. \draw (t1) to (rax);
  6603. \draw (t1) 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. At this point, vertices \code{x} and \code{v} are most saturated, but
  6619. \code{x} is move related to \code{y} and \code{z}, so we color
  6620. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6621. \[
  6622. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6623. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6624. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6625. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6626. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6627. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6628. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6629. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6630. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6631. \draw (t1) to (rax);
  6632. \draw (t) to (z);
  6633. \draw (z) to (y);
  6634. \draw (z) to (w);
  6635. \draw (x) to (w);
  6636. \draw (y) to (w);
  6637. \draw (v) to (w);
  6638. \draw (v) to (rsp);
  6639. \draw (w) to (rsp);
  6640. \draw (x) to (rsp);
  6641. \draw (y) to (rsp);
  6642. \path[-.,bend left=15] (z) edge node {} (rsp);
  6643. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6644. \draw (rax) to (rsp);
  6645. \end{tikzpicture}
  6646. \]
  6647. \fi}
  6648. %
  6649. {\if\edition\pythonEd\pythonColor
  6650. Now we replay the graph coloring, pausing before the coloring of
  6651. \code{w}. Recall the following configuration. The most saturated vertices
  6652. were \code{tmp\_1}, \code{w}, and \code{y}.
  6653. \[
  6654. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6655. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6656. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6657. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6658. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6659. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6660. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6661. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6662. \draw (t0) to (t1);
  6663. \draw (t0) to (z);
  6664. \draw (z) to (y);
  6665. \draw (z) to (w);
  6666. \draw (x) to (w);
  6667. \draw (y) to (w);
  6668. \draw (v) to (w);
  6669. \end{tikzpicture}
  6670. \]
  6671. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6672. or \code{y}, but note that \code{w} is not move related to any
  6673. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6674. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6675. \code{y} and color it $0$, we can delete another move instruction.
  6676. \[
  6677. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6678. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6679. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6680. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6681. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6682. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6683. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6684. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6685. \draw (t0) to (t1);
  6686. \draw (t0) to (z);
  6687. \draw (z) to (y);
  6688. \draw (z) to (w);
  6689. \draw (x) to (w);
  6690. \draw (y) to (w);
  6691. \draw (v) to (w);
  6692. \end{tikzpicture}
  6693. \]
  6694. Now \code{w} is the most saturated, so we color it $2$.
  6695. \[
  6696. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6697. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6698. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6699. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6700. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6701. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6702. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6703. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6704. \draw (t0) to (t1);
  6705. \draw (t0) to (z);
  6706. \draw (z) to (y);
  6707. \draw (z) to (w);
  6708. \draw (x) to (w);
  6709. \draw (y) to (w);
  6710. \draw (v) to (w);
  6711. \end{tikzpicture}
  6712. \]
  6713. To finish the coloring, \code{x} and \code{v} get $0$ and
  6714. \code{tmp\_1} gets $1$.
  6715. \[
  6716. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6717. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6718. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6719. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6720. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6721. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6722. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6723. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6724. \draw (t0) to (t1);
  6725. \draw (t0) to (z);
  6726. \draw (z) to (y);
  6727. \draw (z) to (w);
  6728. \draw (x) to (w);
  6729. \draw (y) to (w);
  6730. \draw (v) to (w);
  6731. \end{tikzpicture}
  6732. \]
  6733. \fi}
  6734. So, we have the following assignment of variables to registers.
  6735. {\if\edition\racketEd
  6736. \begin{gather*}
  6737. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6738. \ttm{w} \mapsto \key{\%rsi}, \,
  6739. \ttm{x} \mapsto \key{\%rcx}, \,
  6740. \ttm{y} \mapsto \key{\%rcx}, \,
  6741. \ttm{z} \mapsto \key{\%rdx}, \,
  6742. \ttm{t} \mapsto \key{\%rcx} \}
  6743. \end{gather*}
  6744. \fi}
  6745. {\if\edition\pythonEd\pythonColor
  6746. \begin{gather*}
  6747. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6748. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6749. \ttm{x} \mapsto \key{\%rcx}, \,
  6750. \ttm{y} \mapsto \key{\%rcx}, \\
  6751. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6752. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6753. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6754. \end{gather*}
  6755. \fi}
  6756. %
  6757. We apply this register assignment to the running example shown next,
  6758. on the left, to obtain the code in the middle. The
  6759. \code{patch\_instructions} then deletes the trivial moves to obtain
  6760. the code on the right.
  6761. {\if\edition\racketEd
  6762. \begin{center}
  6763. \begin{minipage}{0.2\textwidth}
  6764. \begin{lstlisting}
  6765. movq $1, v
  6766. movq $42, w
  6767. movq v, x
  6768. addq $7, x
  6769. movq x, y
  6770. movq x, z
  6771. addq w, z
  6772. movq y, t
  6773. negq t
  6774. movq z, %rax
  6775. addq t, %rax
  6776. jmp conclusion
  6777. \end{lstlisting}
  6778. \end{minipage}
  6779. $\Rightarrow\qquad$
  6780. \begin{minipage}{0.25\textwidth}
  6781. \begin{lstlisting}
  6782. movq $1, %rcx
  6783. movq $42, %rsi
  6784. movq %rcx, %rcx
  6785. addq $7, %rcx
  6786. movq %rcx, %rcx
  6787. movq %rcx, %rdx
  6788. addq %rsi, %rdx
  6789. movq %rcx, %rcx
  6790. negq %rcx
  6791. movq %rdx, %rax
  6792. addq %rcx, %rax
  6793. jmp conclusion
  6794. \end{lstlisting}
  6795. \end{minipage}
  6796. $\Rightarrow\qquad$
  6797. \begin{minipage}{0.23\textwidth}
  6798. \begin{lstlisting}
  6799. movq $1, %rcx
  6800. movq $42, %rsi
  6801. addq $7, %rcx
  6802. movq %rcx, %rdx
  6803. addq %rsi, %rdx
  6804. negq %rcx
  6805. movq %rdx, %rax
  6806. addq %rcx, %rax
  6807. jmp conclusion
  6808. \end{lstlisting}
  6809. \end{minipage}
  6810. \end{center}
  6811. \fi}
  6812. {\if\edition\pythonEd\pythonColor
  6813. \begin{center}
  6814. \begin{minipage}{0.20\textwidth}
  6815. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6816. movq $1, v
  6817. movq $42, w
  6818. movq v, x
  6819. addq $7, x
  6820. movq x, y
  6821. movq x, z
  6822. addq w, z
  6823. movq y, tmp_0
  6824. negq tmp_0
  6825. movq z, tmp_1
  6826. addq tmp_0, tmp_1
  6827. movq tmp_1, %rdi
  6828. callq _print_int
  6829. \end{lstlisting}
  6830. \end{minipage}
  6831. ${\Rightarrow\qquad}$
  6832. \begin{minipage}{0.35\textwidth}
  6833. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6834. movq $1, %rcx
  6835. movq $42, -16(%rbp)
  6836. movq %rcx, %rcx
  6837. addq $7, %rcx
  6838. movq %rcx, %rcx
  6839. movq %rcx, -8(%rbp)
  6840. addq -16(%rbp), -8(%rbp)
  6841. movq %rcx, %rcx
  6842. negq %rcx
  6843. movq -8(%rbp), -8(%rbp)
  6844. addq %rcx, -8(%rbp)
  6845. movq -8(%rbp), %rdi
  6846. callq _print_int
  6847. \end{lstlisting}
  6848. \end{minipage}
  6849. ${\Rightarrow\qquad}$
  6850. \begin{minipage}{0.20\textwidth}
  6851. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6852. movq $1, %rcx
  6853. movq $42, -16(%rbp)
  6854. addq $7, %rcx
  6855. movq %rcx, -8(%rbp)
  6856. movq -16(%rbp), %rax
  6857. addq %rax, -8(%rbp)
  6858. negq %rcx
  6859. addq %rcx, -8(%rbp)
  6860. movq -8(%rbp), %rdi
  6861. callq print_int
  6862. \end{lstlisting}
  6863. \end{minipage}
  6864. \end{center}
  6865. \fi}
  6866. \begin{exercise}\normalfont\normalsize
  6867. Change your implementation of \code{allocate\_registers} to take move
  6868. biasing into account. Create two new tests that include at least one
  6869. opportunity for move biasing, and visually inspect the output x86
  6870. programs to make sure that your move biasing is working properly. Make
  6871. sure that your compiler still passes all the tests.
  6872. \end{exercise}
  6873. %To do: another neat challenge would be to do
  6874. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6875. %% \subsection{Output of the Running Example}
  6876. %% \label{sec:reg-alloc-output}
  6877. % challenge: prioritize variables based on execution frequencies
  6878. % and the number of uses of a variable
  6879. % challenge: enhance the coloring algorithm using Chaitin's
  6880. % approach of prioritizing high-degree variables
  6881. % by removing low-degree variables (coloring them later)
  6882. % from the interference graph
  6883. \section{Further Reading}
  6884. \label{sec:register-allocation-further-reading}
  6885. Early register allocation algorithms were developed for Fortran
  6886. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6887. of graph coloring began in the late 1970s and early 1980s with the
  6888. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6889. algorithm is based on the following observation of
  6890. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6891. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6892. $v$ removed is also $k$ colorable. To see why, suppose that the
  6893. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6894. different colors, but because there are fewer than $k$ neighbors, there
  6895. will be one or more colors left over to use for coloring $v$ in $G$.
  6896. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6897. less than $k$ from the graph and recursively colors the rest of the
  6898. graph. Upon returning from the recursion, it colors $v$ with one of
  6899. the available colors and returns. \citet{Chaitin:1982vn} augments
  6900. this algorithm to handle spilling as follows. If there are no vertices
  6901. of degree lower than $k$ then pick a vertex at random, spill it,
  6902. remove it from the graph, and proceed recursively to color the rest of
  6903. the graph.
  6904. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6905. move-related and that don't interfere with each other, in a process
  6906. called \emph{coalescing}. Although coalescing decreases the number of
  6907. moves, it can make the graph more difficult to
  6908. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6909. which two variables are merged only if they have fewer than $k$
  6910. neighbors of high degree. \citet{George:1996aa} observes that
  6911. conservative coalescing is sometimes too conservative and made it more
  6912. aggressive by iterating the coalescing with the removal of low-degree
  6913. vertices.
  6914. %
  6915. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6916. also proposed \emph{biased coloring}, in which a variable is assigned to
  6917. the same color as another move-related variable if possible, as
  6918. discussed in section~\ref{sec:move-biasing}.
  6919. %
  6920. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6921. performs coalescing, graph coloring, and spill code insertion until
  6922. all variables have been assigned a location.
  6923. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6924. spilled variables that don't have to be: a high-degree variable can be
  6925. colorable if many of its neighbors are assigned the same color.
  6926. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6927. high-degree vertex is not immediately spilled. Instead the decision is
  6928. deferred until after the recursive call, at which point it is apparent
  6929. whether there is actually an available color or not. We observe that
  6930. this algorithm is equivalent to the smallest-last ordering
  6931. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6932. be registers and the rest to be stack locations.
  6933. %% biased coloring
  6934. Earlier editions of the compiler course at Indiana University
  6935. \citep{Dybvig:2010aa} were based on the algorithm of
  6936. \citet{Briggs:1994kx}.
  6937. The smallest-last ordering algorithm is one of many \emph{greedy}
  6938. coloring algorithms. A greedy coloring algorithm visits all the
  6939. vertices in a particular order and assigns each one the first
  6940. available color. An \emph{offline} greedy algorithm chooses the
  6941. ordering up front, prior to assigning colors. The algorithm of
  6942. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6943. ordering does not depend on the colors assigned. Other orderings are
  6944. possible. For example, \citet{Chow:1984ys} ordered variables according
  6945. to an estimate of runtime cost.
  6946. An \emph{online} greedy coloring algorithm uses information about the
  6947. current assignment of colors to influence the order in which the
  6948. remaining vertices are colored. The saturation-based algorithm
  6949. described in this chapter is one such algorithm. We choose to use
  6950. saturation-based coloring because it is fun to introduce graph
  6951. coloring via sudoku!
  6952. A register allocator may choose to map each variable to just one
  6953. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6954. variable to one or more locations. The latter can be achieved by
  6955. \emph{live range splitting}, where a variable is replaced by several
  6956. variables that each handle part of its live
  6957. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6958. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6959. %% replacement algorithm, bottom-up local
  6960. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6961. %% Cooper: top-down (priority bassed), bottom-up
  6962. %% top-down
  6963. %% order variables by priority (estimated cost)
  6964. %% caveat: split variables into two groups:
  6965. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6966. %% color the constrained ones first
  6967. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6968. %% cite J. Cocke for an algorithm that colors variables
  6969. %% in a high-degree first ordering
  6970. %Register Allocation via Usage Counts, Freiburghouse CACM
  6971. \citet{Palsberg:2007si} observes that many of the interference graphs
  6972. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6973. that is, every cycle with four or more edges has an edge that is not
  6974. part of the cycle but that connects two vertices on the cycle. Such
  6975. graphs can be optimally colored by the greedy algorithm with a vertex
  6976. ordering determined by maximum cardinality search.
  6977. In situations in which compile time is of utmost importance, such as
  6978. in just-in-time compilers, graph coloring algorithms can be too
  6979. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6980. be more appropriate.
  6981. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6982. {\if\edition\racketEd
  6983. \addtocontents{toc}{\newpage}
  6984. \fi}
  6985. \chapter{Booleans and Conditionals}
  6986. \label{ch:Lif}
  6987. \setcounter{footnote}{0}
  6988. The \LangVar{} language has only a single kind of value, the
  6989. integers. In this chapter we add a second kind of value, the Booleans,
  6990. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6991. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  6992. are written
  6993. \TRUE{}\index{subject}{True@\TRUE{}} and
  6994. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  6995. language includes several operations that involve Booleans
  6996. (\key{and}\index{subject}{and@\ANDNAME{}},
  6997. \key{or}\index{subject}{or@\ORNAME{}},
  6998. \key{not}\index{subject}{not@\NOTNAME{}},
  6999. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7000. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7001. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7002. conditional expression\index{subject}{conditional expression}
  7003. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7004. With the addition of \key{if}, programs can have
  7005. nontrivial control flow\index{subject}{control flow} which
  7006. %
  7007. \racket{impacts \code{explicate\_control} and liveness analysis.}
  7008. %
  7009. \python{impacts liveness analysis and motivates a new pass named
  7010. \code{explicate\_control}.}%
  7011. %
  7012. Also, because we now have two kinds of values, we need to handle
  7013. programs that apply an operation to the wrong kind of value, such as
  7014. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7015. There are two language design options for such situations. One option
  7016. is to signal an error and the other is to provide a wider
  7017. interpretation of the operation. \racket{The Racket
  7018. language}\python{Python} uses a mixture of these two options,
  7019. depending on the operation and the kind of value. For example, the
  7020. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7021. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7022. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7023. %
  7024. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7025. in Racket because \code{car} expects a pair.}
  7026. %
  7027. \python{On the other hand, \code{1[0]} results in a runtime error
  7028. in Python because an ``\code{int} object is not subscriptable''.}
  7029. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7030. design choices as \racket{Racket}\python{Python}, except that much of the
  7031. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7032. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7033. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7034. \python{MyPy} reports a compile-time error
  7035. %
  7036. \racket{because Racket expects the type of the argument to be of the form
  7037. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7038. %
  7039. \python{stating that a ``value of type \code{int} is not indexable''.}
  7040. The \LangIf{} language performs type checking during compilation just as
  7041. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7042. the alternative choice, that is, a dynamically typed language like
  7043. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7044. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7045. restrictive, for example, rejecting \racket{\code{(not
  7046. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7047. fairly simple because the focus of this book is on compilation and not
  7048. type systems, about which there are already several excellent
  7049. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7050. This chapter is organized as follows. We begin by defining the syntax
  7051. and interpreter for the \LangIf{} language
  7052. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7053. checking (aka semantic analysis\index{subject}{semantic analysis})
  7054. and define a type checker for \LangIf{}
  7055. (section~\ref{sec:type-check-Lif}).
  7056. %
  7057. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7058. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7059. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7060. %
  7061. The remaining sections of this chapter discuss how Booleans and
  7062. conditional control flow require changes to the existing compiler
  7063. passes and the addition of new ones. We introduce the \code{shrink}
  7064. pass to translate some operators into others, thereby reducing the
  7065. number of operators that need to be handled in later passes.
  7066. %
  7067. The main event of this chapter is the \code{explicate\_control} pass
  7068. that is responsible for translating \code{if}s into conditional
  7069. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7070. %
  7071. Regarding register allocation, there is the interesting question of
  7072. how to handle conditional \code{goto}s during liveness analysis.
  7073. \section{The \LangIf{} Language}
  7074. \label{sec:lang-if}
  7075. Definitions of the concrete syntax and abstract syntax of the
  7076. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7077. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7078. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7079. literals\index{subject}{literals}
  7080. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7081. \python{, and the \code{if} statement}. We expand the set of
  7082. operators to include
  7083. \begin{enumerate}
  7084. \item the logical operators \key{and}, \key{or}, and \key{not},
  7085. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7086. for comparing integers or Booleans for equality, and
  7087. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7088. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7089. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7090. comparing integers.
  7091. \end{enumerate}
  7092. \racket{We reorganize the abstract syntax for the primitive
  7093. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7094. rule for all of them. This means that the grammar no longer checks
  7095. whether the arity of an operator matches the number of
  7096. arguments. That responsibility is moved to the type checker for
  7097. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7098. \newcommand{\LifGrammarRacket}{
  7099. \begin{array}{lcl}
  7100. \Type &::=& \key{Boolean} \\
  7101. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7102. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7103. \Exp &::=& \itm{bool}
  7104. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7105. \MID (\key{not}\;\Exp) \\
  7106. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7107. \end{array}
  7108. }
  7109. \newcommand{\LifASTRacket}{
  7110. \begin{array}{lcl}
  7111. \Type &::=& \key{Boolean} \\
  7112. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7113. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7114. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7115. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7116. \end{array}
  7117. }
  7118. \newcommand{\LintOpAST}{
  7119. \begin{array}{rcl}
  7120. \Type &::=& \key{Integer} \\
  7121. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7122. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7123. \end{array}
  7124. }
  7125. \newcommand{\LifGrammarPython}{
  7126. \begin{array}{rcl}
  7127. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7128. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7129. \MID \key{not}~\Exp \\
  7130. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7131. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7132. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7133. \end{array}
  7134. }
  7135. \newcommand{\LifASTPython}{
  7136. \begin{array}{lcl}
  7137. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7138. \itm{unaryop} &::=& \code{Not()} \\
  7139. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7140. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7141. \Exp &::=& \BOOL{\itm{bool}}
  7142. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7143. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7144. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7145. \end{array}
  7146. }
  7147. \begin{figure}[tp]
  7148. \centering
  7149. \begin{tcolorbox}[colback=white]
  7150. {\if\edition\racketEd
  7151. \[
  7152. \begin{array}{l}
  7153. \gray{\LintGrammarRacket{}} \\ \hline
  7154. \gray{\LvarGrammarRacket{}} \\ \hline
  7155. \LifGrammarRacket{} \\
  7156. \begin{array}{lcl}
  7157. \LangIfM{} &::=& \Exp
  7158. \end{array}
  7159. \end{array}
  7160. \]
  7161. \fi}
  7162. {\if\edition\pythonEd\pythonColor
  7163. \[
  7164. \begin{array}{l}
  7165. \gray{\LintGrammarPython} \\ \hline
  7166. \gray{\LvarGrammarPython} \\ \hline
  7167. \LifGrammarPython \\
  7168. \begin{array}{rcl}
  7169. \LangIfM{} &::=& \Stmt^{*}
  7170. \end{array}
  7171. \end{array}
  7172. \]
  7173. \fi}
  7174. \end{tcolorbox}
  7175. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7176. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7177. \label{fig:Lif-concrete-syntax}
  7178. \end{figure}
  7179. \begin{figure}[tp]
  7180. %\begin{minipage}{0.66\textwidth}
  7181. \begin{tcolorbox}[colback=white]
  7182. \centering
  7183. {\if\edition\racketEd
  7184. \[
  7185. \begin{array}{l}
  7186. \gray{\LintOpAST} \\ \hline
  7187. \gray{\LvarASTRacket{}} \\ \hline
  7188. \LifASTRacket{} \\
  7189. \begin{array}{lcl}
  7190. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7191. \end{array}
  7192. \end{array}
  7193. \]
  7194. \fi}
  7195. {\if\edition\pythonEd\pythonColor
  7196. \[
  7197. \begin{array}{l}
  7198. \gray{\LintASTPython} \\ \hline
  7199. \gray{\LvarASTPython} \\ \hline
  7200. \LifASTPython \\
  7201. \begin{array}{lcl}
  7202. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7203. \end{array}
  7204. \end{array}
  7205. \]
  7206. \fi}
  7207. \end{tcolorbox}
  7208. %\end{minipage}
  7209. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7210. \python{
  7211. \index{subject}{BoolOp@\texttt{BoolOp}}
  7212. \index{subject}{Compare@\texttt{Compare}}
  7213. \index{subject}{Lt@\texttt{Lt}}
  7214. \index{subject}{LtE@\texttt{LtE}}
  7215. \index{subject}{Gt@\texttt{Gt}}
  7216. \index{subject}{GtE@\texttt{GtE}}
  7217. }
  7218. \caption{The abstract syntax of \LangIf{}.}
  7219. \label{fig:Lif-syntax}
  7220. \end{figure}
  7221. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7222. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7223. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  7224. evaluate to the corresponding Boolean values. The conditional
  7225. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  7226. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  7227. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  7228. \code{or}, and \code{not} behave according to propositional logic. In
  7229. addition, the \code{and} and \code{or} operations perform
  7230. \emph{short-circuit evaluation}.
  7231. %
  7232. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7233. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7234. %
  7235. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7236. evaluated if $e_1$ evaluates to \TRUE{}.
  7237. \racket{With the increase in the number of primitive operations, the
  7238. interpreter would become repetitive without some care. We refactor
  7239. the case for \code{Prim}, moving the code that differs with each
  7240. operation into the \code{interp\_op} method shown in
  7241. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7242. \code{or} operations separately because of their short-circuiting
  7243. behavior.}
  7244. \begin{figure}[tbp]
  7245. \begin{tcolorbox}[colback=white]
  7246. {\if\edition\racketEd
  7247. \begin{lstlisting}
  7248. (define interp-Lif-class
  7249. (class interp-Lvar-class
  7250. (super-new)
  7251. (define/public (interp_op op) ...)
  7252. (define/override ((interp_exp env) e)
  7253. (define recur (interp_exp env))
  7254. (match e
  7255. [(Bool b) b]
  7256. [(If cnd thn els)
  7257. (match (recur cnd)
  7258. [#t (recur thn)]
  7259. [#f (recur els)])]
  7260. [(Prim 'and (list e1 e2))
  7261. (match (recur e1)
  7262. [#t (match (recur e2) [#t #t] [#f #f])]
  7263. [#f #f])]
  7264. [(Prim 'or (list e1 e2))
  7265. (define v1 (recur e1))
  7266. (match v1
  7267. [#t #t]
  7268. [#f (match (recur e2) [#t #t] [#f #f])])]
  7269. [(Prim op args)
  7270. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7271. [else ((super interp_exp env) e)]))
  7272. ))
  7273. (define (interp_Lif p)
  7274. (send (new interp-Lif-class) interp_program p))
  7275. \end{lstlisting}
  7276. \fi}
  7277. {\if\edition\pythonEd\pythonColor
  7278. \begin{lstlisting}
  7279. class InterpLif(InterpLvar):
  7280. def interp_exp(self, e, env):
  7281. match e:
  7282. case IfExp(test, body, orelse):
  7283. if self.interp_exp(test, env):
  7284. return self.interp_exp(body, env)
  7285. else:
  7286. return self.interp_exp(orelse, env)
  7287. case UnaryOp(Not(), v):
  7288. return not self.interp_exp(v, env)
  7289. case BoolOp(And(), values):
  7290. if self.interp_exp(values[0], env):
  7291. return self.interp_exp(values[1], env)
  7292. else:
  7293. return False
  7294. case BoolOp(Or(), values):
  7295. if self.interp_exp(values[0], env):
  7296. return True
  7297. else:
  7298. return self.interp_exp(values[1], env)
  7299. case Compare(left, [cmp], [right]):
  7300. l = self.interp_exp(left, env)
  7301. r = self.interp_exp(right, env)
  7302. return self.interp_cmp(cmp)(l, r)
  7303. case _:
  7304. return super().interp_exp(e, env)
  7305. def interp_stmt(self, s, env, cont):
  7306. match s:
  7307. case If(test, body, orelse):
  7308. match self.interp_exp(test, env):
  7309. case True:
  7310. return self.interp_stmts(body + cont, env)
  7311. case False:
  7312. return self.interp_stmts(orelse + cont, env)
  7313. case _:
  7314. return super().interp_stmt(s, env, cont)
  7315. ...
  7316. \end{lstlisting}
  7317. \fi}
  7318. \end{tcolorbox}
  7319. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7320. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7321. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7322. \label{fig:interp-Lif}
  7323. \end{figure}
  7324. {\if\edition\racketEd
  7325. \begin{figure}[tbp]
  7326. \begin{tcolorbox}[colback=white]
  7327. \begin{lstlisting}
  7328. (define/public (interp_op op)
  7329. (match op
  7330. ['+ fx+]
  7331. ['- fx-]
  7332. ['read read-fixnum]
  7333. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7334. ['eq? (lambda (v1 v2)
  7335. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7336. (and (boolean? v1) (boolean? v2))
  7337. (and (vector? v1) (vector? v2)))
  7338. (eq? v1 v2)]))]
  7339. ['< (lambda (v1 v2)
  7340. (cond [(and (fixnum? v1) (fixnum? v2))
  7341. (< v1 v2)]))]
  7342. ['<= (lambda (v1 v2)
  7343. (cond [(and (fixnum? v1) (fixnum? v2))
  7344. (<= v1 v2)]))]
  7345. ['> (lambda (v1 v2)
  7346. (cond [(and (fixnum? v1) (fixnum? v2))
  7347. (> v1 v2)]))]
  7348. ['>= (lambda (v1 v2)
  7349. (cond [(and (fixnum? v1) (fixnum? v2))
  7350. (>= v1 v2)]))]
  7351. [else (error 'interp_op "unknown operator")]))
  7352. \end{lstlisting}
  7353. \end{tcolorbox}
  7354. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7355. \label{fig:interp-op-Lif}
  7356. \end{figure}
  7357. \fi}
  7358. {\if\edition\pythonEd\pythonColor
  7359. \begin{figure}
  7360. \begin{tcolorbox}[colback=white]
  7361. \begin{lstlisting}
  7362. class InterpLif(InterpLvar):
  7363. ...
  7364. def interp_cmp(self, cmp):
  7365. match cmp:
  7366. case Lt():
  7367. return lambda x, y: x < y
  7368. case LtE():
  7369. return lambda x, y: x <= y
  7370. case Gt():
  7371. return lambda x, y: x > y
  7372. case GtE():
  7373. return lambda x, y: x >= y
  7374. case Eq():
  7375. return lambda x, y: x == y
  7376. case NotEq():
  7377. return lambda x, y: x != y
  7378. \end{lstlisting}
  7379. \end{tcolorbox}
  7380. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7381. \label{fig:interp-cmp-Lif}
  7382. \end{figure}
  7383. \fi}
  7384. \section{Type Checking \LangIf{} Programs}
  7385. \label{sec:type-check-Lif}
  7386. It is helpful to think about type checking\index{subject}{type
  7387. checking} in two complementary ways. A type checker predicts the
  7388. type of value that will be produced by each expression in the program.
  7389. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7390. type checker should predict that {\if\edition\racketEd
  7391. \begin{lstlisting}
  7392. (+ 10 (- (+ 12 20)))
  7393. \end{lstlisting}
  7394. \fi}
  7395. {\if\edition\pythonEd\pythonColor
  7396. \begin{lstlisting}
  7397. 10 + -(12 + 20)
  7398. \end{lstlisting}
  7399. \fi}
  7400. \noindent produces a value of type \INTTY{}, whereas
  7401. {\if\edition\racketEd
  7402. \begin{lstlisting}
  7403. (and (not #f) #t)
  7404. \end{lstlisting}
  7405. \fi}
  7406. {\if\edition\pythonEd\pythonColor
  7407. \begin{lstlisting}
  7408. (not False) and True
  7409. \end{lstlisting}
  7410. \fi}
  7411. \noindent produces a value of type \BOOLTY{}.
  7412. A second way to think about type checking is that it enforces a set of
  7413. rules about which operators can be applied to which kinds of
  7414. values. For example, our type checker for \LangIf{} signals an error
  7415. for the following expression:
  7416. %
  7417. {\if\edition\racketEd
  7418. \begin{lstlisting}
  7419. (not (+ 10 (- (+ 12 20))))
  7420. \end{lstlisting}
  7421. \fi}
  7422. {\if\edition\pythonEd\pythonColor
  7423. \begin{lstlisting}
  7424. not (10 + -(12 + 20))
  7425. \end{lstlisting}
  7426. \fi}
  7427. \noindent The subexpression
  7428. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7429. \python{\code{(10 + -(12 + 20))}}
  7430. has type \INTTY{}, but the type checker enforces the rule that the
  7431. argument of \code{not} must be an expression of type \BOOLTY{}.
  7432. We implement type checking using classes and methods because they
  7433. provide the open recursion needed to reuse code as we extend the type
  7434. checker in subsequent chapters, analogous to the use of classes and methods
  7435. for the interpreters (section~\ref{sec:extensible-interp}).
  7436. We separate the type checker for the \LangVar{} subset into its own
  7437. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7438. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7439. from the type checker for \LangVar{}. These type checkers are in the
  7440. files
  7441. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7442. and
  7443. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7444. of the support code.
  7445. %
  7446. Each type checker is a structurally recursive function over the AST.
  7447. Given an input expression \code{e}, the type checker either signals an
  7448. error or returns \racket{an expression and} its type.
  7449. %
  7450. \racket{It returns an expression because there are situations in which
  7451. we want to change or update the expression.}
  7452. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7453. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7454. constant is \INTTY{}. To handle variables, the type checker uses the
  7455. environment \code{env} to map variables to types.
  7456. %
  7457. \racket{Consider the case for \key{let}. We type check the
  7458. initializing expression to obtain its type \key{T} and then
  7459. associate type \code{T} with the variable \code{x} in the
  7460. environment used to type check the body of the \key{let}. Thus,
  7461. when the type checker encounters a use of variable \code{x}, it can
  7462. find its type in the environment.}
  7463. %
  7464. \python{Consider the case for assignment. We type check the
  7465. initializing expression to obtain its type \key{t}. If the variable
  7466. \code{lhs.id} is already in the environment because there was a
  7467. prior assignment, we check that this initializer has the same type
  7468. as the prior one. If this is the first assignment to the variable,
  7469. we associate type \code{t} with the variable \code{lhs.id} in the
  7470. environment. Thus, when the type checker encounters a use of
  7471. variable \code{x}, it can find its type in the environment.}
  7472. %
  7473. \racket{Regarding primitive operators, we recursively analyze the
  7474. arguments and then invoke \code{type\_check\_op} to check whether
  7475. the argument types are allowed.}
  7476. %
  7477. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7478. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7479. \racket{Several auxiliary methods are used in the type checker. The
  7480. method \code{operator-types} defines a dictionary that maps the
  7481. operator names to their parameter and return types. The
  7482. \code{type-equal?} method determines whether two types are equal,
  7483. which for now simply dispatches to \code{equal?} (deep
  7484. equality). The \code{check-type-equal?} method triggers an error if
  7485. the two types are not equal. The \code{type-check-op} method looks
  7486. up the operator in the \code{operator-types} dictionary and then
  7487. checks whether the argument types are equal to the parameter types.
  7488. The result is the return type of the operator.}
  7489. %
  7490. \python{The auxiliary method \code{check\_type\_equal} triggers
  7491. an error if the two types are not equal.}
  7492. \begin{figure}[tbp]
  7493. \begin{tcolorbox}[colback=white]
  7494. {\if\edition\racketEd
  7495. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7496. (define type-check-Lvar-class
  7497. (class object%
  7498. (super-new)
  7499. (define/public (operator-types)
  7500. '((+ . ((Integer Integer) . Integer))
  7501. (- . ((Integer Integer) . Integer))
  7502. (read . (() . Integer))))
  7503. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7504. (define/public (check-type-equal? t1 t2 e)
  7505. (unless (type-equal? t1 t2)
  7506. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7507. (define/public (type-check-op op arg-types e)
  7508. (match (dict-ref (operator-types) op)
  7509. [`(,param-types . ,return-type)
  7510. (for ([at arg-types] [pt param-types])
  7511. (check-type-equal? at pt e))
  7512. return-type]
  7513. [else (error 'type-check-op "unrecognized ~a" op)]))
  7514. (define/public (type-check-exp env)
  7515. (lambda (e)
  7516. (match e
  7517. [(Int n) (values (Int n) 'Integer)]
  7518. [(Var x) (values (Var x) (dict-ref env x))]
  7519. [(Let x e body)
  7520. (define-values (e^ Te) ((type-check-exp env) e))
  7521. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7522. (values (Let x e^ b) Tb)]
  7523. [(Prim op es)
  7524. (define-values (new-es ts)
  7525. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7526. (values (Prim op new-es) (type-check-op op ts e))]
  7527. [else (error 'type-check-exp "couldn't match" e)])))
  7528. (define/public (type-check-program e)
  7529. (match e
  7530. [(Program info body)
  7531. (define-values (body^ Tb) ((type-check-exp '()) body))
  7532. (check-type-equal? Tb 'Integer body)
  7533. (Program info body^)]
  7534. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7535. ))
  7536. (define (type-check-Lvar p)
  7537. (send (new type-check-Lvar-class) type-check-program p))
  7538. \end{lstlisting}
  7539. \fi}
  7540. {\if\edition\pythonEd\pythonColor
  7541. \begin{lstlisting}[escapechar=`]
  7542. class TypeCheckLvar:
  7543. def check_type_equal(self, t1, t2, e):
  7544. if t1 != t2:
  7545. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7546. raise Exception(msg)
  7547. def type_check_exp(self, e, env):
  7548. match e:
  7549. case BinOp(left, (Add() | Sub()), right):
  7550. l = self.type_check_exp(left, env)
  7551. check_type_equal(l, int, left)
  7552. r = self.type_check_exp(right, env)
  7553. check_type_equal(r, int, right)
  7554. return int
  7555. case UnaryOp(USub(), v):
  7556. t = self.type_check_exp(v, env)
  7557. check_type_equal(t, int, v)
  7558. return int
  7559. case Name(id):
  7560. return env[id]
  7561. case Constant(value) if isinstance(value, int):
  7562. return int
  7563. case Call(Name('input_int'), []):
  7564. return int
  7565. def type_check_stmts(self, ss, env):
  7566. if len(ss) == 0:
  7567. return
  7568. match ss[0]:
  7569. case Assign([lhs], value):
  7570. t = self.type_check_exp(value, env)
  7571. if lhs.id in env:
  7572. check_type_equal(env[lhs.id], t, value)
  7573. else:
  7574. env[lhs.id] = t
  7575. return self.type_check_stmts(ss[1:], env)
  7576. case Expr(Call(Name('print'), [arg])):
  7577. t = self.type_check_exp(arg, env)
  7578. check_type_equal(t, int, arg)
  7579. return self.type_check_stmts(ss[1:], env)
  7580. case Expr(value):
  7581. self.type_check_exp(value, env)
  7582. return self.type_check_stmts(ss[1:], env)
  7583. def type_check_P(self, p):
  7584. match p:
  7585. case Module(body):
  7586. self.type_check_stmts(body, {})
  7587. \end{lstlisting}
  7588. \fi}
  7589. \end{tcolorbox}
  7590. \caption{Type checker for the \LangVar{} language.}
  7591. \label{fig:type-check-Lvar}
  7592. \end{figure}
  7593. \begin{figure}[tbp]
  7594. \begin{tcolorbox}[colback=white]
  7595. {\if\edition\racketEd
  7596. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7597. (define type-check-Lif-class
  7598. (class type-check-Lvar-class
  7599. (super-new)
  7600. (inherit check-type-equal?)
  7601. (define/override (operator-types)
  7602. (append '((and . ((Boolean Boolean) . Boolean))
  7603. (or . ((Boolean Boolean) . Boolean))
  7604. (< . ((Integer Integer) . Boolean))
  7605. (<= . ((Integer Integer) . Boolean))
  7606. (> . ((Integer Integer) . Boolean))
  7607. (>= . ((Integer Integer) . Boolean))
  7608. (not . ((Boolean) . Boolean)))
  7609. (super operator-types)))
  7610. (define/override (type-check-exp env)
  7611. (lambda (e)
  7612. (match e
  7613. [(Bool b) (values (Bool b) 'Boolean)]
  7614. [(Prim 'eq? (list e1 e2))
  7615. (define-values (e1^ T1) ((type-check-exp env) e1))
  7616. (define-values (e2^ T2) ((type-check-exp env) e2))
  7617. (check-type-equal? T1 T2 e)
  7618. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7619. [(If cnd thn els)
  7620. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7621. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7622. (define-values (els^ Te) ((type-check-exp env) els))
  7623. (check-type-equal? Tc 'Boolean e)
  7624. (check-type-equal? Tt Te e)
  7625. (values (If cnd^ thn^ els^) Te)]
  7626. [else ((super type-check-exp env) e)])))
  7627. ))
  7628. (define (type-check-Lif p)
  7629. (send (new type-check-Lif-class) type-check-program p))
  7630. \end{lstlisting}
  7631. \fi}
  7632. {\if\edition\pythonEd\pythonColor
  7633. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7634. class TypeCheckLif(TypeCheckLvar):
  7635. def type_check_exp(self, e, env):
  7636. match e:
  7637. case Constant(value) if isinstance(value, bool):
  7638. return bool
  7639. case BinOp(left, Sub(), right):
  7640. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7641. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7642. return int
  7643. case UnaryOp(Not(), v):
  7644. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7645. return bool
  7646. case BoolOp(op, values):
  7647. left = values[0] ; right = values[1]
  7648. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7649. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7650. return bool
  7651. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7652. or isinstance(cmp, NotEq):
  7653. l = self.type_check_exp(left, env)
  7654. r = self.type_check_exp(right, env)
  7655. check_type_equal(l, r, e)
  7656. return bool
  7657. case Compare(left, [cmp], [right]):
  7658. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7659. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7660. return bool
  7661. case IfExp(test, body, orelse):
  7662. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7663. b = self.type_check_exp(body, env)
  7664. o = self.type_check_exp(orelse, env)
  7665. check_type_equal(b, o, e)
  7666. return b
  7667. case _:
  7668. return super().type_check_exp(e, env)
  7669. def type_check_stmts(self, ss, env):
  7670. if len(ss) == 0:
  7671. return
  7672. match ss[0]:
  7673. case If(test, body, orelse):
  7674. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7675. b = self.type_check_stmts(body, env)
  7676. o = self.type_check_stmts(orelse, env)
  7677. check_type_equal(b, o, ss[0])
  7678. return self.type_check_stmts(ss[1:], env)
  7679. case _:
  7680. return super().type_check_stmts(ss, env)
  7681. \end{lstlisting}
  7682. \fi}
  7683. \end{tcolorbox}
  7684. \caption{Type checker for the \LangIf{} language.}
  7685. \label{fig:type-check-Lif}
  7686. \end{figure}
  7687. The definition of the type checker for \LangIf{} is shown in
  7688. figure~\ref{fig:type-check-Lif}.
  7689. %
  7690. The type of a Boolean constant is \BOOLTY{}.
  7691. %
  7692. \racket{The \code{operator-types} function adds dictionary entries for
  7693. the new operators.}
  7694. %
  7695. \python{Logical not requires its argument to be a \BOOLTY{} and
  7696. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  7697. %
  7698. The equality operator requires the two arguments to have the same type,
  7699. and therefore we handle it separately from the other operators.
  7700. %
  7701. \python{The other comparisons (less-than, etc.) require their
  7702. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  7703. %
  7704. The condition of an \code{if} must
  7705. be of \BOOLTY{} type, and the two branches must have the same type.
  7706. \begin{exercise}\normalfont\normalsize
  7707. Create ten new test programs in \LangIf{}. Half the programs should
  7708. have a type error. For those programs, create an empty file with the
  7709. same base name and with file extension \code{.tyerr}. For example, if
  7710. the test
  7711. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7712. is expected to error, then create
  7713. an empty file named \code{cond\_test\_14.tyerr}.
  7714. %
  7715. \racket{This indicates to \code{interp-tests} and
  7716. \code{compiler-tests} that a type error is expected. }
  7717. %
  7718. The other half of the test programs should not have type errors.
  7719. %
  7720. \racket{In the \code{run-tests.rkt} script, change the second argument
  7721. of \code{interp-tests} and \code{compiler-tests} to
  7722. \code{type-check-Lif}, which causes the type checker to run prior to
  7723. the compiler passes. Temporarily change the \code{passes} to an
  7724. empty list and run the script, thereby checking that the new test
  7725. programs either type check or do not, as intended.}
  7726. %
  7727. Run the test script to check that these test programs type check as
  7728. expected.
  7729. \end{exercise}
  7730. \clearpage
  7731. \section{The \LangCIf{} Intermediate Language}
  7732. \label{sec:Cif}
  7733. {\if\edition\racketEd
  7734. %
  7735. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7736. comparison operators to the \Exp{} nonterminal and the literals
  7737. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7738. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7739. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7740. comparison operation and the branches are \code{goto} statements,
  7741. making it straightforward to compile \code{if} statements to x86. The
  7742. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7743. expressions. A \code{goto} statement transfers control to the $\Tail$
  7744. expression corresponding to its label.
  7745. %
  7746. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7747. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7748. defines its abstract syntax.
  7749. %
  7750. \fi}
  7751. %
  7752. {\if\edition\pythonEd\pythonColor
  7753. %
  7754. The output of \key{explicate\_control} is a language similar to the
  7755. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7756. \code{goto} statements, so we name it \LangCIf{}.
  7757. %
  7758. The \LangCIf{} language supports the same operators as \LangIf{} but
  7759. the arguments of operators are restricted to atomic expressions. The
  7760. \LangCIf{} language does not include \code{if} expressions but it does
  7761. include a restricted form of \code{if} statement. The condition must be
  7762. a comparison and the two branches may only contain \code{goto}
  7763. statements. These restrictions make it easier to translate \code{if}
  7764. statements to x86. The \LangCIf{} language also adds a \code{return}
  7765. statement to finish the program with a specified value.
  7766. %
  7767. The \key{CProgram} construct contains a dictionary mapping labels to
  7768. lists of statements that end with a \code{return} statement, a
  7769. \code{goto}, or a conditional \code{goto}.
  7770. %% Statement lists of this
  7771. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  7772. %% is a control transfer at the end and control only enters at the
  7773. %% beginning of the list, which is marked by the label.
  7774. %
  7775. A \code{goto} statement transfers control to the sequence of statements
  7776. associated with its label.
  7777. %
  7778. The concrete syntax for \LangCIf{} is defined in
  7779. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  7780. in figure~\ref{fig:c1-syntax}.
  7781. %
  7782. \fi}
  7783. %
  7784. \newcommand{\CifGrammarRacket}{
  7785. \begin{array}{lcl}
  7786. \Atm &::=& \itm{bool} \\
  7787. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7788. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7789. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7790. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7791. \end{array}
  7792. }
  7793. \newcommand{\CifASTRacket}{
  7794. \begin{array}{lcl}
  7795. \Atm &::=& \BOOL{\itm{bool}} \\
  7796. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7797. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7798. \Tail &::= & \GOTO{\itm{label}} \\
  7799. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7800. \end{array}
  7801. }
  7802. \newcommand{\CifGrammarPython}{
  7803. \begin{array}{lcl}
  7804. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7805. \Exp &::= & \Atm \MID \CREAD{}
  7806. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7807. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7808. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7809. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  7810. &\MID& \CASSIGN{\Var}{\Exp}
  7811. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7812. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7813. \end{array}
  7814. }
  7815. \newcommand{\CifASTPython}{
  7816. \begin{array}{lcl}
  7817. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7818. \Exp &::= & \Atm \MID \READ{} \\
  7819. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7820. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7821. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7822. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7823. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  7824. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7825. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7826. \end{array}
  7827. }
  7828. \begin{figure}[tbp]
  7829. \begin{tcolorbox}[colback=white]
  7830. \small
  7831. {\if\edition\racketEd
  7832. \[
  7833. \begin{array}{l}
  7834. \gray{\CvarGrammarRacket} \\ \hline
  7835. \CifGrammarRacket \\
  7836. \begin{array}{lcl}
  7837. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7838. \end{array}
  7839. \end{array}
  7840. \]
  7841. \fi}
  7842. {\if\edition\pythonEd\pythonColor
  7843. \[
  7844. \begin{array}{l}
  7845. \CifGrammarPython \\
  7846. \begin{array}{lcl}
  7847. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  7848. \end{array}
  7849. \end{array}
  7850. \]
  7851. \fi}
  7852. \end{tcolorbox}
  7853. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7854. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7855. \label{fig:c1-concrete-syntax}
  7856. \end{figure}
  7857. \begin{figure}[tp]
  7858. \begin{tcolorbox}[colback=white]
  7859. \small
  7860. {\if\edition\racketEd
  7861. \[
  7862. \begin{array}{l}
  7863. \gray{\CvarASTRacket} \\ \hline
  7864. \CifASTRacket \\
  7865. \begin{array}{lcl}
  7866. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7867. \end{array}
  7868. \end{array}
  7869. \]
  7870. \fi}
  7871. {\if\edition\pythonEd\pythonColor
  7872. \[
  7873. \begin{array}{l}
  7874. \CifASTPython \\
  7875. \begin{array}{lcl}
  7876. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  7877. \end{array}
  7878. \end{array}
  7879. \]
  7880. \fi}
  7881. \end{tcolorbox}
  7882. \racket{
  7883. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7884. }
  7885. \index{subject}{Goto@\texttt{Goto}}
  7886. \index{subject}{Return@\texttt{Return}}
  7887. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7888. (figure~\ref{fig:c0-syntax})}.}
  7889. \label{fig:c1-syntax}
  7890. \end{figure}
  7891. \section{The \LangXIf{} Language}
  7892. \label{sec:x86-if}
  7893. \index{subject}{x86} To implement the new logical operations, the
  7894. comparison operations, and the \key{if} expression\python{ and
  7895. statement}, we delve further into the x86
  7896. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7897. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7898. subset of x86, which includes instructions for logical operations,
  7899. comparisons, and \racket{conditional} jumps.
  7900. %
  7901. \python{The abstract syntax for an \LangXIf{} program contains a
  7902. dictionary mapping labels to sequences of instructions, each of
  7903. which we refer to as a \emph{basic block}\index{subject}{basic
  7904. block}.}
  7905. One challenge is that x86 does not provide an instruction that
  7906. directly implements logical negation (\code{not} in \LangIf{} and
  7907. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7908. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7909. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7910. bit of its arguments, and writes the results into its second argument.
  7911. Recall the following truth table for exclusive-or:
  7912. \begin{center}
  7913. \begin{tabular}{l|cc}
  7914. & 0 & 1 \\ \hline
  7915. 0 & 0 & 1 \\
  7916. 1 & 1 & 0
  7917. \end{tabular}
  7918. \end{center}
  7919. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7920. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7921. for the bit $1$, the result is the opposite of the second bit. Thus,
  7922. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7923. the first argument, as follows, where $\Arg$ is the translation of
  7924. $\Atm$ to x86:
  7925. \[
  7926. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7927. \qquad\Rightarrow\qquad
  7928. \begin{array}{l}
  7929. \key{movq}~ \Arg\key{,} \Var\\
  7930. \key{xorq}~ \key{\$1,} \Var
  7931. \end{array}
  7932. \]
  7933. \newcommand{\GrammarXIf}{
  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 &::=& \key{\%}\itm{bytereg}\\
  7938. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7939. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7940. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7941. \MID \key{set}cc~\Arg
  7942. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7943. &\MID& \key{j}cc~\itm{label} \\
  7944. \end{array}
  7945. }
  7946. \begin{figure}[tp]
  7947. \begin{tcolorbox}[colback=white]
  7948. \[
  7949. \begin{array}{l}
  7950. \gray{\GrammarXInt} \\ \hline
  7951. \GrammarXIf \\
  7952. \begin{array}{lcl}
  7953. \LangXIfM{} &::= & \key{.globl main} \\
  7954. & & \key{main:} \; \Instr\ldots
  7955. \end{array}
  7956. \end{array}
  7957. \]
  7958. \end{tcolorbox}
  7959. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7960. \label{fig:x86-1-concrete}
  7961. \end{figure}
  7962. \newcommand{\ASTXIfRacket}{
  7963. \begin{array}{lcl}
  7964. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7965. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7966. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7967. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7968. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7969. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7970. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7971. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7972. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7973. \end{array}
  7974. }
  7975. \begin{figure}[tp]
  7976. \begin{tcolorbox}[colback=white]
  7977. \small
  7978. {\if\edition\racketEd
  7979. \[\arraycolsep=3pt
  7980. \begin{array}{l}
  7981. \gray{\ASTXIntRacket} \\ \hline
  7982. \ASTXIfRacket \\
  7983. \begin{array}{lcl}
  7984. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7985. \end{array}
  7986. \end{array}
  7987. \]
  7988. \fi}
  7989. %
  7990. {\if\edition\pythonEd\pythonColor
  7991. \[
  7992. \begin{array}{lcl}
  7993. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7994. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7995. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7996. \MID \BYTEREG{\itm{bytereg}} \\
  7997. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7998. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7999. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  8000. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  8001. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  8002. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  8003. \MID \PUSHQ{\Arg}} \\
  8004. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  8005. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8006. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8007. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  8008. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8009. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  8010. \Block &::= & \Instr^{+} \\
  8011. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8012. \end{array}
  8013. \]
  8014. \fi}
  8015. \end{tcolorbox}
  8016. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8017. \label{fig:x86-1}
  8018. \end{figure}
  8019. Next we consider the x86 instructions that are relevant for compiling
  8020. the comparison operations. The \key{cmpq} instruction compares its two
  8021. arguments to determine whether one argument is less than, equal to, or
  8022. greater than the other argument. The \key{cmpq} instruction is unusual
  8023. regarding the order of its arguments and where the result is
  8024. placed. The argument order is backward: if you want to test whether
  8025. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8026. \key{cmpq} is placed in the special EFLAGS register. This register
  8027. cannot be accessed directly, but it can be queried by a number of
  8028. instructions, including the \key{set} instruction. The instruction
  8029. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8030. depending on whether the contents of the EFLAGS register matches the
  8031. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8032. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8033. The \key{set} instruction has a quirk in that its destination argument
  8034. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8035. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8036. register. Thankfully, the \key{movzbq} instruction can be used to
  8037. move from a single-byte register to a normal 64-bit register. The
  8038. abstract syntax for the \code{set} instruction differs from the
  8039. concrete syntax in that it separates the instruction name from the
  8040. condition code.
  8041. \python{The x86 instructions for jumping are relevant to the
  8042. compilation of \key{if} expressions.}
  8043. %
  8044. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8045. counter to the address of the instruction after the specified
  8046. label.}
  8047. %
  8048. \racket{The x86 instruction for conditional jump is relevant to the
  8049. compilation of \key{if} expressions.}
  8050. %
  8051. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8052. counter to point to the instruction after \itm{label}, depending on
  8053. whether the result in the EFLAGS register matches the condition code
  8054. \itm{cc}; otherwise, the jump instruction falls through to the next
  8055. instruction. Like the abstract syntax for \code{set}, the abstract
  8056. syntax for conditional jump separates the instruction name from the
  8057. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8058. corresponds to \code{jle foo}. Because the conditional jump instruction
  8059. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8060. a \key{cmpq} instruction to set the EFLAGS register.
  8061. \section{Shrink the \LangIf{} Language}
  8062. \label{sec:shrink-Lif}
  8063. The \LangIf{} language includes several features that are easily
  8064. expressible with other features. For example, \code{and} and \code{or}
  8065. are expressible using \code{if} as follows.
  8066. \begin{align*}
  8067. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8068. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8069. \end{align*}
  8070. By performing these translations in the front end of the compiler,
  8071. subsequent passes of the compiler do not need to deal with these features,
  8072. thus making the passes shorter.
  8073. On the other hand, translations sometimes reduce the efficiency of the
  8074. generated code by increasing the number of instructions. For example,
  8075. expressing subtraction in terms of negation
  8076. \[
  8077. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8078. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8079. \]
  8080. produces code with two x86 instructions (\code{negq} and \code{addq})
  8081. instead of just one (\code{subq}).
  8082. \begin{exercise}\normalfont\normalsize
  8083. %
  8084. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8085. the language by translating them to \code{if} expressions in \LangIf{}.
  8086. %
  8087. Create four test programs that involve these operators.
  8088. %
  8089. {\if\edition\racketEd
  8090. In the \code{run-tests.rkt} script, add the following entry for
  8091. \code{shrink} to the list of passes (it should be the only pass at
  8092. this point).
  8093. \begin{lstlisting}
  8094. (list "shrink" shrink interp_Lif type-check-Lif)
  8095. \end{lstlisting}
  8096. This instructs \code{interp-tests} to run the interpreter
  8097. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8098. output of \code{shrink}.
  8099. \fi}
  8100. %
  8101. Run the script to test your compiler on all the test programs.
  8102. \end{exercise}
  8103. {\if\edition\racketEd
  8104. \section{Uniquify Variables}
  8105. \label{sec:uniquify-Lif}
  8106. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8107. \code{if} expressions.
  8108. \begin{exercise}\normalfont\normalsize
  8109. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8110. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8111. \begin{lstlisting}
  8112. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8113. \end{lstlisting}
  8114. Run the script to test your compiler.
  8115. \end{exercise}
  8116. \fi}
  8117. \section{Remove Complex Operands}
  8118. \label{sec:remove-complex-opera-Lif}
  8119. The output language of \code{remove\_complex\_operands} is
  8120. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8121. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8122. but the \code{if} expression is not. All three subexpressions of an
  8123. \code{if} are allowed to be complex expressions, but the operands of
  8124. the \code{not} operator and comparison operators must be atomic.
  8125. %
  8126. \python{We add a new language form, the \code{Begin} expression, to aid
  8127. in the translation of \code{if} expressions. When we recursively
  8128. process the two branches of the \code{if}, we generate temporary
  8129. variables and their initializing expressions. However, these
  8130. expressions may contain side effects and should only be executed
  8131. when the condition of the \code{if} is true (for the ``then''
  8132. branch) or false (for the ``else'' branch). The \code{Begin} provides
  8133. a way to initialize the temporary variables within the two branches
  8134. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8135. form execute the statements $ss$ and then returns the result of
  8136. expression $e$.}
  8137. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8138. the new features in \LangIf{}. In recursively processing
  8139. subexpressions, recall that you should invoke \code{rco\_atom} when
  8140. the output needs to be an \Atm{} (as specified in the grammar for
  8141. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8142. \Exp{}. Regarding \code{if}, it is particularly important
  8143. \emph{not} to replace its condition with a temporary variable, because
  8144. that would interfere with the generation of high-quality output in the
  8145. upcoming \code{explicate\_control} pass.
  8146. \newcommand{\LifMonadASTRacket}{
  8147. \begin{array}{rcl}
  8148. \Atm &::=& \BOOL{\itm{bool}}\\
  8149. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8150. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8151. \MID \IF{\Exp}{\Exp}{\Exp}
  8152. \end{array}
  8153. }
  8154. \newcommand{\LifMonadASTPython}{
  8155. \begin{array}{rcl}
  8156. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  8157. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  8158. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  8159. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  8160. \Atm &::=& \BOOL{\itm{bool}}\\
  8161. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8162. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  8163. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8164. \end{array}
  8165. }
  8166. \begin{figure}[tp]
  8167. \centering
  8168. \begin{tcolorbox}[colback=white]
  8169. {\if\edition\racketEd
  8170. \[
  8171. \begin{array}{l}
  8172. \gray{\LvarMonadASTRacket} \\ \hline
  8173. \LifMonadASTRacket \\
  8174. \begin{array}{rcl}
  8175. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8176. \end{array}
  8177. \end{array}
  8178. \]
  8179. \fi}
  8180. {\if\edition\pythonEd\pythonColor
  8181. \[
  8182. \begin{array}{l}
  8183. \gray{\LvarMonadASTPython} \\ \hline
  8184. \LifMonadASTPython \\
  8185. \begin{array}{rcl}
  8186. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8187. \end{array}
  8188. \end{array}
  8189. \]
  8190. \fi}
  8191. \end{tcolorbox}
  8192. \python{\index{subject}{Begin@\texttt{Begin}}}
  8193. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8194. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8195. \label{fig:Lif-anf-syntax}
  8196. \end{figure}
  8197. \begin{exercise}\normalfont\normalsize
  8198. %
  8199. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8200. and \code{rco\_exp} functions in \code{compiler.rkt}.
  8201. %
  8202. Create three new \LangIf{} programs that exercise the interesting
  8203. code in this pass.
  8204. %
  8205. {\if\edition\racketEd
  8206. In the \code{run-tests.rkt} script, add the following entry to the
  8207. list of \code{passes} and then run the script to test your compiler.
  8208. \begin{lstlisting}
  8209. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8210. \end{lstlisting}
  8211. \fi}
  8212. \end{exercise}
  8213. \section{Explicate Control}
  8214. \label{sec:explicate-control-Lif}
  8215. \racket{Recall that the purpose of \code{explicate\_control} is to
  8216. make the order of evaluation explicit in the syntax of the program.
  8217. With the addition of \key{if}, this becomes more interesting.}
  8218. %
  8219. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8220. %
  8221. The main challenge to overcome is that the condition of an \key{if}
  8222. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8223. condition must be a comparison.
  8224. As a motivating example, consider the following program that has an
  8225. \key{if} expression nested in the condition of another \key{if}:%
  8226. \python{\footnote{Programmers rarely write nested \code{if}
  8227. expressions, but it is not uncommon for the condition of an
  8228. \code{if} statement to be a call of a function that also contains an
  8229. \code{if} statement. When such a function is inlined, the result is
  8230. a nested \code{if} that requires the techniques discussed in this
  8231. section.}}
  8232. % cond_test_41.rkt, if_lt_eq.py
  8233. \begin{center}
  8234. \begin{minipage}{0.96\textwidth}
  8235. {\if\edition\racketEd
  8236. \begin{lstlisting}
  8237. (let ([x (read)])
  8238. (let ([y (read)])
  8239. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8240. (+ y 2)
  8241. (+ y 10))))
  8242. \end{lstlisting}
  8243. \fi}
  8244. {\if\edition\pythonEd\pythonColor
  8245. \begin{lstlisting}
  8246. x = input_int()
  8247. y = input_int()
  8248. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8249. \end{lstlisting}
  8250. \fi}
  8251. \end{minipage}
  8252. \end{center}
  8253. %
  8254. The naive way to compile \key{if} and the comparison operations would
  8255. be to handle each of them in isolation, regardless of their context.
  8256. Each comparison would be translated into a \key{cmpq} instruction
  8257. followed by several instructions to move the result from the EFLAGS
  8258. register into a general purpose register or stack location. Each
  8259. \key{if} would be translated into a \key{cmpq} instruction followed by
  8260. a conditional jump. The generated code for the inner \key{if} in this
  8261. example would be as follows:
  8262. \begin{center}
  8263. \begin{minipage}{0.96\textwidth}
  8264. \begin{lstlisting}
  8265. cmpq $1, x
  8266. setl %al
  8267. movzbq %al, tmp
  8268. cmpq $1, tmp
  8269. je then_branch_1
  8270. jmp else_branch_1
  8271. \end{lstlisting}
  8272. \end{minipage}
  8273. \end{center}
  8274. Notice that the three instructions starting with \code{setl} are
  8275. redundant; the conditional jump could come immediately after the first
  8276. \code{cmpq}.
  8277. Our goal is to compile \key{if} expressions so that the relevant
  8278. comparison instruction appears directly before the conditional jump.
  8279. For example, we want to generate the following code for the inner
  8280. \code{if}:
  8281. \begin{center}
  8282. \begin{minipage}{0.96\textwidth}
  8283. \begin{lstlisting}
  8284. cmpq $1, x
  8285. jl then_branch_1
  8286. jmp else_branch_1
  8287. \end{lstlisting}
  8288. \end{minipage}
  8289. \end{center}
  8290. One way to achieve this goal is to reorganize the code at the level of
  8291. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8292. the following code:
  8293. \begin{center}
  8294. \begin{minipage}{0.96\textwidth}
  8295. {\if\edition\racketEd
  8296. \begin{lstlisting}
  8297. (let ([x (read)])
  8298. (let ([y (read)])
  8299. (if (< x 1)
  8300. (if (eq? x 0)
  8301. (+ y 2)
  8302. (+ y 10))
  8303. (if (eq? x 2)
  8304. (+ y 2)
  8305. (+ y 10)))))
  8306. \end{lstlisting}
  8307. \fi}
  8308. {\if\edition\pythonEd\pythonColor
  8309. \begin{lstlisting}
  8310. x = input_int()
  8311. y = input_int()
  8312. print(((y + 2) if x == 0 else (y + 10)) \
  8313. if (x < 1) \
  8314. else ((y + 2) if (x == 2) else (y + 10)))
  8315. \end{lstlisting}
  8316. \fi}
  8317. \end{minipage}
  8318. \end{center}
  8319. Unfortunately, this approach duplicates the two branches from the
  8320. outer \code{if}, and a compiler must never duplicate code! After all,
  8321. the two branches could be very large expressions.
  8322. How can we apply this transformation without duplicating code? In
  8323. other words, how can two different parts of a program refer to one
  8324. piece of code?
  8325. %
  8326. The answer is that we must move away from abstract syntax \emph{trees}
  8327. and instead use \emph{graphs}.
  8328. %
  8329. At the level of x86 assembly, this is straightforward because we can
  8330. label the code for each branch and insert jumps in all the places that
  8331. need to execute the branch. In this way, jump instructions are edges
  8332. in the graph and the basic blocks are the nodes.
  8333. %
  8334. Likewise, our language \LangCIf{} provides the ability to label a
  8335. sequence of statements and to jump to a label via \code{goto}.
  8336. As a preview of what \code{explicate\_control} will do,
  8337. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8338. \code{explicate\_control} on this example. Note how the condition of
  8339. every \code{if} is a comparison operation and that we have not
  8340. duplicated any code but instead have used labels and \code{goto} to
  8341. enable sharing of code.
  8342. \begin{figure}[tbp]
  8343. \begin{tcolorbox}[colback=white]
  8344. {\if\edition\racketEd
  8345. \begin{tabular}{lll}
  8346. \begin{minipage}{0.4\textwidth}
  8347. % cond_test_41.rkt
  8348. \begin{lstlisting}
  8349. (let ([x (read)])
  8350. (let ([y (read)])
  8351. (if (if (< x 1)
  8352. (eq? x 0)
  8353. (eq? x 2))
  8354. (+ y 2)
  8355. (+ y 10))))
  8356. \end{lstlisting}
  8357. \end{minipage}
  8358. &
  8359. $\Rightarrow$
  8360. &
  8361. \begin{minipage}{0.55\textwidth}
  8362. \begin{lstlisting}
  8363. start:
  8364. x = (read);
  8365. y = (read);
  8366. if (< x 1)
  8367. goto block_4;
  8368. else
  8369. goto block_5;
  8370. block_4:
  8371. if (eq? x 0)
  8372. goto block_2;
  8373. else
  8374. goto block_3;
  8375. block_5:
  8376. if (eq? x 2)
  8377. goto block_2;
  8378. else
  8379. goto block_3;
  8380. block_2:
  8381. return (+ y 2);
  8382. block_3:
  8383. return (+ y 10);
  8384. \end{lstlisting}
  8385. \end{minipage}
  8386. \end{tabular}
  8387. \fi}
  8388. {\if\edition\pythonEd\pythonColor
  8389. \begin{tabular}{lll}
  8390. \begin{minipage}{0.4\textwidth}
  8391. % cond_test_41.rkt
  8392. \begin{lstlisting}
  8393. x = input_int()
  8394. y = input_int()
  8395. print(y + 2 \
  8396. if (x == 0 \
  8397. if x < 1 \
  8398. else x == 2) \
  8399. else y + 10)
  8400. \end{lstlisting}
  8401. \end{minipage}
  8402. &
  8403. $\Rightarrow$
  8404. &
  8405. \begin{minipage}{0.55\textwidth}
  8406. \begin{lstlisting}
  8407. start:
  8408. x = input_int()
  8409. y = input_int()
  8410. if x < 1:
  8411. goto block_8
  8412. else:
  8413. goto block_9
  8414. block_8:
  8415. if x == 0:
  8416. goto block_4
  8417. else:
  8418. goto block_5
  8419. block_9:
  8420. if x == 2:
  8421. goto block_6
  8422. else:
  8423. goto block_7
  8424. block_4:
  8425. goto block_2
  8426. block_5:
  8427. goto block_3
  8428. block_6:
  8429. goto block_2
  8430. block_7:
  8431. goto block_3
  8432. block_2:
  8433. tmp_0 = y + 2
  8434. goto block_1
  8435. block_3:
  8436. tmp_0 = y + 10
  8437. goto block_1
  8438. block_1:
  8439. print(tmp_0)
  8440. return 0
  8441. \end{lstlisting}
  8442. \end{minipage}
  8443. \end{tabular}
  8444. \fi}
  8445. \end{tcolorbox}
  8446. \caption{Translation from \LangIf{} to \LangCIf{}
  8447. via the \code{explicate\_control}.}
  8448. \label{fig:explicate-control-s1-38}
  8449. \end{figure}
  8450. {\if\edition\racketEd
  8451. %
  8452. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8453. \code{explicate\_control} for \LangVar{} using two recursive
  8454. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8455. former function translates expressions in tail position, whereas the
  8456. latter function translates expressions on the right-hand side of a
  8457. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8458. have a new kind of position to deal with: the predicate position of
  8459. the \key{if}. We need another function, \code{explicate\_pred}, that
  8460. decides how to compile an \key{if} by analyzing its condition. So,
  8461. \code{explicate\_pred} takes an \LangIf{} expression and two
  8462. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8463. and outputs a tail. In the following paragraphs we discuss specific
  8464. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8465. \code{explicate\_pred} functions.
  8466. %
  8467. \fi}
  8468. %
  8469. {\if\edition\pythonEd\pythonColor
  8470. %
  8471. We recommend implementing \code{explicate\_control} using the
  8472. following four auxiliary functions.
  8473. \begin{description}
  8474. \item[\code{explicate\_effect}] generates code for expressions as
  8475. statements, so their result is ignored and only their side effects
  8476. matter.
  8477. \item[\code{explicate\_assign}] generates code for expressions
  8478. on the right-hand side of an assignment.
  8479. \item[\code{explicate\_pred}] generates code for an \code{if}
  8480. expression or statement by analyzing the condition expression.
  8481. \item[\code{explicate\_stmt}] generates code for statements.
  8482. \end{description}
  8483. These four functions should build the dictionary of basic blocks. The
  8484. following auxiliary function can be used to create a new basic block
  8485. from a list of statements. It returns a \code{goto} statement that
  8486. jumps to the new basic block.
  8487. \begin{center}
  8488. \begin{minipage}{\textwidth}
  8489. \begin{lstlisting}
  8490. def create_block(stmts, basic_blocks):
  8491. label = label_name(generate_name('block'))
  8492. basic_blocks[label] = stmts
  8493. return Goto(label)
  8494. \end{lstlisting}
  8495. \end{minipage}
  8496. \end{center}
  8497. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8498. \code{explicate\_control} pass.
  8499. The \code{explicate\_effect} function has three parameters: 1) the
  8500. expression to be compiled, 2) the already-compiled code for this
  8501. expression's \emph{continuation}, that is, the list of statements that
  8502. should execute after this expression, and 3) the dictionary of
  8503. generated basic blocks. The \code{explicate\_effect} function returns
  8504. a list of \LangCIf{} statements and it may add to the dictionary of
  8505. basic blocks.
  8506. %
  8507. Let's consider a few of the cases for the expression to be compiled.
  8508. If the expression to be compiled is a constant, then it can be
  8509. discarded because it has no side effects. If it's a \CREAD{}, then it
  8510. has a side-effect and should be preserved. So the expression should be
  8511. translated into a statement using the \code{Expr} AST class. If the
  8512. expression to be compiled is an \code{if} expression, we translate the
  8513. two branches using \code{explicate\_effect} and then translate the
  8514. condition expression using \code{explicate\_pred}, which generates
  8515. code for the entire \code{if}.
  8516. The \code{explicate\_assign} function has four parameters: 1) the
  8517. right-hand side of the assignment, 2) the left-hand side of the
  8518. assignment (the variable), 3) the continuation, and 4) the dictionary
  8519. of basic blocks. The \code{explicate\_assign} function returns a list
  8520. of \LangCIf{} statements and it may add to the dictionary of basic
  8521. blocks.
  8522. When the right-hand side is an \code{if} expression, there is some
  8523. work to do. In particular, the two branches should be translated using
  8524. \code{explicate\_assign} and the condition expression should be
  8525. translated using \code{explicate\_pred}. Otherwise we can simply
  8526. generate an assignment statement, with the given left and right-hand
  8527. sides, concatenated with its continuation.
  8528. \begin{figure}[tbp]
  8529. \begin{tcolorbox}[colback=white]
  8530. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8531. def explicate_effect(e, cont, basic_blocks):
  8532. match e:
  8533. case IfExp(test, body, orelse):
  8534. ...
  8535. case Call(func, args):
  8536. ...
  8537. case Begin(body, result):
  8538. ...
  8539. case _:
  8540. ...
  8541. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8542. match rhs:
  8543. case IfExp(test, body, orelse):
  8544. ...
  8545. case Begin(body, result):
  8546. ...
  8547. case _:
  8548. return [Assign([lhs], rhs)] + cont
  8549. def explicate_pred(cnd, thn, els, basic_blocks):
  8550. match cnd:
  8551. case Compare(left, [op], [right]):
  8552. goto_thn = create_block(thn, basic_blocks)
  8553. goto_els = create_block(els, basic_blocks)
  8554. return [If(cnd, [goto_thn], [goto_els])]
  8555. case Constant(True):
  8556. return thn;
  8557. case Constant(False):
  8558. return els;
  8559. case UnaryOp(Not(), operand):
  8560. ...
  8561. case IfExp(test, body, orelse):
  8562. ...
  8563. case Begin(body, result):
  8564. ...
  8565. case _:
  8566. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8567. [create_block(els, basic_blocks)],
  8568. [create_block(thn, basic_blocks)])]
  8569. def explicate_stmt(s, cont, basic_blocks):
  8570. match s:
  8571. case Assign([lhs], rhs):
  8572. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8573. case Expr(value):
  8574. return explicate_effect(value, cont, basic_blocks)
  8575. case If(test, body, orelse):
  8576. ...
  8577. def explicate_control(p):
  8578. match p:
  8579. case Module(body):
  8580. new_body = [Return(Constant(0))]
  8581. basic_blocks = {}
  8582. for s in reversed(body):
  8583. new_body = explicate_stmt(s, new_body, basic_blocks)
  8584. basic_blocks[label_name('start')] = new_body
  8585. return CProgram(basic_blocks)
  8586. \end{lstlisting}
  8587. \end{tcolorbox}
  8588. \caption{Skeleton for the \code{explicate\_control} pass.}
  8589. \label{fig:explicate-control-Lif}
  8590. \end{figure}
  8591. \fi}
  8592. {\if\edition\racketEd
  8593. \subsection{Explicate Tail and Assign}
  8594. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8595. additional cases for Boolean constants and \key{if}. The cases for
  8596. \code{if} should recursively compile the two branches using either
  8597. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8598. cases should then invoke \code{explicate\_pred} on the condition
  8599. expression, passing in the generated code for the two branches. For
  8600. example, consider the following program with an \code{if} in tail
  8601. position.
  8602. % cond_test_6.rkt
  8603. \begin{lstlisting}
  8604. (let ([x (read)])
  8605. (if (eq? x 0) 42 777))
  8606. \end{lstlisting}
  8607. The two branches are recursively compiled to return statements. We
  8608. then delegate to \code{explicate\_pred}, passing the condition
  8609. \code{(eq? x 0)} and the two return statements. We return to this
  8610. example shortly when we discuss \code{explicate\_pred}.
  8611. Next let us consider a program with an \code{if} on the right-hand
  8612. side of a \code{let}.
  8613. \begin{lstlisting}
  8614. (let ([y (read)])
  8615. (let ([x (if (eq? y 0) 40 777)])
  8616. (+ x 2)))
  8617. \end{lstlisting}
  8618. Note that the body of the inner \code{let} will have already been
  8619. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8620. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8621. to recursively process both branches of the \code{if}, and we do not
  8622. want to duplicate code, so we generate the following block using an
  8623. auxiliary function named \code{create\_block}, discussed in the next
  8624. section.
  8625. \begin{lstlisting}
  8626. block_6:
  8627. return (+ x 2)
  8628. \end{lstlisting}
  8629. We then use \code{goto block\_6;} as the \code{cont} argument for
  8630. compiling the branches. So the two branches compile to
  8631. \begin{center}
  8632. \begin{minipage}{0.2\textwidth}
  8633. \begin{lstlisting}
  8634. x = 40;
  8635. goto block_6;
  8636. \end{lstlisting}
  8637. \end{minipage}
  8638. \hspace{0.5in} and \hspace{0.5in}
  8639. \begin{minipage}{0.2\textwidth}
  8640. \begin{lstlisting}
  8641. x = 777;
  8642. goto block_6;
  8643. \end{lstlisting}
  8644. \end{minipage}
  8645. \end{center}
  8646. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8647. \code{(eq? y 0)} and the previously presented code for the branches.
  8648. \subsection{Create Block}
  8649. We recommend implementing the \code{create\_block} auxiliary function
  8650. as follows, using a global variable \code{basic-blocks} to store a
  8651. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8652. that \code{create\_block} generates a new label and then associates
  8653. the given \code{tail} with the new label in the \code{basic-blocks}
  8654. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8655. new label. However, if the given \code{tail} is already a \code{Goto},
  8656. then there is no need to generate a new label and entry in
  8657. \code{basic-blocks}; we can simply return that \code{Goto}.
  8658. %
  8659. \begin{lstlisting}
  8660. (define (create_block tail)
  8661. (match tail
  8662. [(Goto label) (Goto label)]
  8663. [else
  8664. (let ([label (gensym 'block)])
  8665. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8666. (Goto label))]))
  8667. \end{lstlisting}
  8668. \fi}
  8669. {\if\edition\racketEd
  8670. \subsection{Explicate Predicate}
  8671. The skeleton for the \code{explicate\_pred} function is given in
  8672. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8673. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8674. the code generated by explicate for the \emph{then} branch; and (3)
  8675. \code{els}, the code generated by explicate for the \emph{else}
  8676. branch. The \code{explicate\_pred} function should match on
  8677. \code{cnd} with a case for every kind of expression that can have type
  8678. \BOOLTY{}.
  8679. \begin{figure}[tbp]
  8680. \begin{tcolorbox}[colback=white]
  8681. \begin{lstlisting}
  8682. (define (explicate_pred cnd thn els)
  8683. (match cnd
  8684. [(Var x) ___]
  8685. [(Let x rhs body) ___]
  8686. [(Prim 'not (list e)) ___]
  8687. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8688. (IfStmt (Prim op es) (create_block thn)
  8689. (create_block els))]
  8690. [(Bool b) (if b thn els)]
  8691. [(If cnd^ thn^ els^) ___]
  8692. [else (error "explicate_pred unhandled case" cnd)]))
  8693. \end{lstlisting}
  8694. \end{tcolorbox}
  8695. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8696. \label{fig:explicate-pred}
  8697. \end{figure}
  8698. \fi}
  8699. %
  8700. {\if\edition\pythonEd\pythonColor
  8701. The \code{explicate\_pred} function has four parameters: 1) the
  8702. condition expression, 2) the generated statements for the ``then''
  8703. branch, 3) the generated statements for the ``else'' branch, and 4)
  8704. the dictionary of basic blocks. The \code{explicate\_pred} function
  8705. returns a list of \LangCIf{} statements and it may add to the
  8706. dictionary of basic blocks.
  8707. \fi}
  8708. Consider the case for comparison operators. We translate the
  8709. comparison to an \code{if} statement whose branches are \code{goto}
  8710. statements created by applying \code{create\_block} to the code
  8711. generated for the \code{thn} and \code{els} branches. Let us
  8712. illustrate this translation by returning to the program with an
  8713. \code{if} expression in tail position, shown next. We invoke
  8714. \code{explicate\_pred} on its condition
  8715. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8716. %
  8717. {\if\edition\racketEd
  8718. \begin{lstlisting}
  8719. (let ([x (read)])
  8720. (if (eq? x 0) 42 777))
  8721. \end{lstlisting}
  8722. \fi}
  8723. %
  8724. {\if\edition\pythonEd\pythonColor
  8725. \begin{lstlisting}
  8726. x = input_int()
  8727. 42 if x == 0 else 777
  8728. \end{lstlisting}
  8729. \fi}
  8730. %
  8731. \noindent The two branches \code{42} and \code{777} were already
  8732. compiled to \code{return} statements, from which we now create the
  8733. following blocks:
  8734. %
  8735. \begin{center}
  8736. \begin{minipage}{\textwidth}
  8737. \begin{lstlisting}
  8738. block_1:
  8739. return 42;
  8740. block_2:
  8741. return 777;
  8742. \end{lstlisting}
  8743. \end{minipage}
  8744. \end{center}
  8745. %
  8746. After that, \code{explicate\_pred} compiles the comparison
  8747. \racket{\code{(eq? x 0)}}
  8748. \python{\code{x == 0}}
  8749. to the following \code{if} statement:
  8750. %
  8751. {\if\edition\racketEd
  8752. \begin{center}
  8753. \begin{minipage}{\textwidth}
  8754. \begin{lstlisting}
  8755. if (eq? x 0)
  8756. goto block_1;
  8757. else
  8758. goto block_2;
  8759. \end{lstlisting}
  8760. \end{minipage}
  8761. \end{center}
  8762. \fi}
  8763. {\if\edition\pythonEd\pythonColor
  8764. \begin{center}
  8765. \begin{minipage}{\textwidth}
  8766. \begin{lstlisting}
  8767. if x == 0:
  8768. goto block_1;
  8769. else
  8770. goto block_2;
  8771. \end{lstlisting}
  8772. \end{minipage}
  8773. \end{center}
  8774. \fi}
  8775. Next consider the case for Boolean constants. We perform a kind of
  8776. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8777. either the \code{thn} or \code{els} branch, depending on whether the
  8778. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8779. following program:
  8780. {\if\edition\racketEd
  8781. \begin{lstlisting}
  8782. (if #t 42 777)
  8783. \end{lstlisting}
  8784. \fi}
  8785. {\if\edition\pythonEd\pythonColor
  8786. \begin{lstlisting}
  8787. 42 if True else 777
  8788. \end{lstlisting}
  8789. \fi}
  8790. %
  8791. \noindent Again, the two branches \code{42} and \code{777} were
  8792. compiled to \code{return} statements, so \code{explicate\_pred}
  8793. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8794. code for the \emph{then} branch.
  8795. \begin{lstlisting}
  8796. return 42;
  8797. \end{lstlisting}
  8798. This case demonstrates that we sometimes discard the \code{thn} or
  8799. \code{els} blocks that are input to \code{explicate\_pred}.
  8800. The case for \key{if} expressions in \code{explicate\_pred} is
  8801. particularly illuminating because it deals with the challenges
  8802. discussed previously regarding nested \key{if} expressions
  8803. (figure~\ref{fig:explicate-control-s1-38}). The
  8804. \racket{\lstinline{thn^}}\python{\code{body}} and
  8805. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8806. \key{if} inherit their context from the current one, that is,
  8807. predicate context. So, you should recursively apply
  8808. \code{explicate\_pred} to the
  8809. \racket{\lstinline{thn^}}\python{\code{body}} and
  8810. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8811. those recursive calls, pass \code{thn} and \code{els} as the extra
  8812. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8813. inside each recursive call. As discussed previously, to avoid
  8814. duplicating code, we need to add them to the dictionary of basic
  8815. blocks so that we can instead refer to them by name and execute them
  8816. with a \key{goto}.
  8817. {\if\edition\pythonEd\pythonColor
  8818. %
  8819. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8820. three parameters: 1) the statement to be compiled, 2) the code for its
  8821. continuation, and 3) the dictionary of basic blocks. The
  8822. \code{explicate\_stmt} returns a list of statements and it may add to
  8823. the dictionary of basic blocks. The cases for assignment and an
  8824. expression-statement are given in full in the skeleton code: they
  8825. simply dispatch to \code{explicate\_assign} and
  8826. \code{explicate\_effect}, respectively. The case for \code{if}
  8827. statements is not given, and is similar to the case for \code{if}
  8828. expressions.
  8829. The \code{explicate\_control} function itself is given in
  8830. figure~\ref{fig:explicate-control-Lif}. It applies
  8831. \code{explicate\_stmt} to each statement in the program, from back to
  8832. front. Thus, the result so-far, stored in \code{new\_body}, can be
  8833. used as the continuation parameter in the next call to
  8834. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8835. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8836. the dictionary of basic blocks, labeling it as the ``start'' block.
  8837. %
  8838. \fi}
  8839. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8840. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8841. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8842. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8843. %% results from the two recursive calls. We complete the case for
  8844. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8845. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8846. %% the result $B_5$.
  8847. %% \[
  8848. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8849. %% \quad\Rightarrow\quad
  8850. %% B_5
  8851. %% \]
  8852. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8853. %% inherit the current context, so they are in tail position. Thus, the
  8854. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8855. %% \code{explicate\_tail}.
  8856. %% %
  8857. %% We need to pass $B_0$ as the accumulator argument for both of these
  8858. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8859. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8860. %% to the control-flow graph and obtain a promised goto $G_0$.
  8861. %% %
  8862. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8863. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8864. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8865. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8866. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8867. %% \[
  8868. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8869. %% \]
  8870. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8871. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8872. %% should not be confused with the labels for the blocks that appear in
  8873. %% the generated code. We initially construct unlabeled blocks; we only
  8874. %% attach labels to blocks when we add them to the control-flow graph, as
  8875. %% we see in the next case.
  8876. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8877. %% function. The context of the \key{if} is an assignment to some
  8878. %% variable $x$ and then the control continues to some promised block
  8879. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8880. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8881. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8882. %% branches of the \key{if} inherit the current context, so they are in
  8883. %% assignment positions. Let $B_2$ be the result of applying
  8884. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8885. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8886. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8887. %% the result of applying \code{explicate\_pred} to the predicate
  8888. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8889. %% translates to the promise $B_4$.
  8890. %% \[
  8891. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8892. %% \]
  8893. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8894. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8895. \code{remove\_complex\_operands} pass and then the
  8896. \code{explicate\_control} pass on the example program. We walk through
  8897. the output program.
  8898. %
  8899. Following the order of evaluation in the output of
  8900. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8901. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8902. in the predicate of the inner \key{if}. In the output of
  8903. \code{explicate\_control}, in the
  8904. block labeled \code{start}, two assignment statements are followed by an
  8905. \code{if} statement that branches to \code{block\_4} or
  8906. \code{block\_5}. The blocks associated with those labels contain the
  8907. translations of the code
  8908. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8909. and
  8910. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8911. respectively. In particular, we start \code{block\_4} with the
  8912. comparison
  8913. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8914. and then branch to \code{block\_2} or \code{block\_3},
  8915. which correspond to the two branches of the outer \key{if}, that is,
  8916. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8917. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8918. %
  8919. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8920. %
  8921. \python{The \code{block\_1} corresponds to the \code{print} statement
  8922. at the end of the program.}
  8923. {\if\edition\racketEd
  8924. \subsection{Interactions between Explicate and Shrink}
  8925. The way in which the \code{shrink} pass transforms logical operations
  8926. such as \code{and} and \code{or} can impact the quality of code
  8927. generated by \code{explicate\_control}. For example, consider the
  8928. following program:
  8929. % cond_test_21.rkt, and_eq_input.py
  8930. \begin{lstlisting}
  8931. (if (and (eq? (read) 0) (eq? (read) 1))
  8932. 0
  8933. 42)
  8934. \end{lstlisting}
  8935. The \code{and} operation should transform into something that the
  8936. \code{explicate\_pred} function can analyze and descend through to
  8937. reach the underlying \code{eq?} conditions. Ideally, for this program
  8938. your \code{explicate\_control} pass should generate code similar to
  8939. the following:
  8940. \begin{center}
  8941. \begin{minipage}{\textwidth}
  8942. \begin{lstlisting}
  8943. start:
  8944. tmp1 = (read);
  8945. if (eq? tmp1 0) goto block40;
  8946. else goto block39;
  8947. block40:
  8948. tmp2 = (read);
  8949. if (eq? tmp2 1) goto block38;
  8950. else goto block39;
  8951. block38:
  8952. return 0;
  8953. block39:
  8954. return 42;
  8955. \end{lstlisting}
  8956. \end{minipage}
  8957. \end{center}
  8958. \fi}
  8959. \begin{exercise}\normalfont\normalsize
  8960. \racket{
  8961. Implement the pass \code{explicate\_control} by adding the cases for
  8962. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8963. \code{explicate\_assign} functions. Implement the auxiliary function
  8964. \code{explicate\_pred} for predicate contexts.}
  8965. \python{Implement \code{explicate\_control} pass with its
  8966. four auxiliary functions.}
  8967. %
  8968. Create test cases that exercise all the new cases in the code for
  8969. this pass.
  8970. %
  8971. {\if\edition\racketEd
  8972. Add the following entry to the list of \code{passes} in
  8973. \code{run-tests.rkt}:
  8974. \begin{lstlisting}
  8975. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8976. \end{lstlisting}
  8977. and then run \code{run-tests.rkt} to test your compiler.
  8978. \fi}
  8979. \end{exercise}
  8980. \section{Select Instructions}
  8981. \label{sec:select-Lif}
  8982. \index{subject}{select instructions}
  8983. The \code{select\_instructions} pass translates \LangCIf{} to
  8984. \LangXIfVar{}.
  8985. %
  8986. \racket{Recall that we implement this pass using three auxiliary
  8987. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8988. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8989. %
  8990. \racket{For $\Atm$, we have new cases for the Booleans.}
  8991. %
  8992. \python{We begin with the Boolean constants.}
  8993. We take the usual approach of encoding them as integers.
  8994. \[
  8995. \TRUE{} \quad\Rightarrow\quad \key{1}
  8996. \qquad\qquad
  8997. \FALSE{} \quad\Rightarrow\quad \key{0}
  8998. \]
  8999. For translating statements, we discuss some of the cases. The
  9000. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9001. discussed at the beginning of this section. Given an assignment, if
  9002. the left-hand-side variable is the same as the argument of \code{not},
  9003. then just the \code{xorq} instruction suffices.
  9004. \[
  9005. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9006. \quad\Rightarrow\quad
  9007. \key{xorq}~\key{\$}1\key{,}~\Var
  9008. \]
  9009. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9010. semantics of x86. In the following translation, let $\Arg$ be the
  9011. result of translating $\Atm$ to x86.
  9012. \[
  9013. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9014. \quad\Rightarrow\quad
  9015. \begin{array}{l}
  9016. \key{movq}~\Arg\key{,}~\Var\\
  9017. \key{xorq}~\key{\$}1\key{,}~\Var
  9018. \end{array}
  9019. \]
  9020. Next consider the cases for equality comparisons. Translating this
  9021. operation to x86 is slightly involved due to the unusual nature of the
  9022. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9023. We recommend translating an assignment with an equality on the
  9024. right-hand side into a sequence of three instructions. \\
  9025. \begin{tabular}{lll}
  9026. \begin{minipage}{0.4\textwidth}
  9027. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9028. \end{minipage}
  9029. &
  9030. $\Rightarrow$
  9031. &
  9032. \begin{minipage}{0.4\textwidth}
  9033. \begin{lstlisting}
  9034. cmpq |$\Arg_2$|, |$\Arg_1$|
  9035. sete %al
  9036. movzbq %al, |$\Var$|
  9037. \end{lstlisting}
  9038. \end{minipage}
  9039. \end{tabular} \\
  9040. The translations for the other comparison operators are similar to
  9041. this but use different condition codes for the \code{set} instruction.
  9042. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9043. \key{goto} and \key{if} statements. Both are straightforward to
  9044. translate to x86.}
  9045. %
  9046. A \key{goto} statement becomes a jump instruction.
  9047. \[
  9048. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9049. \]
  9050. %
  9051. An \key{if} statement becomes a compare instruction followed by a
  9052. conditional jump (for the \emph{then} branch), and the fall-through is to
  9053. a regular jump (for the \emph{else} branch).\\
  9054. \begin{tabular}{lll}
  9055. \begin{minipage}{0.4\textwidth}
  9056. \begin{lstlisting}
  9057. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9058. goto |$\ell_1$||$\racket{\key{;}}$|
  9059. else|$\python{\key{:}}$|
  9060. goto |$\ell_2$||$\racket{\key{;}}$|
  9061. \end{lstlisting}
  9062. \end{minipage}
  9063. &
  9064. $\Rightarrow$
  9065. &
  9066. \begin{minipage}{0.4\textwidth}
  9067. \begin{lstlisting}
  9068. cmpq |$\Arg_2$|, |$\Arg_1$|
  9069. je |$\ell_1$|
  9070. jmp |$\ell_2$|
  9071. \end{lstlisting}
  9072. \end{minipage}
  9073. \end{tabular} \\
  9074. Again, the translations for the other comparison operators are similar to this
  9075. but use different condition codes for the conditional jump instruction.
  9076. \python{Regarding the \key{return} statement, we recommend treating it
  9077. as an assignment to the \key{rax} register followed by a jump to the
  9078. conclusion of the \code{main} function.}
  9079. \begin{exercise}\normalfont\normalsize
  9080. Expand your \code{select\_instructions} pass to handle the new
  9081. features of the \LangCIf{} language.
  9082. %
  9083. {\if\edition\racketEd
  9084. Add the following entry to the list of \code{passes} in
  9085. \code{run-tests.rkt}
  9086. \begin{lstlisting}
  9087. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9088. \end{lstlisting}
  9089. \fi}
  9090. %
  9091. Run the script to test your compiler on all the test programs.
  9092. \end{exercise}
  9093. \section{Register Allocation}
  9094. \label{sec:register-allocation-Lif}
  9095. \index{subject}{register allocation}
  9096. The changes required for compiling \LangIf{} affect liveness analysis,
  9097. building the interference graph, and assigning homes, but the graph
  9098. coloring algorithm itself does not change.
  9099. \subsection{Liveness Analysis}
  9100. \label{sec:liveness-analysis-Lif}
  9101. \index{subject}{liveness analysis}
  9102. Recall that for \LangVar{} we implemented liveness analysis for a
  9103. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9104. the addition of \key{if} expressions to \LangIf{},
  9105. \code{explicate\_control} produces many basic blocks.
  9106. %% We recommend that you create a new auxiliary function named
  9107. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9108. %% control-flow graph.
  9109. The first question is, in what order should we process the basic blocks?
  9110. Recall that to perform liveness analysis on a basic block we need to
  9111. know the live-after set for the last instruction in the block. If a
  9112. basic block has no successors (i.e., contains no jumps to other
  9113. blocks), then it has an empty live-after set and we can immediately
  9114. apply liveness analysis to it. If a basic block has some successors,
  9115. then we need to complete liveness analysis on those blocks
  9116. first. These ordering constraints are the reverse of a
  9117. \emph{topological order}\index{subject}{topological order} on a graph
  9118. representation of the program. In particular, the \emph{control flow
  9119. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9120. of a program has a node for each basic block and an edge for each jump
  9121. from one block to another. It is straightforward to generate a CFG
  9122. from the dictionary of basic blocks. One then transposes the CFG and
  9123. applies the topological sort algorithm.
  9124. %
  9125. %
  9126. \racket{We recommend using the \code{tsort} and \code{transpose}
  9127. functions of the Racket \code{graph} package to accomplish this.}
  9128. %
  9129. \python{We provide implementations of \code{topological\_sort} and
  9130. \code{transpose} in the file \code{graph.py} of the support code.}
  9131. %
  9132. As an aside, a topological ordering is only guaranteed to exist if the
  9133. graph does not contain any cycles. This is the case for the
  9134. control-flow graphs that we generate from \LangIf{} programs.
  9135. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9136. and learn how to handle cycles in the control-flow graph.
  9137. \racket{You need to construct a directed graph to represent the
  9138. control-flow graph. Do not use the \code{directed-graph} of the
  9139. \code{graph} package because that allows at most one edge
  9140. between each pair of vertices, whereas a control-flow graph may have
  9141. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9142. file in the support code implements a graph representation that
  9143. allows multiple edges between a pair of vertices.}
  9144. {\if\edition\racketEd
  9145. The next question is how to analyze jump instructions. Recall that in
  9146. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9147. \code{label->live} that maps each label to the set of live locations
  9148. at the beginning of its block. We use \code{label->live} to determine
  9149. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9150. that we have many basic blocks, \code{label->live} needs to be updated
  9151. as we process the blocks. In particular, after performing liveness
  9152. analysis on a block, we take the live-before set of its first
  9153. instruction and associate that with the block's label in the
  9154. \code{label->live} alist.
  9155. \fi}
  9156. %
  9157. {\if\edition\pythonEd\pythonColor
  9158. %
  9159. The next question is how to analyze jump instructions. The locations
  9160. that are live before a \code{jmp} should be the locations in
  9161. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9162. maintaining a dictionary named \code{live\_before\_block} that maps each
  9163. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9164. block. After performing liveness analysis on each block, we take the
  9165. live-before set of its first instruction and associate that with the
  9166. block's label in the \code{live\_before\_block} dictionary.
  9167. %
  9168. \fi}
  9169. In \LangXIfVar{} we also have the conditional jump
  9170. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9171. this instruction is particularly interesting because during
  9172. compilation, we do not know which way a conditional jump will go. Thus
  9173. we do not know whether to use the live-before set for the block
  9174. associated with the $\itm{label}$ or the live-before set for the
  9175. following instruction. However, there is no harm to the correctness
  9176. of the generated code if we classify more locations as live than the
  9177. ones that are truly live during one particular execution of the
  9178. instruction. Thus, we can take the union of the live-before sets from
  9179. the following instruction and from the mapping for $\itm{label}$ in
  9180. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9181. The auxiliary functions for computing the variables in an
  9182. instruction's argument and for computing the variables read-from ($R$)
  9183. or written-to ($W$) by an instruction need to be updated to handle the
  9184. new kinds of arguments and instructions in \LangXIfVar{}.
  9185. \begin{exercise}\normalfont\normalsize
  9186. {\if\edition\racketEd
  9187. %
  9188. Update the \code{uncover\_live} pass to apply liveness analysis to
  9189. every basic block in the program.
  9190. %
  9191. Add the following entry to the list of \code{passes} in the
  9192. \code{run-tests.rkt} script:
  9193. \begin{lstlisting}
  9194. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9195. \end{lstlisting}
  9196. \fi}
  9197. {\if\edition\pythonEd\pythonColor
  9198. %
  9199. Update the \code{uncover\_live} function to perform liveness analysis,
  9200. in reverse topological order, on all the basic blocks in the
  9201. program.
  9202. %
  9203. \fi}
  9204. % Check that the live-after sets that you generate for
  9205. % example X matches the following... -Jeremy
  9206. \end{exercise}
  9207. \subsection{Build the Interference Graph}
  9208. \label{sec:build-interference-Lif}
  9209. Many of the new instructions in \LangXIfVar{} can be handled in the
  9210. same way as the instructions in \LangXVar{}.
  9211. % Thus, if your code was
  9212. % already quite general, it will not need to be changed to handle the
  9213. % new instructions. If your code is not general enough, we recommend that
  9214. % you change your code to be more general. For example, you can factor
  9215. % out the computing of the the read and write sets for each kind of
  9216. % instruction into auxiliary functions.
  9217. %
  9218. Some instructions, such as the \key{movzbq} instruction, require special care,
  9219. similar to the \key{movq} instruction. Refer to rule number 1 in
  9220. section~\ref{sec:build-interference}.
  9221. \begin{exercise}\normalfont\normalsize
  9222. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9223. {\if\edition\racketEd
  9224. Add the following entries to the list of \code{passes} in the
  9225. \code{run-tests.rkt} script:
  9226. \begin{lstlisting}
  9227. (list "build_interference" build_interference interp-pseudo-x86-1)
  9228. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9229. \end{lstlisting}
  9230. \fi}
  9231. % Check that the interference graph that you generate for
  9232. % example X matches the following graph G... -Jeremy
  9233. \end{exercise}
  9234. \section{Patch Instructions}
  9235. The new instructions \key{cmpq} and \key{movzbq} have some special
  9236. restrictions that need to be handled in the \code{patch\_instructions}
  9237. pass.
  9238. %
  9239. The second argument of the \key{cmpq} instruction must not be an
  9240. immediate value (such as an integer). So, if you are comparing two
  9241. immediates, we recommend inserting a \key{movq} instruction to put the
  9242. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  9243. one memory reference.
  9244. %
  9245. The second argument of the \key{movzbq} must be a register.
  9246. \begin{exercise}\normalfont\normalsize
  9247. %
  9248. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9249. %
  9250. {\if\edition\racketEd
  9251. Add the following entry to the list of \code{passes} in
  9252. \code{run-tests.rkt}, and then run this script to test your compiler.
  9253. \begin{lstlisting}
  9254. (list "patch_instructions" patch_instructions interp-x86-1)
  9255. \end{lstlisting}
  9256. \fi}
  9257. \end{exercise}
  9258. {\if\edition\pythonEd\pythonColor
  9259. \section{Prelude and Conclusion}
  9260. \label{sec:prelude-conclusion-cond}
  9261. The generation of the \code{main} function with its prelude and
  9262. conclusion must change to accommodate how the program now consists of
  9263. one or more basic blocks. After the prelude in \code{main}, jump to
  9264. the \code{start} block. Place the conclusion in a basic block labeled
  9265. with \code{conclusion}.
  9266. \fi}
  9267. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9268. \LangIf{} translated to x86, showing the results of
  9269. \code{explicate\_control}, \code{select\_instructions}, and the final
  9270. x86 assembly.
  9271. \begin{figure}[tbp]
  9272. \begin{tcolorbox}[colback=white]
  9273. {\if\edition\racketEd
  9274. \begin{tabular}{lll}
  9275. \begin{minipage}{0.4\textwidth}
  9276. % cond_test_20.rkt, eq_input.py
  9277. \begin{lstlisting}
  9278. (if (eq? (read) 1) 42 0)
  9279. \end{lstlisting}
  9280. $\Downarrow$
  9281. \begin{lstlisting}
  9282. start:
  9283. tmp7951 = (read);
  9284. if (eq? tmp7951 1)
  9285. goto block7952;
  9286. else
  9287. goto block7953;
  9288. block7952:
  9289. return 42;
  9290. block7953:
  9291. return 0;
  9292. \end{lstlisting}
  9293. $\Downarrow$
  9294. \begin{lstlisting}
  9295. start:
  9296. callq read_int
  9297. movq %rax, tmp7951
  9298. cmpq $1, tmp7951
  9299. je block7952
  9300. jmp block7953
  9301. block7953:
  9302. movq $0, %rax
  9303. jmp conclusion
  9304. block7952:
  9305. movq $42, %rax
  9306. jmp conclusion
  9307. \end{lstlisting}
  9308. \end{minipage}
  9309. &
  9310. $\Rightarrow\qquad$
  9311. \begin{minipage}{0.4\textwidth}
  9312. \begin{lstlisting}
  9313. start:
  9314. callq read_int
  9315. movq %rax, %rcx
  9316. cmpq $1, %rcx
  9317. je block7952
  9318. jmp block7953
  9319. block7953:
  9320. movq $0, %rax
  9321. jmp conclusion
  9322. block7952:
  9323. movq $42, %rax
  9324. jmp conclusion
  9325. .globl main
  9326. main:
  9327. pushq %rbp
  9328. movq %rsp, %rbp
  9329. pushq %r13
  9330. pushq %r12
  9331. pushq %rbx
  9332. pushq %r14
  9333. subq $0, %rsp
  9334. jmp start
  9335. conclusion:
  9336. addq $0, %rsp
  9337. popq %r14
  9338. popq %rbx
  9339. popq %r12
  9340. popq %r13
  9341. popq %rbp
  9342. retq
  9343. \end{lstlisting}
  9344. \end{minipage}
  9345. \end{tabular}
  9346. \fi}
  9347. {\if\edition\pythonEd\pythonColor
  9348. \begin{tabular}{lll}
  9349. \begin{minipage}{0.4\textwidth}
  9350. % cond_test_20.rkt, eq_input.py
  9351. \begin{lstlisting}
  9352. print(42 if input_int() == 1 else 0)
  9353. \end{lstlisting}
  9354. $\Downarrow$
  9355. \begin{lstlisting}
  9356. start:
  9357. tmp_0 = input_int()
  9358. if tmp_0 == 1:
  9359. goto block_3
  9360. else:
  9361. goto block_4
  9362. block_3:
  9363. tmp_1 = 42
  9364. goto block_2
  9365. block_4:
  9366. tmp_1 = 0
  9367. goto block_2
  9368. block_2:
  9369. print(tmp_1)
  9370. return 0
  9371. \end{lstlisting}
  9372. $\Downarrow$
  9373. \begin{lstlisting}
  9374. start:
  9375. callq read_int
  9376. movq %rax, tmp_0
  9377. cmpq 1, tmp_0
  9378. je block_3
  9379. jmp block_4
  9380. block_3:
  9381. movq 42, tmp_1
  9382. jmp block_2
  9383. block_4:
  9384. movq 0, tmp_1
  9385. jmp block_2
  9386. block_2:
  9387. movq tmp_1, %rdi
  9388. callq print_int
  9389. movq 0, %rax
  9390. jmp conclusion
  9391. \end{lstlisting}
  9392. \end{minipage}
  9393. &
  9394. $\Rightarrow\qquad$
  9395. \begin{minipage}{0.4\textwidth}
  9396. \begin{lstlisting}
  9397. .globl main
  9398. main:
  9399. pushq %rbp
  9400. movq %rsp, %rbp
  9401. subq $0, %rsp
  9402. jmp start
  9403. start:
  9404. callq read_int
  9405. movq %rax, %rcx
  9406. cmpq $1, %rcx
  9407. je block_3
  9408. jmp block_4
  9409. block_3:
  9410. movq $42, %rcx
  9411. jmp block_2
  9412. block_4:
  9413. movq $0, %rcx
  9414. jmp block_2
  9415. block_2:
  9416. movq %rcx, %rdi
  9417. callq print_int
  9418. movq $0, %rax
  9419. jmp conclusion
  9420. conclusion:
  9421. addq $0, %rsp
  9422. popq %rbp
  9423. retq
  9424. \end{lstlisting}
  9425. \end{minipage}
  9426. \end{tabular}
  9427. \fi}
  9428. \end{tcolorbox}
  9429. \caption{Example compilation of an \key{if} expression to x86, showing
  9430. the results of \code{explicate\_control},
  9431. \code{select\_instructions}, and the final x86 assembly code. }
  9432. \label{fig:if-example-x86}
  9433. \end{figure}
  9434. \begin{figure}[tbp]
  9435. \begin{tcolorbox}[colback=white]
  9436. {\if\edition\racketEd
  9437. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9438. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9439. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9440. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9441. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9442. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9443. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9444. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9445. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9446. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9447. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9448. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9449. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9450. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9451. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9452. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9453. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9454. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9455. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9456. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9457. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9458. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9459. \end{tikzpicture}
  9460. \fi}
  9461. {\if\edition\pythonEd\pythonColor
  9462. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9463. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9464. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9465. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9466. \node (C-1) at (0,0) {\large \LangCIf{}};
  9467. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9468. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9469. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9470. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9471. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9472. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9473. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9474. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9475. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9476. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9477. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9478. \end{tikzpicture}
  9479. \fi}
  9480. \end{tcolorbox}
  9481. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9482. \label{fig:Lif-passes}
  9483. \end{figure}
  9484. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9485. compilation of \LangIf{}.
  9486. \section{Challenge: Optimize Blocks and Remove Jumps}
  9487. \label{sec:opt-jumps}
  9488. We discuss two optional challenges that involve optimizing the
  9489. control-flow of the program.
  9490. \subsection{Optimize Blocks}
  9491. The algorithm for \code{explicate\_control} that we discussed in
  9492. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9493. blocks. It creates a basic block whenever a continuation \emph{might}
  9494. get used more than once (for example, whenever the \code{cont} parameter is
  9495. passed into two or more recursive calls). However, some continuation
  9496. arguments may not be used at all. For example, consider the case for
  9497. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  9498. \code{els} continuation.
  9499. %
  9500. {\if\edition\racketEd
  9501. The following example program falls into this
  9502. case, and it creates two unused blocks.
  9503. \begin{center}
  9504. \begin{tabular}{lll}
  9505. \begin{minipage}{0.4\textwidth}
  9506. % cond_test_82.rkt
  9507. \begin{lstlisting}
  9508. (let ([y (if #t
  9509. (read)
  9510. (if (eq? (read) 0)
  9511. 777
  9512. (let ([x (read)])
  9513. (+ 1 x))))])
  9514. (+ y 2))
  9515. \end{lstlisting}
  9516. \end{minipage}
  9517. &
  9518. $\Rightarrow$
  9519. &
  9520. \begin{minipage}{0.55\textwidth}
  9521. \begin{lstlisting}
  9522. start:
  9523. y = (read);
  9524. goto block_5;
  9525. block_5:
  9526. return (+ y 2);
  9527. block_6:
  9528. y = 777;
  9529. goto block_5;
  9530. block_7:
  9531. x = (read);
  9532. y = (+ 1 x2);
  9533. goto block_5;
  9534. \end{lstlisting}
  9535. \end{minipage}
  9536. \end{tabular}
  9537. \end{center}
  9538. \fi}
  9539. The question is, how can we decide whether to create a basic block?
  9540. \emph{Lazy evaluation}\index{subject}{lazy
  9541. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9542. delaying the creation of a basic block until the point in time at which
  9543. we know that it will be used.
  9544. %
  9545. {\if\edition\racketEd
  9546. %
  9547. Racket provides support for
  9548. lazy evaluation with the
  9549. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9550. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9551. \index{subject}{delay} creates a
  9552. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9553. expressions is postponed. When \key{(force}
  9554. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9555. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9556. result of $e_n$ is cached in the promise and returned. If \code{force}
  9557. is applied again to the same promise, then the cached result is
  9558. returned. If \code{force} is applied to an argument that is not a
  9559. promise, \code{force} simply returns the argument.
  9560. %
  9561. \fi}
  9562. %
  9563. {\if\edition\pythonEd\pythonColor
  9564. %
  9565. While Python does not provide direct support for lazy evaluation, it
  9566. is easy to mimic. We can \emph{delay} the evaluation of a computation
  9567. by wrapping it inside a function with no parameters. We can
  9568. \emph{force} its evaluation by calling the function. However, in some
  9569. cases of \code{explicate\_pred}, etc., we will return a list of
  9570. statements and in other cases we will return a function that computes
  9571. a list of statements. We use the term \emph{promise} to refer to a
  9572. value that may be delayed. To uniformly deal with
  9573. promises, we define the following \code{force} function that checks
  9574. whether its input is delayed (i.e., whether it is a function) and then
  9575. either 1) calls the function, or 2) returns the input.
  9576. \begin{lstlisting}
  9577. def force(promise):
  9578. if isinstance(promise, types.FunctionType):
  9579. return promise()
  9580. else:
  9581. return promise
  9582. \end{lstlisting}
  9583. %
  9584. \fi}
  9585. We use promises for the input and output of the functions
  9586. \code{explicate\_pred}, \code{explicate\_assign},
  9587. %
  9588. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9589. %
  9590. So, instead of taking and returning \racket{$\Tail$
  9591. expressions}\python{lists of statements}, they take and return
  9592. promises. Furthermore, when we come to a situation in which a
  9593. continuation might be used more than once, as in the case for
  9594. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9595. that creates a basic block for each continuation (if there is not
  9596. already one) and then returns a \code{goto} statement to that basic
  9597. block. When we come to a situation in which we have a promise but need an
  9598. actual piece of code, for example, to create a larger piece of code with a
  9599. constructor such as \code{Seq}, then insert a call to \code{force}.
  9600. %
  9601. {\if\edition\racketEd
  9602. %
  9603. Also, we must modify the \code{create\_block} function to begin with
  9604. \code{delay} to create a promise. When forced, this promise forces the
  9605. original promise. If that returns a \code{Goto} (because the block was
  9606. already added to \code{basic-blocks}), then we return the
  9607. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9608. return a \code{Goto} to the new label.
  9609. \begin{center}
  9610. \begin{minipage}{\textwidth}
  9611. \begin{lstlisting}
  9612. (define (create_block tail)
  9613. (delay
  9614. (define t (force tail))
  9615. (match t
  9616. [(Goto label) (Goto label)]
  9617. [else
  9618. (let ([label (gensym 'block)])
  9619. (set! basic-blocks (cons (cons label t) basic-blocks))
  9620. (Goto label))])))
  9621. \end{lstlisting}
  9622. \end{minipage}
  9623. \end{center}
  9624. \fi}
  9625. {\if\edition\pythonEd\pythonColor
  9626. %
  9627. Here is the new version of the \code{create\_block} auxiliary function
  9628. that works on promises and that checks whether the block consists of a
  9629. solitary \code{goto} statement.\\
  9630. \begin{minipage}{\textwidth}
  9631. \begin{lstlisting}
  9632. def create_block(promise, basic_blocks):
  9633. stmts = force(promise)
  9634. match stmts:
  9635. case [Goto(l)]:
  9636. return Goto(l)
  9637. case _:
  9638. label = label_name(generate_name('block'))
  9639. basic_blocks[label] = stmts
  9640. return Goto(label)
  9641. \end{lstlisting}
  9642. \end{minipage}
  9643. \fi}
  9644. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9645. improved \code{explicate\_control} on this example. As you can
  9646. see, the number of basic blocks has been reduced from four blocks (see
  9647. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9648. \begin{figure}[tbp]
  9649. \begin{tcolorbox}[colback=white]
  9650. {\if\edition\racketEd
  9651. \begin{tabular}{lll}
  9652. \begin{minipage}{0.4\textwidth}
  9653. % cond_test_82.rkt
  9654. \begin{lstlisting}
  9655. (let ([y (if #t
  9656. (read)
  9657. (if (eq? (read) 0)
  9658. 777
  9659. (let ([x (read)])
  9660. (+ 1 x))))])
  9661. (+ y 2))
  9662. \end{lstlisting}
  9663. \end{minipage}
  9664. &
  9665. $\Rightarrow$
  9666. &
  9667. \begin{minipage}{0.55\textwidth}
  9668. \begin{lstlisting}
  9669. start:
  9670. y = (read);
  9671. goto block_5;
  9672. block_5:
  9673. return (+ y 2);
  9674. \end{lstlisting}
  9675. \end{minipage}
  9676. \end{tabular}
  9677. \fi}
  9678. {\if\edition\pythonEd\pythonColor
  9679. \begin{tabular}{lll}
  9680. \begin{minipage}{0.4\textwidth}
  9681. % cond_test_41.rkt
  9682. \begin{lstlisting}
  9683. x = input_int()
  9684. y = input_int()
  9685. print(y + 2 \
  9686. if (x == 0 \
  9687. if x < 1 \
  9688. else x == 2) \
  9689. else y + 10)
  9690. \end{lstlisting}
  9691. \end{minipage}
  9692. &
  9693. $\Rightarrow$
  9694. &
  9695. \begin{minipage}{0.55\textwidth}
  9696. \begin{lstlisting}
  9697. start:
  9698. x = input_int()
  9699. y = input_int()
  9700. if x < 1:
  9701. goto block_4
  9702. else:
  9703. goto block_5
  9704. block_4:
  9705. if x == 0:
  9706. goto block_2
  9707. else:
  9708. goto block_3
  9709. block_5:
  9710. if x == 2:
  9711. goto block_2
  9712. else:
  9713. goto block_3
  9714. block_2:
  9715. tmp_0 = y + 2
  9716. goto block_1
  9717. block_3:
  9718. tmp_0 = y + 10
  9719. goto block_1
  9720. block_1:
  9721. print(tmp_0)
  9722. return 0
  9723. \end{lstlisting}
  9724. \end{minipage}
  9725. \end{tabular}
  9726. \fi}
  9727. \end{tcolorbox}
  9728. \caption{Translation from \LangIf{} to \LangCIf{}
  9729. via the improved \code{explicate\_control}.}
  9730. \label{fig:explicate-control-challenge}
  9731. \end{figure}
  9732. %% Recall that in the example output of \code{explicate\_control} in
  9733. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9734. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9735. %% block. The first goal of this challenge assignment is to remove those
  9736. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9737. %% \code{explicate\_control} on the left and shows the result of bypassing
  9738. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9739. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9740. %% \code{block55}. The optimized code on the right of
  9741. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9742. %% \code{then} branch jumping directly to \code{block55}. The story is
  9743. %% similar for the \code{else} branch, as well as for the two branches in
  9744. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9745. %% have been optimized in this way, there are no longer any jumps to
  9746. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9747. %% \begin{figure}[tbp]
  9748. %% \begin{tabular}{lll}
  9749. %% \begin{minipage}{0.4\textwidth}
  9750. %% \begin{lstlisting}
  9751. %% block62:
  9752. %% tmp54 = (read);
  9753. %% if (eq? tmp54 2) then
  9754. %% goto block59;
  9755. %% else
  9756. %% goto block60;
  9757. %% block61:
  9758. %% tmp53 = (read);
  9759. %% if (eq? tmp53 0) then
  9760. %% goto block57;
  9761. %% else
  9762. %% goto block58;
  9763. %% block60:
  9764. %% goto block56;
  9765. %% block59:
  9766. %% goto block55;
  9767. %% block58:
  9768. %% goto block56;
  9769. %% block57:
  9770. %% goto block55;
  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. %% &
  9784. %% $\Rightarrow$
  9785. %% &
  9786. %% \begin{minipage}{0.55\textwidth}
  9787. %% \begin{lstlisting}
  9788. %% block62:
  9789. %% tmp54 = (read);
  9790. %% if (eq? tmp54 2) then
  9791. %% goto block55;
  9792. %% else
  9793. %% goto block56;
  9794. %% block61:
  9795. %% tmp53 = (read);
  9796. %% if (eq? tmp53 0) then
  9797. %% goto block55;
  9798. %% else
  9799. %% goto block56;
  9800. %% block56:
  9801. %% return (+ 700 77);
  9802. %% block55:
  9803. %% return (+ 10 32);
  9804. %% start:
  9805. %% tmp52 = (read);
  9806. %% if (eq? tmp52 1) then
  9807. %% goto block61;
  9808. %% else
  9809. %% goto block62;
  9810. %% \end{lstlisting}
  9811. %% \end{minipage}
  9812. %% \end{tabular}
  9813. %% \caption{Optimize jumps by removing trivial blocks.}
  9814. %% \label{fig:optimize-jumps}
  9815. %% \end{figure}
  9816. %% The name of this pass is \code{optimize-jumps}. We recommend
  9817. %% implementing this pass in two phases. The first phrase builds a hash
  9818. %% table that maps labels to possibly improved labels. The second phase
  9819. %% changes the target of each \code{goto} to use the improved label. If
  9820. %% the label is for a trivial block, then the hash table should map the
  9821. %% label to the first non-trivial block that can be reached from this
  9822. %% label by jumping through trivial blocks. If the label is for a
  9823. %% non-trivial block, then the hash table should map the label to itself;
  9824. %% we do not want to change jumps to non-trivial blocks.
  9825. %% The first phase can be accomplished by constructing an empty hash
  9826. %% table, call it \code{short-cut}, and then iterating over the control
  9827. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9828. %% then update the hash table, mapping the block's source to the target
  9829. %% of the \code{goto}. Also, the hash table may already have mapped some
  9830. %% labels to the block's source, to you must iterate through the hash
  9831. %% table and update all of those so that they instead map to the target
  9832. %% of the \code{goto}.
  9833. %% For the second phase, we recommend iterating through the $\Tail$ of
  9834. %% each block in the program, updating the target of every \code{goto}
  9835. %% according to the mapping in \code{short-cut}.
  9836. \begin{exercise}\normalfont\normalsize
  9837. Implement the improvements to the \code{explicate\_control} pass.
  9838. Check that it removes trivial blocks in a few example programs. Then
  9839. check that your compiler still passes all your tests.
  9840. \end{exercise}
  9841. \subsection{Remove Jumps}
  9842. There is an opportunity for removing jumps that is apparent in the
  9843. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9844. ends with a jump to \code{block\_5}, and there are no other jumps to
  9845. \code{block\_5} in the rest of the program. In this situation we can
  9846. avoid the runtime overhead of this jump by merging \code{block\_5}
  9847. into the preceding block, which in this case is the \code{start} block.
  9848. Figure~\ref{fig:remove-jumps} shows the output of
  9849. \code{allocate\_registers} on the left and the result of this
  9850. optimization on the right.
  9851. \begin{figure}[tbp]
  9852. \begin{tcolorbox}[colback=white]
  9853. {\if\edition\racketEd
  9854. \begin{tabular}{lll}
  9855. \begin{minipage}{0.5\textwidth}
  9856. % cond_test_82.rkt
  9857. \begin{lstlisting}
  9858. start:
  9859. callq read_int
  9860. movq %rax, %rcx
  9861. jmp block_5
  9862. block_5:
  9863. movq %rcx, %rax
  9864. addq $2, %rax
  9865. jmp conclusion
  9866. \end{lstlisting}
  9867. \end{minipage}
  9868. &
  9869. $\Rightarrow\qquad$
  9870. \begin{minipage}{0.4\textwidth}
  9871. \begin{lstlisting}
  9872. start:
  9873. callq read_int
  9874. movq %rax, %rcx
  9875. movq %rcx, %rax
  9876. addq $2, %rax
  9877. jmp conclusion
  9878. \end{lstlisting}
  9879. \end{minipage}
  9880. \end{tabular}
  9881. \fi}
  9882. {\if\edition\pythonEd\pythonColor
  9883. \begin{tabular}{lll}
  9884. \begin{minipage}{0.5\textwidth}
  9885. % cond_test_20.rkt
  9886. \begin{lstlisting}
  9887. start:
  9888. callq read_int
  9889. movq %rax, tmp_0
  9890. cmpq 1, tmp_0
  9891. je block_3
  9892. jmp block_4
  9893. block_3:
  9894. movq 42, tmp_1
  9895. jmp block_2
  9896. block_4:
  9897. movq 0, tmp_1
  9898. jmp block_2
  9899. block_2:
  9900. movq tmp_1, %rdi
  9901. callq print_int
  9902. movq 0, %rax
  9903. jmp conclusion
  9904. \end{lstlisting}
  9905. \end{minipage}
  9906. &
  9907. $\Rightarrow\qquad$
  9908. \begin{minipage}{0.4\textwidth}
  9909. \begin{lstlisting}
  9910. start:
  9911. callq read_int
  9912. movq %rax, tmp_0
  9913. cmpq 1, tmp_0
  9914. je block_3
  9915. movq 0, tmp_1
  9916. jmp block_2
  9917. block_3:
  9918. movq 42, tmp_1
  9919. jmp block_2
  9920. block_2:
  9921. movq tmp_1, %rdi
  9922. callq print_int
  9923. movq 0, %rax
  9924. jmp conclusion
  9925. \end{lstlisting}
  9926. \end{minipage}
  9927. \end{tabular}
  9928. \fi}
  9929. \end{tcolorbox}
  9930. \caption{Merging basic blocks by removing unnecessary jumps.}
  9931. \label{fig:remove-jumps}
  9932. \end{figure}
  9933. \begin{exercise}\normalfont\normalsize
  9934. %
  9935. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9936. into their preceding basic block, when there is only one preceding
  9937. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9938. %
  9939. {\if\edition\racketEd
  9940. In the \code{run-tests.rkt} script, add the following entry to the
  9941. list of \code{passes} between \code{allocate\_registers}
  9942. and \code{patch\_instructions}:
  9943. \begin{lstlisting}
  9944. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9945. \end{lstlisting}
  9946. \fi}
  9947. %
  9948. Run the script to test your compiler.
  9949. %
  9950. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9951. blocks on several test programs.
  9952. \end{exercise}
  9953. \section{Further Reading}
  9954. \label{sec:cond-further-reading}
  9955. The algorithm for the \code{explicate\_control} pass is based on the
  9956. \code{expose-basic-blocks} pass in the course notes of
  9957. \citet{Dybvig:2010aa}.
  9958. %
  9959. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9960. \citet{Appel:2003fk}, and is related to translations into continuation
  9961. passing
  9962. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9963. %
  9964. The treatment of conditionals in the \code{explicate\_control} pass is
  9965. similar to short-cut Boolean
  9966. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9967. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9968. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9969. \chapter{Loops and Dataflow Analysis}
  9970. \label{ch:Lwhile}
  9971. \setcounter{footnote}{0}
  9972. % TODO: define R'_8
  9973. % TODO: multi-graph
  9974. {\if\edition\racketEd
  9975. %
  9976. In this chapter we study two features that are the hallmarks of
  9977. imperative programming languages: loops and assignments to local
  9978. variables. The following example demonstrates these new features by
  9979. computing the sum of the first five positive integers:
  9980. % similar to loop_test_1.rkt
  9981. \begin{lstlisting}
  9982. (let ([sum 0])
  9983. (let ([i 5])
  9984. (begin
  9985. (while (> i 0)
  9986. (begin
  9987. (set! sum (+ sum i))
  9988. (set! i (- i 1))))
  9989. sum)))
  9990. \end{lstlisting}
  9991. The \code{while} loop consists of a condition and a
  9992. body.\footnote{The \code{while} loop is not a built-in
  9993. feature of the Racket language, but Racket includes many looping
  9994. constructs and it is straightforward to define \code{while} as a
  9995. macro.} The body is evaluated repeatedly so long as the condition
  9996. remains true.
  9997. %
  9998. The \code{set!} consists of a variable and a right-hand side
  9999. expression. The \code{set!} updates value of the variable to the
  10000. value of the right-hand side.
  10001. %
  10002. The primary purpose of both the \code{while} loop and \code{set!} is
  10003. to cause side effects, so they do not give a meaningful result
  10004. value. Instead, their result is the \code{\#<void>} value. The
  10005. expression \code{(void)} is an explicit way to create the
  10006. \code{\#<void>} value, and it has type \code{Void}. The
  10007. \code{\#<void>} value can be passed around just like other values
  10008. inside an \LangLoop{} program, and it can be compared for equality with
  10009. another \code{\#<void>} value. However, there are no other operations
  10010. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10011. Racket defines the \code{void?} predicate that returns \code{\#t}
  10012. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10013. %
  10014. \footnote{Racket's \code{Void} type corresponds to what is often
  10015. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10016. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10017. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10018. %
  10019. With the addition of side effect-producing features such as
  10020. \code{while} loop and \code{set!}, it is helpful to include a language
  10021. feature for sequencing side effects: the \code{begin} expression. It
  10022. consists of one or more subexpressions that are evaluated
  10023. left to right.
  10024. %
  10025. \fi}
  10026. {\if\edition\pythonEd\pythonColor
  10027. %
  10028. In this chapter we study loops, one of the hallmarks of imperative
  10029. programming languages. The following example demonstrates the
  10030. \code{while} loop by computing the sum of the first five positive
  10031. integers.
  10032. \begin{lstlisting}
  10033. sum = 0
  10034. i = 5
  10035. while i > 0:
  10036. sum = sum + i
  10037. i = i - 1
  10038. print(sum)
  10039. \end{lstlisting}
  10040. The \code{while} loop consists of a condition expression and a body (a
  10041. sequence of statements). The body is evaluated repeatedly so long as
  10042. the condition remains true.
  10043. %
  10044. \fi}
  10045. \section{The \LangLoop{} Language}
  10046. \newcommand{\LwhileGrammarRacket}{
  10047. \begin{array}{lcl}
  10048. \Type &::=& \key{Void}\\
  10049. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10050. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10051. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10052. \end{array}
  10053. }
  10054. \newcommand{\LwhileASTRacket}{
  10055. \begin{array}{lcl}
  10056. \Type &::=& \key{Void}\\
  10057. \Exp &::=& \SETBANG{\Var}{\Exp}
  10058. \MID \BEGIN{\Exp^{*}}{\Exp}
  10059. \MID \WHILE{\Exp}{\Exp}
  10060. \MID \VOID{}
  10061. \end{array}
  10062. }
  10063. \newcommand{\LwhileGrammarPython}{
  10064. \begin{array}{rcl}
  10065. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10066. \end{array}
  10067. }
  10068. \newcommand{\LwhileASTPython}{
  10069. \begin{array}{lcl}
  10070. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10071. \end{array}
  10072. }
  10073. \begin{figure}[tp]
  10074. \centering
  10075. \begin{tcolorbox}[colback=white]
  10076. \small
  10077. {\if\edition\racketEd
  10078. \[
  10079. \begin{array}{l}
  10080. \gray{\LintGrammarRacket{}} \\ \hline
  10081. \gray{\LvarGrammarRacket{}} \\ \hline
  10082. \gray{\LifGrammarRacket{}} \\ \hline
  10083. \LwhileGrammarRacket \\
  10084. \begin{array}{lcl}
  10085. \LangLoopM{} &::=& \Exp
  10086. \end{array}
  10087. \end{array}
  10088. \]
  10089. \fi}
  10090. {\if\edition\pythonEd\pythonColor
  10091. \[
  10092. \begin{array}{l}
  10093. \gray{\LintGrammarPython} \\ \hline
  10094. \gray{\LvarGrammarPython} \\ \hline
  10095. \gray{\LifGrammarPython} \\ \hline
  10096. \LwhileGrammarPython \\
  10097. \begin{array}{rcl}
  10098. \LangLoopM{} &::=& \Stmt^{*}
  10099. \end{array}
  10100. \end{array}
  10101. \]
  10102. \fi}
  10103. \end{tcolorbox}
  10104. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10105. \label{fig:Lwhile-concrete-syntax}
  10106. \end{figure}
  10107. \begin{figure}[tp]
  10108. \centering
  10109. \begin{tcolorbox}[colback=white]
  10110. \small
  10111. {\if\edition\racketEd
  10112. \[
  10113. \begin{array}{l}
  10114. \gray{\LintOpAST} \\ \hline
  10115. \gray{\LvarASTRacket{}} \\ \hline
  10116. \gray{\LifASTRacket{}} \\ \hline
  10117. \LwhileASTRacket{} \\
  10118. \begin{array}{lcl}
  10119. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10120. \end{array}
  10121. \end{array}
  10122. \]
  10123. \fi}
  10124. {\if\edition\pythonEd\pythonColor
  10125. \[
  10126. \begin{array}{l}
  10127. \gray{\LintASTPython} \\ \hline
  10128. \gray{\LvarASTPython} \\ \hline
  10129. \gray{\LifASTPython} \\ \hline
  10130. \LwhileASTPython \\
  10131. \begin{array}{lcl}
  10132. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10133. \end{array}
  10134. \end{array}
  10135. \]
  10136. \fi}
  10137. \end{tcolorbox}
  10138. \python{
  10139. \index{subject}{While@\texttt{While}}
  10140. }
  10141. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10142. \label{fig:Lwhile-syntax}
  10143. \end{figure}
  10144. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10145. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10146. shows the definition of its abstract syntax.
  10147. %
  10148. The definitional interpreter for \LangLoop{} is shown in
  10149. figure~\ref{fig:interp-Lwhile}.
  10150. %
  10151. {\if\edition\racketEd
  10152. %
  10153. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10154. and \code{Void}, and we make changes to the cases for \code{Var} and
  10155. \code{Let} regarding variables. To support assignment to variables and
  10156. to make their lifetimes indefinite (see the second example in
  10157. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10158. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10159. value.
  10160. %
  10161. Now we discuss the new cases. For \code{SetBang}, we find the
  10162. variable in the environment to obtain a boxed value, and then we change
  10163. it using \code{set-box!} to the result of evaluating the right-hand
  10164. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10165. %
  10166. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10167. if the result is true, (2) evaluate the body.
  10168. The result value of a \code{while} loop is also \code{\#<void>}.
  10169. %
  10170. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10171. subexpressions \itm{es} for their effects and then evaluates
  10172. and returns the result from \itm{body}.
  10173. %
  10174. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10175. %
  10176. \fi}
  10177. {\if\edition\pythonEd\pythonColor
  10178. %
  10179. We add a new case for \code{While} in the \code{interp\_stmts}
  10180. function, where we repeatedly interpret the \code{body} so long as the
  10181. \code{test} expression remains true.
  10182. %
  10183. \fi}
  10184. \begin{figure}[tbp]
  10185. \begin{tcolorbox}[colback=white]
  10186. {\if\edition\racketEd
  10187. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10188. (define interp-Lwhile-class
  10189. (class interp-Lif-class
  10190. (super-new)
  10191. (define/override ((interp-exp env) e)
  10192. (define recur (interp-exp env))
  10193. (match e
  10194. [(Let x e body)
  10195. (define new-env (dict-set env x (box (recur e))))
  10196. ((interp-exp new-env) body)]
  10197. [(Var x) (unbox (dict-ref env x))]
  10198. [(SetBang x rhs)
  10199. (set-box! (dict-ref env x) (recur rhs))]
  10200. [(WhileLoop cnd body)
  10201. (define (loop)
  10202. (cond [(recur cnd) (recur body) (loop)]
  10203. [else (void)]))
  10204. (loop)]
  10205. [(Begin es body)
  10206. (for ([e es]) (recur e))
  10207. (recur body)]
  10208. [(Void) (void)]
  10209. [else ((super interp-exp env) e)]))
  10210. ))
  10211. (define (interp-Lwhile p)
  10212. (send (new interp-Lwhile-class) interp-program p))
  10213. \end{lstlisting}
  10214. \fi}
  10215. {\if\edition\pythonEd\pythonColor
  10216. \begin{lstlisting}
  10217. class InterpLwhile(InterpLif):
  10218. def interp_stmt(self, s, env, cont):
  10219. match s:
  10220. case While(test, body, []):
  10221. if self.interp_exp(test, env):
  10222. self.interp_stmts(body + [s] + cont, env)
  10223. else:
  10224. return self.interp_stmts(cont, env)
  10225. case _:
  10226. return super().interp_stmt(s, env, cont)
  10227. \end{lstlisting}
  10228. \fi}
  10229. \end{tcolorbox}
  10230. \caption{Interpreter for \LangLoop{}.}
  10231. \label{fig:interp-Lwhile}
  10232. \end{figure}
  10233. The definition of the type checker for \LangLoop{} is shown in
  10234. figure~\ref{fig:type-check-Lwhile}.
  10235. %
  10236. {\if\edition\racketEd
  10237. %
  10238. The type checking of the \code{SetBang} expression requires the type
  10239. of the variable and the right-hand side to agree. The result type is
  10240. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10241. and the result type is \code{Void}. For \code{Begin}, the result type
  10242. is the type of its last subexpression.
  10243. %
  10244. \fi}
  10245. %
  10246. {\if\edition\pythonEd\pythonColor
  10247. %
  10248. A \code{while} loop is well typed if the type of the \code{test}
  10249. expression is \code{bool} and the statements in the \code{body} are
  10250. well typed.
  10251. %
  10252. \fi}
  10253. \begin{figure}[tbp]
  10254. \begin{tcolorbox}[colback=white]
  10255. {\if\edition\racketEd
  10256. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10257. (define type-check-Lwhile-class
  10258. (class type-check-Lif-class
  10259. (super-new)
  10260. (inherit check-type-equal?)
  10261. (define/override (type-check-exp env)
  10262. (lambda (e)
  10263. (define recur (type-check-exp env))
  10264. (match e
  10265. [(SetBang x rhs)
  10266. (define-values (rhs^ rhsT) (recur rhs))
  10267. (define varT (dict-ref env x))
  10268. (check-type-equal? rhsT varT e)
  10269. (values (SetBang x rhs^) 'Void)]
  10270. [(WhileLoop cnd body)
  10271. (define-values (cnd^ Tc) (recur cnd))
  10272. (check-type-equal? Tc 'Boolean e)
  10273. (define-values (body^ Tbody) ((type-check-exp env) body))
  10274. (values (WhileLoop cnd^ body^) 'Void)]
  10275. [(Begin es body)
  10276. (define-values (es^ ts)
  10277. (for/lists (l1 l2) ([e es]) (recur e)))
  10278. (define-values (body^ Tbody) (recur body))
  10279. (values (Begin es^ body^) Tbody)]
  10280. [else ((super type-check-exp env) e)])))
  10281. ))
  10282. (define (type-check-Lwhile p)
  10283. (send (new type-check-Lwhile-class) type-check-program p))
  10284. \end{lstlisting}
  10285. \fi}
  10286. {\if\edition\pythonEd\pythonColor
  10287. \begin{lstlisting}
  10288. class TypeCheckLwhile(TypeCheckLif):
  10289. def type_check_stmts(self, ss, env):
  10290. if len(ss) == 0:
  10291. return
  10292. match ss[0]:
  10293. case While(test, body, []):
  10294. test_t = self.type_check_exp(test, env)
  10295. check_type_equal(bool, test_t, test)
  10296. body_t = self.type_check_stmts(body, env)
  10297. return self.type_check_stmts(ss[1:], env)
  10298. case _:
  10299. return super().type_check_stmts(ss, env)
  10300. \end{lstlisting}
  10301. \fi}
  10302. \end{tcolorbox}
  10303. \caption{Type checker for the \LangLoop{} language.}
  10304. \label{fig:type-check-Lwhile}
  10305. \end{figure}
  10306. {\if\edition\racketEd
  10307. %
  10308. At first glance, the translation of these language features to x86
  10309. seems straightforward because the \LangCIf{} intermediate language
  10310. already supports all the ingredients that we need: assignment,
  10311. \code{goto}, conditional branching, and sequencing. However, there are
  10312. complications that arise, which we discuss in the next section. After
  10313. that we introduce the changes necessary to the existing passes.
  10314. %
  10315. \fi}
  10316. {\if\edition\pythonEd\pythonColor
  10317. %
  10318. At first glance, the translation of \code{while} loops to x86 seems
  10319. straightforward because the \LangCIf{} intermediate language already
  10320. supports \code{goto} and conditional branching. However, there are
  10321. complications that arise which we discuss in the next section. After
  10322. that we introduce the changes necessary to the existing passes.
  10323. %
  10324. \fi}
  10325. \section{Cyclic Control Flow and Dataflow Analysis}
  10326. \label{sec:dataflow-analysis}
  10327. Up until this point, the programs generated in
  10328. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10329. \code{while} loop introduces a cycle. Does that matter?
  10330. %
  10331. Indeed, it does. Recall that for register allocation, the compiler
  10332. performs liveness analysis to determine which variables can share the
  10333. same register. To accomplish this, we analyzed the control-flow graph
  10334. in reverse topological order
  10335. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10336. well defined only for acyclic graphs.
  10337. Let us return to the example of computing the sum of the first five
  10338. positive integers. Here is the program after instruction
  10339. selection\index{subject}{instruction selection} but before register
  10340. allocation.
  10341. \begin{center}
  10342. {\if\edition\racketEd
  10343. \begin{minipage}{0.45\textwidth}
  10344. \begin{lstlisting}
  10345. (define (main) : Integer
  10346. mainstart:
  10347. movq $0, sum
  10348. movq $5, i
  10349. jmp block5
  10350. block5:
  10351. movq i, tmp3
  10352. cmpq tmp3, $0
  10353. jl block7
  10354. jmp block8
  10355. \end{lstlisting}
  10356. \end{minipage}
  10357. \begin{minipage}{0.45\textwidth}
  10358. \begin{lstlisting}
  10359. block7:
  10360. addq i, sum
  10361. movq $1, tmp4
  10362. negq tmp4
  10363. addq tmp4, i
  10364. jmp block5
  10365. block8:
  10366. movq $27, %rax
  10367. addq sum, %rax
  10368. jmp mainconclusion)
  10369. \end{lstlisting}
  10370. \end{minipage}
  10371. \fi}
  10372. {\if\edition\pythonEd\pythonColor
  10373. \begin{minipage}{0.45\textwidth}
  10374. \begin{lstlisting}
  10375. mainstart:
  10376. movq $0, sum
  10377. movq $5, i
  10378. jmp block5
  10379. block5:
  10380. cmpq $0, i
  10381. jg block7
  10382. jmp block8
  10383. \end{lstlisting}
  10384. \end{minipage}
  10385. \begin{minipage}{0.45\textwidth}
  10386. \begin{lstlisting}
  10387. block7:
  10388. addq i, sum
  10389. subq $1, i
  10390. jmp block5
  10391. block8:
  10392. movq sum, %rdi
  10393. callq print_int
  10394. movq $0, %rax
  10395. jmp mainconclusion
  10396. \end{lstlisting}
  10397. \end{minipage}
  10398. \fi}
  10399. \end{center}
  10400. Recall that liveness analysis works backward, starting at the end
  10401. of each function. For this example we could start with \code{block8}
  10402. because we know what is live at the beginning of the conclusion:
  10403. only \code{rax} and \code{rsp}. So the live-before set
  10404. for \code{block8} is \code{\{rsp,sum\}}.
  10405. %
  10406. Next we might try to analyze \code{block5} or \code{block7}, but
  10407. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10408. we are stuck.
  10409. The way out of this impasse is to realize that we can compute an
  10410. underapproximation of each live-before set by starting with empty
  10411. live-after sets. By \emph{underapproximation}, we mean that the set
  10412. contains only variables that are live for some execution of the
  10413. program, but the set may be missing some variables that are live.
  10414. Next, the underapproximations for each block can be improved by (1)
  10415. updating the live-after set for each block using the approximate
  10416. live-before sets from the other blocks, and (2) performing liveness
  10417. analysis again on each block. In fact, by iterating this process, the
  10418. underapproximations eventually become the correct solutions!
  10419. %
  10420. This approach of iteratively analyzing a control-flow graph is
  10421. applicable to many static analysis problems and goes by the name
  10422. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10423. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10424. Washington.
  10425. Let us apply this approach to the previously presented example. We use
  10426. the empty set for the initial live-before set for each block. Let
  10427. $m_0$ be the following mapping from label names to sets of locations
  10428. (variables and registers):
  10429. \begin{center}
  10430. \begin{lstlisting}
  10431. mainstart: {}, block5: {}, block7: {}, block8: {}
  10432. \end{lstlisting}
  10433. \end{center}
  10434. Using the above live-before approximations, we determine the
  10435. live-after for each block and then apply liveness analysis to each
  10436. block. This produces our next approximation $m_1$ of the live-before
  10437. sets.
  10438. \begin{center}
  10439. \begin{lstlisting}
  10440. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10441. \end{lstlisting}
  10442. \end{center}
  10443. For the second round, the live-after for \code{mainstart} is the
  10444. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10445. the liveness analysis for \code{mainstart} computes the empty set. The
  10446. live-after for \code{block5} is the union of the live-before sets for
  10447. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10448. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10449. sum\}}. The live-after for \code{block7} is the live-before for
  10450. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10451. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10452. Together these yield the following approximation $m_2$ of
  10453. the live-before sets:
  10454. \begin{center}
  10455. \begin{lstlisting}
  10456. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10457. \end{lstlisting}
  10458. \end{center}
  10459. In the preceding iteration, only \code{block5} changed, so we can
  10460. limit our attention to \code{mainstart} and \code{block7}, the two
  10461. blocks that jump to \code{block5}. As a result, the live-before sets
  10462. for \code{mainstart} and \code{block7} are updated to include
  10463. \code{rsp}, yielding the following approximation $m_3$:
  10464. \begin{center}
  10465. \begin{lstlisting}
  10466. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10467. \end{lstlisting}
  10468. \end{center}
  10469. Because \code{block7} changed, we analyze \code{block5} once more, but
  10470. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10471. our approximations have converged, so $m_3$ is the solution.
  10472. This iteration process is guaranteed to converge to a solution by the
  10473. Kleene fixed-point theorem, a general theorem about functions on
  10474. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10475. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10476. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10477. join operator
  10478. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10479. will be working with join semilattices.} When two elements are
  10480. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10481. as much information as $m_i$, so we can think of $m_j$ as a
  10482. better-than-or-equal-to approximation in relation to $m_i$. The
  10483. bottom element $\bot$ represents the complete lack of information,
  10484. that is, the worst approximation. The join operator takes two lattice
  10485. elements and combines their information; that is, it produces the
  10486. least upper bound of the two.\index{subject}{least upper bound}
  10487. A dataflow analysis typically involves two lattices: one lattice to
  10488. represent abstract states and another lattice that aggregates the
  10489. abstract states of all the blocks in the control-flow graph. For
  10490. liveness analysis, an abstract state is a set of locations. We form
  10491. the lattice $L$ by taking its elements to be sets of locations, the
  10492. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10493. set, and the join operator to be set union.
  10494. %
  10495. We form a second lattice $M$ by taking its elements to be mappings
  10496. from the block labels to sets of locations (elements of $L$). We
  10497. order the mappings point-wise, using the ordering of $L$. So, given any
  10498. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10499. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10500. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10501. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10502. We can think of one iteration of liveness analysis applied to the
  10503. whole program as being a function $f$ on the lattice $M$. It takes a
  10504. mapping as input and computes a new mapping.
  10505. \[
  10506. f(m_i) = m_{i+1}
  10507. \]
  10508. Next let us think for a moment about what a final solution $m_s$
  10509. should look like. If we perform liveness analysis using the solution
  10510. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10511. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10512. \[
  10513. f(m_s) = m_s
  10514. \]
  10515. Furthermore, the solution should include only locations that are
  10516. forced to be there by performing liveness analysis on the program, so
  10517. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10518. The Kleene fixed-point theorem states that if a function $f$ is
  10519. monotone (better inputs produce better outputs), then the least fixed
  10520. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10521. chain} obtained by starting at $\bot$ and iterating $f$, as
  10522. follows:\index{subject}{Kleene fixed-point theorem}
  10523. \[
  10524. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10525. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10526. \]
  10527. When a lattice contains only finitely long ascending chains, then
  10528. every Kleene chain tops out at some fixed point after some number of
  10529. iterations of $f$.
  10530. \[
  10531. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10532. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10533. \]
  10534. The liveness analysis is indeed a monotone function and the lattice
  10535. $M$ has finitely long ascending chains because there are only a
  10536. finite number of variables and blocks in the program. Thus we are
  10537. guaranteed that iteratively applying liveness analysis to all blocks
  10538. in the program will eventually produce the least fixed point solution.
  10539. Next let us consider dataflow analysis in general and discuss the
  10540. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10541. %
  10542. The algorithm has four parameters: the control-flow graph \code{G}, a
  10543. function \code{transfer} that applies the analysis to one block, and the
  10544. \code{bottom} and \code{join} operators for the lattice of abstract
  10545. states. The \code{analyze\_dataflow} function is formulated as a
  10546. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10547. function come from the predecessor nodes in the control-flow
  10548. graph. However, liveness analysis is a \emph{backward} dataflow
  10549. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10550. function with the transpose of the control-flow graph.
  10551. The algorithm begins by creating the bottom mapping, represented by a
  10552. hash table. It then pushes all the nodes in the control-flow graph
  10553. onto the work list (a queue). The algorithm repeats the \code{while}
  10554. loop as long as there are items in the work list. In each iteration, a
  10555. node is popped from the work list and processed. The \code{input} for
  10556. the node is computed by taking the join of the abstract states of all
  10557. the predecessor nodes. The \code{transfer} function is then applied to
  10558. obtain the \code{output} abstract state. If the output differs from
  10559. the previous state for this block, the mapping for this block is
  10560. updated and its successor nodes are pushed onto the work list.
  10561. \begin{figure}[tb]
  10562. \begin{tcolorbox}[colback=white]
  10563. {\if\edition\racketEd
  10564. \begin{lstlisting}
  10565. (define (analyze_dataflow G transfer bottom join)
  10566. (define mapping (make-hash))
  10567. (for ([v (in-vertices G)])
  10568. (dict-set! mapping v bottom))
  10569. (define worklist (make-queue))
  10570. (for ([v (in-vertices G)])
  10571. (enqueue! worklist v))
  10572. (define trans-G (transpose G))
  10573. (while (not (queue-empty? worklist))
  10574. (define node (dequeue! worklist))
  10575. (define input (for/fold ([state bottom])
  10576. ([pred (in-neighbors trans-G node)])
  10577. (join state (dict-ref mapping pred))))
  10578. (define output (transfer node input))
  10579. (cond [(not (equal? output (dict-ref mapping node)))
  10580. (dict-set! mapping node output)
  10581. (for ([v (in-neighbors G node)])
  10582. (enqueue! worklist v))]))
  10583. mapping)
  10584. \end{lstlisting}
  10585. \fi}
  10586. {\if\edition\pythonEd\pythonColor
  10587. \begin{lstlisting}
  10588. def analyze_dataflow(G, transfer, bottom, join):
  10589. trans_G = transpose(G)
  10590. mapping = dict((v, bottom) for v in G.vertices())
  10591. worklist = deque(G.vertices)
  10592. while worklist:
  10593. node = worklist.pop()
  10594. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10595. input = reduce(join, inputs, bottom)
  10596. output = transfer(node, input)
  10597. if output != mapping[node]:
  10598. mapping[node] = output
  10599. worklist.extend(G.adjacent(node))
  10600. \end{lstlisting}
  10601. \fi}
  10602. \end{tcolorbox}
  10603. \caption{Generic work list algorithm for dataflow analysis.}
  10604. \label{fig:generic-dataflow}
  10605. \end{figure}
  10606. {\if\edition\racketEd
  10607. \section{Mutable Variables and Remove Complex Operands}
  10608. There is a subtle interaction between the
  10609. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10610. and the left-to-right order of evaluation of Racket. Consider the
  10611. following example:
  10612. \begin{lstlisting}
  10613. (let ([x 2])
  10614. (+ x (begin (set! x 40) x)))
  10615. \end{lstlisting}
  10616. The result of this program is \code{42} because the first read from
  10617. \code{x} produces \code{2} and the second produces \code{40}. However,
  10618. if we naively apply the \code{remove\_complex\_operands} pass to this
  10619. example we obtain the following program whose result is \code{80}!
  10620. \begin{lstlisting}
  10621. (let ([x 2])
  10622. (let ([tmp (begin (set! x 40) x)])
  10623. (+ x tmp)))
  10624. \end{lstlisting}
  10625. The problem is that with mutable variables, the ordering between
  10626. reads and writes is important, and the
  10627. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10628. before the first read of \code{x}.
  10629. We recommend solving this problem by giving special treatment to reads
  10630. from mutable variables, that is, variables that occur on the left-hand
  10631. side of a \code{set!}. We mark each read from a mutable variable with
  10632. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10633. that the read operation is effectful in that it can produce different
  10634. results at different points in time. Let's apply this idea to the
  10635. following variation that also involves a variable that is not mutated:
  10636. % loop_test_24.rkt
  10637. \begin{lstlisting}
  10638. (let ([x 2])
  10639. (let ([y 0])
  10640. (+ y (+ x (begin (set! x 40) x)))))
  10641. \end{lstlisting}
  10642. We first analyze this program to discover that variable \code{x}
  10643. is mutable but \code{y} is not. We then transform the program as
  10644. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10645. \begin{lstlisting}
  10646. (let ([x 2])
  10647. (let ([y 0])
  10648. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10649. \end{lstlisting}
  10650. Now that we have a clear distinction between reads from mutable and
  10651. immutable variables, we can apply the \code{remove\_complex\_operands}
  10652. pass, where reads from immutable variables are still classified as
  10653. atomic expressions but reads from mutable variables are classified as
  10654. complex. Thus, \code{remove\_complex\_operands} yields the following
  10655. program:\\
  10656. \begin{minipage}{\textwidth}
  10657. \begin{lstlisting}
  10658. (let ([x 2])
  10659. (let ([y 0])
  10660. (+ y (let ([t1 (get! x)])
  10661. (let ([t2 (begin (set! x 40) (get! x))])
  10662. (+ t1 t2))))))
  10663. \end{lstlisting}
  10664. \end{minipage}
  10665. The temporary variable \code{t1} gets the value of \code{x} before the
  10666. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10667. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10668. do not generate a temporary variable for the occurrence of \code{y}
  10669. because it's an immutable variable. We want to avoid such unnecessary
  10670. extra temporaries because they would needlessly increase the number of
  10671. variables, making it more likely for some of them to be spilled. The
  10672. result of this program is \code{42}, the same as the result prior to
  10673. \code{remove\_complex\_operands}.
  10674. The approach that we've sketched requires only a small
  10675. modification to \code{remove\_complex\_operands} to handle
  10676. \code{get!}. However, it requires a new pass, called
  10677. \code{uncover-get!}, that we discuss in
  10678. section~\ref{sec:uncover-get-bang}.
  10679. As an aside, this problematic interaction between \code{set!} and the
  10680. pass \code{remove\_complex\_operands} is particular to Racket and not
  10681. its predecessor, the Scheme language. The key difference is that
  10682. Scheme does not specify an order of evaluation for the arguments of an
  10683. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10684. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10685. would be correct results for the example program. Interestingly,
  10686. Racket is implemented on top of the Chez Scheme
  10687. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10688. presented in this section (using extra \code{let} bindings to control
  10689. the order of evaluation) is used in the translation from Racket to
  10690. Scheme~\citep{Flatt:2019tb}.
  10691. \fi} % racket
  10692. Having discussed the complications that arise from adding support for
  10693. assignment and loops, we turn to discussing the individual compilation
  10694. passes.
  10695. {\if\edition\racketEd
  10696. \section{Uncover \texttt{get!}}
  10697. \label{sec:uncover-get-bang}
  10698. The goal of this pass is to mark uses of mutable variables so that
  10699. \code{remove\_complex\_operands} can treat them as complex expressions
  10700. and thereby preserve their ordering relative to the side effects in
  10701. other operands. So, the first step is to collect all the mutable
  10702. variables. We recommend creating an auxiliary function for this,
  10703. named \code{collect-set!}, that recursively traverses expressions,
  10704. returning the set of all variables that occur on the left-hand side of a
  10705. \code{set!}. Here's an excerpt of its implementation.
  10706. \begin{center}
  10707. \begin{minipage}{\textwidth}
  10708. \begin{lstlisting}
  10709. (define (collect-set! e)
  10710. (match e
  10711. [(Var x) (set)]
  10712. [(Int n) (set)]
  10713. [(Let x rhs body)
  10714. (set-union (collect-set! rhs) (collect-set! body))]
  10715. [(SetBang var rhs)
  10716. (set-union (set var) (collect-set! rhs))]
  10717. ...))
  10718. \end{lstlisting}
  10719. \end{minipage}
  10720. \end{center}
  10721. By placing this pass after \code{uniquify}, we need not worry about
  10722. variable shadowing, and our logic for \code{Let} can remain simple, as
  10723. in this excerpt.
  10724. The second step is to mark the occurrences of the mutable variables
  10725. with the new \code{GetBang} AST node (\code{get!} in concrete
  10726. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10727. function, which takes two parameters: the set of mutable variables
  10728. \code{set!-vars} and the expression \code{e} to be processed. The
  10729. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10730. mutable variable or leaves it alone if not.
  10731. \begin{center}
  10732. \begin{minipage}{\textwidth}
  10733. \begin{lstlisting}
  10734. (define ((uncover-get!-exp set!-vars) e)
  10735. (match e
  10736. [(Var x)
  10737. (if (set-member? set!-vars x)
  10738. (GetBang x)
  10739. (Var x))]
  10740. ...))
  10741. \end{lstlisting}
  10742. \end{minipage}
  10743. \end{center}
  10744. To wrap things up, define the \code{uncover-get!} function for
  10745. processing a whole program, using \code{collect-set!} to obtain the
  10746. set of mutable variables and then \code{uncover-get!-exp} to replace
  10747. their occurrences with \code{GetBang}.
  10748. \fi}
  10749. \section{Remove Complex Operands}
  10750. \label{sec:rco-loop}
  10751. {\if\edition\racketEd
  10752. %
  10753. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10754. \code{while} are all complex expressions. The subexpressions of
  10755. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10756. %
  10757. \fi}
  10758. {\if\edition\pythonEd\pythonColor
  10759. %
  10760. The change needed for this pass is to add a case for the \code{while}
  10761. statement. The condition of a \code{while} loop is allowed to be a
  10762. complex expression, just like the condition of the \code{if}
  10763. statement.
  10764. %
  10765. \fi}
  10766. %
  10767. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10768. \LangLoopANF{} of this pass.
  10769. \newcommand{\LwhileMonadASTRacket}{
  10770. \begin{array}{rcl}
  10771. \Atm &::=& \VOID{} \\
  10772. \Exp &::=& \GETBANG{\Var}
  10773. \MID \SETBANG{\Var}{\Exp}
  10774. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10775. &\MID& \WHILE{\Exp}{\Exp}
  10776. \end{array}
  10777. }
  10778. \newcommand{\LwhileMonadASTPython}{
  10779. \begin{array}{rcl}
  10780. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10781. \end{array}
  10782. }
  10783. \begin{figure}[tp]
  10784. \centering
  10785. \begin{tcolorbox}[colback=white]
  10786. \small
  10787. {\if\edition\racketEd
  10788. \[
  10789. \begin{array}{l}
  10790. \gray{\LvarMonadASTRacket} \\ \hline
  10791. \gray{\LifMonadASTRacket} \\ \hline
  10792. \LwhileMonadASTRacket \\
  10793. \begin{array}{rcl}
  10794. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10795. \end{array}
  10796. \end{array}
  10797. \]
  10798. \fi}
  10799. {\if\edition\pythonEd\pythonColor
  10800. \[
  10801. \begin{array}{l}
  10802. \gray{\LvarMonadASTPython} \\ \hline
  10803. \gray{\LifMonadASTPython} \\ \hline
  10804. \LwhileMonadASTPython \\
  10805. \begin{array}{rcl}
  10806. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10807. \end{array}
  10808. \end{array}
  10809. %% \begin{array}{rcl}
  10810. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10811. %% \Exp &::=& \Atm \MID \READ{} \\
  10812. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10813. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10814. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10815. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10816. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10817. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10818. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10819. %% \end{array}
  10820. \]
  10821. \fi}
  10822. \end{tcolorbox}
  10823. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10824. \label{fig:Lwhile-anf-syntax}
  10825. \end{figure}
  10826. {\if\edition\racketEd
  10827. %
  10828. As usual, when a complex expression appears in a grammar position that
  10829. needs to be atomic, such as the argument of a primitive operator, we
  10830. must introduce a temporary variable and bind it to the complex
  10831. expression. This approach applies, unchanged, to handle the new
  10832. language forms. For example, in the following code there are two
  10833. \code{begin} expressions appearing as arguments to the \code{+}
  10834. operator. The output of \code{rco\_exp} is then shown, in which the
  10835. \code{begin} expressions have been bound to temporary
  10836. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10837. allowed to have arbitrary expressions in their right-hand side
  10838. expression, so it is fine to place \code{begin} there.
  10839. %
  10840. \begin{center}
  10841. \begin{tabular}{lcl}
  10842. \begin{minipage}{0.4\textwidth}
  10843. \begin{lstlisting}
  10844. (let ([x2 10])
  10845. (let ([y3 0])
  10846. (+ (+ (begin
  10847. (set! y3 (read))
  10848. (get! x2))
  10849. (begin
  10850. (set! x2 (read))
  10851. (get! y3)))
  10852. (get! x2))))
  10853. \end{lstlisting}
  10854. \end{minipage}
  10855. &
  10856. $\Rightarrow$
  10857. &
  10858. \begin{minipage}{0.4\textwidth}
  10859. \begin{lstlisting}
  10860. (let ([x2 10])
  10861. (let ([y3 0])
  10862. (let ([tmp4 (begin
  10863. (set! y3 (read))
  10864. x2)])
  10865. (let ([tmp5 (begin
  10866. (set! x2 (read))
  10867. y3)])
  10868. (let ([tmp6 (+ tmp4 tmp5)])
  10869. (let ([tmp7 x2])
  10870. (+ tmp6 tmp7)))))))
  10871. \end{lstlisting}
  10872. \end{minipage}
  10873. \end{tabular}
  10874. \end{center}
  10875. \fi}
  10876. \section{Explicate Control \racket{and \LangCLoop{}}}
  10877. \label{sec:explicate-loop}
  10878. \newcommand{\CloopASTRacket}{
  10879. \begin{array}{lcl}
  10880. \Atm &::=& \VOID \\
  10881. \Stmt &::=& \READ{}
  10882. \end{array}
  10883. }
  10884. {\if\edition\racketEd
  10885. Recall that in the \code{explicate\_control} pass we define one helper
  10886. function for each kind of position in the program. For the \LangVar{}
  10887. language of integers and variables, we needed assignment and tail
  10888. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10889. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10890. another kind of position: effect position. Except for the last
  10891. subexpression, the subexpressions inside a \code{begin} are evaluated
  10892. only for their effect. Their result values are discarded. We can
  10893. generate better code by taking this fact into account.
  10894. The output language of \code{explicate\_control} is \LangCLoop{}
  10895. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10896. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10897. and that \code{read} may appear as a statement. The most significant
  10898. difference between the programs generated by \code{explicate\_control}
  10899. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10900. chapter is that the control-flow graphs of the latter may contain
  10901. cycles.
  10902. \begin{figure}[tp]
  10903. \begin{tcolorbox}[colback=white]
  10904. \small
  10905. \[
  10906. \begin{array}{l}
  10907. \gray{\CvarASTRacket} \\ \hline
  10908. \gray{\CifASTRacket} \\ \hline
  10909. \CloopASTRacket \\
  10910. \begin{array}{lcl}
  10911. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10912. \end{array}
  10913. \end{array}
  10914. \]
  10915. \end{tcolorbox}
  10916. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10917. \label{fig:c7-syntax}
  10918. \end{figure}
  10919. The new auxiliary function \code{explicate\_effect} takes an
  10920. expression (in an effect position) and the code for its
  10921. continuation. The function returns a $\Tail$ that includes the
  10922. generated code for the input expression followed by the
  10923. continuation. If the expression is obviously pure, that is, never
  10924. causes side effects, then the expression can be removed, so the result
  10925. is just the continuation.
  10926. %
  10927. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10928. interesting; the generated code is depicted in the following diagram:
  10929. \begin{center}
  10930. \begin{minipage}{0.3\textwidth}
  10931. \xymatrix{
  10932. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10933. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10934. & *+[F]{\txt{\itm{cont}}} \\
  10935. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10936. }
  10937. \end{minipage}
  10938. \end{center}
  10939. We start by creating a fresh label $\itm{loop}$ for the top of the
  10940. loop. Next, recursively process the \itm{body} (in effect position)
  10941. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10942. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10943. \itm{body'} as the \emph{then} branch and the continuation block as the
  10944. \emph{else} branch. The result should be added to the dictionary of
  10945. \code{basic-blocks} with the label \itm{loop}. The result for the
  10946. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10947. The auxiliary functions for tail, assignment, and predicate positions
  10948. need to be updated. The three new language forms, \code{while},
  10949. \code{set!}, and \code{begin}, can appear in assignment and tail
  10950. positions. Only \code{begin} may appear in predicate positions; the
  10951. other two have result type \code{Void}.
  10952. \fi}
  10953. %
  10954. {\if\edition\pythonEd\pythonColor
  10955. %
  10956. The output of this pass is the language \LangCIf{}. No new language
  10957. features are needed in the output because a \code{while} loop can be
  10958. expressed in terms of \code{goto} and \code{if} statements, which are
  10959. already in \LangCIf{}.
  10960. %
  10961. Add a case for the \code{while} statement to the
  10962. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10963. the condition expression.
  10964. %
  10965. \fi}
  10966. {\if\edition\racketEd
  10967. \section{Select Instructions}
  10968. \label{sec:select-instructions-loop}
  10969. \index{subject}{select instructions}
  10970. Only two small additions are needed in the \code{select\_instructions}
  10971. pass to handle the changes to \LangCLoop{}. First, to handle the
  10972. addition of \VOID{} we simply translate it to \code{0}. Second,
  10973. \code{read} may appear as a stand-alone statement instead of
  10974. appearing only on the right-hand side of an assignment statement. The code
  10975. generation is nearly identical to the one for assignment; just leave
  10976. off the instruction for moving the result into the left-hand side.
  10977. \fi}
  10978. \section{Register Allocation}
  10979. \label{sec:register-allocation-loop}
  10980. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10981. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10982. which complicates the liveness analysis needed for register
  10983. allocation.
  10984. %
  10985. We recommend using the generic \code{analyze\_dataflow} function that
  10986. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10987. perform liveness analysis, replacing the code in
  10988. \code{uncover\_live} that processed the basic blocks in topological
  10989. order (section~\ref{sec:liveness-analysis-Lif}).
  10990. The \code{analyze\_dataflow} function has the following four parameters.
  10991. \begin{enumerate}
  10992. \item The first parameter \code{G} should be passed the transpose
  10993. of the control-flow graph.
  10994. \item The second parameter \code{transfer} should be passed a function
  10995. that applies liveness analysis to a basic block. It takes two
  10996. parameters: the label for the block to analyze and the live-after
  10997. set for that block. The transfer function should return the
  10998. live-before set for the block.
  10999. %
  11000. \racket{Also, as a side effect, it should update the block's
  11001. $\itm{info}$ with the liveness information for each instruction.}
  11002. %
  11003. \python{Also, as a side-effect, it should update the live-before and
  11004. live-after sets for each instruction.}
  11005. %
  11006. To implement the \code{transfer} function, you should be able to
  11007. reuse the code you already have for analyzing basic blocks.
  11008. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11009. \code{bottom} and \code{join} for the lattice of abstract states,
  11010. that is, sets of locations. For liveness analysis, the bottom of the
  11011. lattice is the empty set, and the join operator is set union.
  11012. \end{enumerate}
  11013. \begin{figure}[p]
  11014. \begin{tcolorbox}[colback=white]
  11015. {\if\edition\racketEd
  11016. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11017. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11018. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11019. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11020. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11021. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11022. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11023. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11024. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11025. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11026. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11027. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11028. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11029. \path[->,bend left=15] (Lfun) edge [above] node
  11030. {\ttfamily\footnotesize shrink} (Lfun-2);
  11031. \path[->,bend left=15] (Lfun-2) edge [above] node
  11032. {\ttfamily\footnotesize uniquify} (F1-4);
  11033. \path[->,bend left=15] (F1-4) edge [above] node
  11034. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11035. \path[->,bend left=15] (F1-5) edge [left] node
  11036. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11037. \path[->,bend left=10] (F1-6) edge [above] node
  11038. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11039. \path[->,bend left=15] (C3-2) edge [right] node
  11040. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11041. \path[->,bend right=15] (x86-2) edge [right] node
  11042. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11043. \path[->,bend right=15] (x86-2-1) edge [below] node
  11044. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11045. \path[->,bend right=15] (x86-2-2) edge [right] node
  11046. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11047. \path[->,bend left=15] (x86-3) edge [above] node
  11048. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11049. \path[->,bend left=15] (x86-4) edge [right] node
  11050. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11051. \end{tikzpicture}
  11052. \fi}
  11053. {\if\edition\pythonEd\pythonColor
  11054. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11055. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11056. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11057. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11058. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11059. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11060. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11061. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11062. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11063. \path[->,bend left=15] (Lfun) edge [above] node
  11064. {\ttfamily\footnotesize shrink} (Lfun-2);
  11065. \path[->,bend left=15] (Lfun-2) edge [above] node
  11066. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11067. \path[->,bend left=10] (F1-6) edge [right] node
  11068. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11069. \path[->,bend right=15] (C3-2) edge [right] node
  11070. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11071. \path[->,bend right=15] (x86-2) edge [below] node
  11072. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11073. \path[->,bend left=15] (x86-3) edge [above] node
  11074. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11075. \path[->,bend right=15] (x86-4) edge [below] node
  11076. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11077. \end{tikzpicture}
  11078. \fi}
  11079. \end{tcolorbox}
  11080. \caption{Diagram of the passes for \LangLoop{}.}
  11081. \label{fig:Lwhile-passes}
  11082. \end{figure}
  11083. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11084. for the compilation of \LangLoop{}.
  11085. % Further Reading: dataflow analysis
  11086. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11087. \chapter{Tuples and Garbage Collection}
  11088. \label{ch:Lvec}
  11089. \index{subject}{tuple}
  11090. \index{subject}{vector}
  11091. \setcounter{footnote}{0}
  11092. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11093. %% all the IR grammars are spelled out! \\ --Jeremy}
  11094. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11095. %% the root stack. \\ --Jeremy}
  11096. In this chapter we study the implementation of tuples\racket{, called
  11097. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11098. in which each element may have a different type.
  11099. %
  11100. This language feature is the first to use the computer's
  11101. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11102. indefinite; that is, a tuple lives forever from the programmer's
  11103. viewpoint. Of course, from an implementer's viewpoint, it is important
  11104. to reclaim the space associated with a tuple when it is no longer
  11105. needed, which is why we also study \emph{garbage collection}
  11106. \index{subject}{garbage collection} techniques in this chapter.
  11107. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11108. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11109. language (chapter~\ref{ch:Lwhile}) with tuples.
  11110. %
  11111. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11112. copying live tuples back and forth between two halves of the heap. The
  11113. garbage collector requires coordination with the compiler so that it
  11114. can find all the live tuples.
  11115. %
  11116. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11117. discuss the necessary changes and additions to the compiler passes,
  11118. including a new compiler pass named \code{expose\_allocation}.
  11119. \section{The \LangVec{} Language}
  11120. \label{sec:r3}
  11121. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11122. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11123. the definition of the abstract syntax.
  11124. %
  11125. \racket{The \LangVec{} language includes the forms \code{vector} for
  11126. creating a tuple, \code{vector-ref} for reading an element of a
  11127. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11128. \code{vector-length} for obtaining the number of elements of a
  11129. tuple.}
  11130. %
  11131. \python{The \LangVec{} language adds 1) tuple creation via a
  11132. comma-separated list of expressions, 2) accessing an element of a
  11133. tuple with the square bracket notation, i.e., \code{t[n]} returns
  11134. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  11135. operator, and 4) obtaining the number of elements (the length) of a
  11136. tuple. In this chapter, we restrict access indices to constant
  11137. integers.}
  11138. %
  11139. The following program shows an example use of tuples. It creates a tuple
  11140. \code{t} containing the elements \code{40},
  11141. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11142. contains just \code{2}. The element at index $1$ of \code{t} is
  11143. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11144. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11145. to which we add \code{2}, the element at index $0$ of the tuple.
  11146. The result of the program is \code{42}.
  11147. %
  11148. {\if\edition\racketEd
  11149. \begin{lstlisting}
  11150. (let ([t (vector 40 #t (vector 2))])
  11151. (if (vector-ref t 1)
  11152. (+ (vector-ref t 0)
  11153. (vector-ref (vector-ref t 2) 0))
  11154. 44))
  11155. \end{lstlisting}
  11156. \fi}
  11157. {\if\edition\pythonEd\pythonColor
  11158. \begin{lstlisting}
  11159. t = 40, True, (2,)
  11160. print( t[0] + t[2][0] if t[1] else 44 )
  11161. \end{lstlisting}
  11162. \fi}
  11163. \newcommand{\LtupGrammarRacket}{
  11164. \begin{array}{lcl}
  11165. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11166. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11167. \MID \LP\key{vector-length}\;\Exp\RP \\
  11168. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11169. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11170. \end{array}
  11171. }
  11172. \newcommand{\LtupASTRacket}{
  11173. \begin{array}{lcl}
  11174. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11175. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11176. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11177. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11178. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11179. \end{array}
  11180. }
  11181. \newcommand{\LtupGrammarPython}{
  11182. \begin{array}{rcl}
  11183. \itm{cmp} &::= & \key{is} \\
  11184. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11185. \end{array}
  11186. }
  11187. \newcommand{\LtupASTPython}{
  11188. \begin{array}{lcl}
  11189. \itm{cmp} &::= & \code{Is()} \\
  11190. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11191. &\MID& \LEN{\Exp}
  11192. \end{array}
  11193. }
  11194. \begin{figure}[tbp]
  11195. \centering
  11196. \begin{tcolorbox}[colback=white]
  11197. \small
  11198. {\if\edition\racketEd
  11199. \[
  11200. \begin{array}{l}
  11201. \gray{\LintGrammarRacket{}} \\ \hline
  11202. \gray{\LvarGrammarRacket{}} \\ \hline
  11203. \gray{\LifGrammarRacket{}} \\ \hline
  11204. \gray{\LwhileGrammarRacket} \\ \hline
  11205. \LtupGrammarRacket \\
  11206. \begin{array}{lcl}
  11207. \LangVecM{} &::=& \Exp
  11208. \end{array}
  11209. \end{array}
  11210. \]
  11211. \fi}
  11212. {\if\edition\pythonEd\pythonColor
  11213. \[
  11214. \begin{array}{l}
  11215. \gray{\LintGrammarPython{}} \\ \hline
  11216. \gray{\LvarGrammarPython{}} \\ \hline
  11217. \gray{\LifGrammarPython{}} \\ \hline
  11218. \gray{\LwhileGrammarPython} \\ \hline
  11219. \LtupGrammarPython \\
  11220. \begin{array}{rcl}
  11221. \LangVecM{} &::=& \Stmt^{*}
  11222. \end{array}
  11223. \end{array}
  11224. \]
  11225. \fi}
  11226. \end{tcolorbox}
  11227. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11228. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11229. \label{fig:Lvec-concrete-syntax}
  11230. \end{figure}
  11231. \begin{figure}[tp]
  11232. \centering
  11233. \begin{tcolorbox}[colback=white]
  11234. \small
  11235. {\if\edition\racketEd
  11236. \[
  11237. \begin{array}{l}
  11238. \gray{\LintOpAST} \\ \hline
  11239. \gray{\LvarASTRacket{}} \\ \hline
  11240. \gray{\LifASTRacket{}} \\ \hline
  11241. \gray{\LwhileASTRacket{}} \\ \hline
  11242. \LtupASTRacket{} \\
  11243. \begin{array}{lcl}
  11244. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11245. \end{array}
  11246. \end{array}
  11247. \]
  11248. \fi}
  11249. {\if\edition\pythonEd\pythonColor
  11250. \[
  11251. \begin{array}{l}
  11252. \gray{\LintASTPython} \\ \hline
  11253. \gray{\LvarASTPython} \\ \hline
  11254. \gray{\LifASTPython} \\ \hline
  11255. \gray{\LwhileASTPython} \\ \hline
  11256. \LtupASTPython \\
  11257. \begin{array}{lcl}
  11258. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11259. \end{array}
  11260. \end{array}
  11261. \]
  11262. \fi}
  11263. \end{tcolorbox}
  11264. \caption{The abstract syntax of \LangVec{}.}
  11265. \label{fig:Lvec-syntax}
  11266. \end{figure}
  11267. Tuples raise several interesting new issues. First, variable binding
  11268. performs a shallow copy in dealing with tuples, which means that
  11269. different variables can refer to the same tuple; that is, two
  11270. variables can be \emph{aliases}\index{subject}{alias} for the same
  11271. entity. Consider the following example, in which \code{t1} and
  11272. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11273. different tuple value with equal elements. The result of the
  11274. program is \code{42}.
  11275. \begin{center}
  11276. \begin{minipage}{0.96\textwidth}
  11277. {\if\edition\racketEd
  11278. \begin{lstlisting}
  11279. (let ([t1 (vector 3 7)])
  11280. (let ([t2 t1])
  11281. (let ([t3 (vector 3 7)])
  11282. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11283. 42
  11284. 0))))
  11285. \end{lstlisting}
  11286. \fi}
  11287. {\if\edition\pythonEd\pythonColor
  11288. \begin{lstlisting}
  11289. t1 = 3, 7
  11290. t2 = t1
  11291. t3 = 3, 7
  11292. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  11293. \end{lstlisting}
  11294. \fi}
  11295. \end{minipage}
  11296. \end{center}
  11297. {\if\edition\racketEd
  11298. Whether two variables are aliased or not affects what happens
  11299. when the underlying tuple is mutated\index{subject}{mutation}.
  11300. Consider the following example in which \code{t1} and \code{t2}
  11301. again refer to the same tuple value.
  11302. \begin{center}
  11303. \begin{minipage}{0.96\textwidth}
  11304. \begin{lstlisting}
  11305. (let ([t1 (vector 3 7)])
  11306. (let ([t2 t1])
  11307. (let ([_ (vector-set! t2 0 42)])
  11308. (vector-ref t1 0))))
  11309. \end{lstlisting}
  11310. \end{minipage}
  11311. \end{center}
  11312. The mutation through \code{t2} is visible in referencing the tuple
  11313. from \code{t1}, so the result of this program is \code{42}.
  11314. \fi}
  11315. The next issue concerns the lifetime of tuples. When does a tuple's
  11316. lifetime end? Notice that \LangVec{} does not include an operation
  11317. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11318. to any notion of static scoping.
  11319. %
  11320. {\if\edition\racketEd
  11321. %
  11322. For example, the following program returns \code{42} even though the
  11323. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11324. that reads from the vector to which it was bound.
  11325. \begin{center}
  11326. \begin{minipage}{0.96\textwidth}
  11327. \begin{lstlisting}
  11328. (let ([v (vector (vector 44))])
  11329. (let ([x (let ([w (vector 42)])
  11330. (let ([_ (vector-set! v 0 w)])
  11331. 0))])
  11332. (+ x (vector-ref (vector-ref v 0) 0))))
  11333. \end{lstlisting}
  11334. \end{minipage}
  11335. \end{center}
  11336. \fi}
  11337. %
  11338. {\if\edition\pythonEd\pythonColor
  11339. %
  11340. For example, the following program returns \code{42} even though the
  11341. variable \code{x} goes out of scope when the function returns, prior
  11342. to reading the tuple element at index zero. (We study the compilation
  11343. of functions in chapter~\ref{ch:Lfun}.)
  11344. %
  11345. \begin{center}
  11346. \begin{minipage}{0.96\textwidth}
  11347. \begin{lstlisting}
  11348. def f():
  11349. x = 42, 43
  11350. return x
  11351. t = f()
  11352. print( t[0] )
  11353. \end{lstlisting}
  11354. \end{minipage}
  11355. \end{center}
  11356. \fi}
  11357. %
  11358. From the perspective of programmer-observable behavior, tuples live
  11359. forever. However, if they really lived forever then many long-running
  11360. programs would run out of memory. To solve this problem, the
  11361. language's runtime system performs automatic garbage collection.
  11362. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11363. \LangVec{} language.
  11364. %
  11365. \racket{We define the \code{vector}, \code{vector-ref},
  11366. \code{vector-set!}, and \code{vector-length} operations for
  11367. \LangVec{} in terms of the corresponding operations in Racket. One
  11368. subtle point is that the \code{vector-set!} operation returns the
  11369. \code{\#<void>} value.}
  11370. %
  11371. \python{We represent tuples with Python lists in the interpreter
  11372. because we need to write to them
  11373. (section~\ref{sec:expose-allocation}). (Python tuples are
  11374. immutable.) We define element access, the \code{is} operator, and
  11375. the \code{len} operator for \LangVec{} in terms of the corresponding
  11376. operations in Python.}
  11377. \begin{figure}[tbp]
  11378. \begin{tcolorbox}[colback=white]
  11379. {\if\edition\racketEd
  11380. \begin{lstlisting}
  11381. (define interp-Lvec-class
  11382. (class interp-Lwhile-class
  11383. (super-new)
  11384. (define/override (interp-op op)
  11385. (match op
  11386. ['eq? (lambda (v1 v2)
  11387. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11388. (and (boolean? v1) (boolean? v2))
  11389. (and (vector? v1) (vector? v2))
  11390. (and (void? v1) (void? v2)))
  11391. (eq? v1 v2)]))]
  11392. ['vector vector]
  11393. ['vector-length vector-length]
  11394. ['vector-ref vector-ref]
  11395. ['vector-set! vector-set!]
  11396. [else (super interp-op op)]
  11397. ))
  11398. (define/override ((interp-exp env) e)
  11399. (match e
  11400. [(HasType e t) ((interp-exp env) e)]
  11401. [else ((super interp-exp env) e)]
  11402. ))
  11403. ))
  11404. (define (interp-Lvec p)
  11405. (send (new interp-Lvec-class) interp-program p))
  11406. \end{lstlisting}
  11407. \fi}
  11408. %
  11409. {\if\edition\pythonEd\pythonColor
  11410. \begin{lstlisting}
  11411. class InterpLtup(InterpLwhile):
  11412. def interp_cmp(self, cmp):
  11413. match cmp:
  11414. case Is():
  11415. return lambda x, y: x is y
  11416. case _:
  11417. return super().interp_cmp(cmp)
  11418. def interp_exp(self, e, env):
  11419. match e:
  11420. case Tuple(es, Load()):
  11421. return tuple([self.interp_exp(e, env) for e in es])
  11422. case Subscript(tup, index, Load()):
  11423. t = self.interp_exp(tup, env)
  11424. n = self.interp_exp(index, env)
  11425. return t[n]
  11426. case _:
  11427. return super().interp_exp(e, env)
  11428. \end{lstlisting}
  11429. \fi}
  11430. \end{tcolorbox}
  11431. \caption{Interpreter for the \LangVec{} language.}
  11432. \label{fig:interp-Lvec}
  11433. \end{figure}
  11434. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11435. \LangVec{}.
  11436. %
  11437. The type of a tuple is a
  11438. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11439. type for each of its elements.
  11440. %
  11441. \racket{To create the s-expression for the \code{Vector} type, we use the
  11442. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11443. operator} \code{,@} to insert the list \code{t*} without its usual
  11444. start and end parentheses. \index{subject}{unquote-splicing}}
  11445. %
  11446. The type of accessing the ith element of a tuple is the ith element
  11447. type of the tuple's type, if there is one. If not, an error is
  11448. signaled. Note that the index \code{i} is required to be a constant
  11449. integer (and not, for example, a call to
  11450. \racket{\code{read}}\python{input\_int}) so that the type checker
  11451. can determine the element's type given the tuple type.
  11452. %
  11453. \racket{
  11454. Regarding writing an element to a tuple, the element's type must
  11455. be equal to the ith element type of the tuple's type.
  11456. The result type is \code{Void}.}
  11457. %% When allocating a tuple,
  11458. %% we need to know which elements of the tuple are themselves tuples for
  11459. %% the purposes of garbage collection. We can obtain this information
  11460. %% during type checking. The type checker shown in
  11461. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11462. %% expression; it also
  11463. %% %
  11464. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11465. %% where $T$ is the tuple's type.
  11466. %
  11467. %records the type of each tuple expression in a new field named \code{has\_type}.
  11468. \begin{figure}[tp]
  11469. \begin{tcolorbox}[colback=white]
  11470. {\if\edition\racketEd
  11471. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11472. (define type-check-Lvec-class
  11473. (class type-check-Lif-class
  11474. (super-new)
  11475. (inherit check-type-equal?)
  11476. (define/override (type-check-exp env)
  11477. (lambda (e)
  11478. (define recur (type-check-exp env))
  11479. (match e
  11480. [(Prim 'vector es)
  11481. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11482. (define t `(Vector ,@t*))
  11483. (values (Prim 'vector e*) t)]
  11484. [(Prim 'vector-ref (list e1 (Int i)))
  11485. (define-values (e1^ t) (recur e1))
  11486. (match t
  11487. [`(Vector ,ts ...)
  11488. (unless (and (0 . <= . i) (i . < . (length ts)))
  11489. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11490. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11491. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11492. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11493. (define-values (e-vec t-vec) (recur e1))
  11494. (define-values (e-elt^ t-elt) (recur elt))
  11495. (match t-vec
  11496. [`(Vector ,ts ...)
  11497. (unless (and (0 . <= . i) (i . < . (length ts)))
  11498. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11499. (check-type-equal? (list-ref ts i) t-elt e)
  11500. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11501. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11502. [(Prim 'vector-length (list e))
  11503. (define-values (e^ t) (recur e))
  11504. (match t
  11505. [`(Vector ,ts ...)
  11506. (values (Prim 'vector-length (list e^)) 'Integer)]
  11507. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11508. [(Prim 'eq? (list arg1 arg2))
  11509. (define-values (e1 t1) (recur arg1))
  11510. (define-values (e2 t2) (recur arg2))
  11511. (match* (t1 t2)
  11512. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11513. [(other wise) (check-type-equal? t1 t2 e)])
  11514. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11515. [else ((super type-check-exp env) e)]
  11516. )))
  11517. ))
  11518. (define (type-check-Lvec p)
  11519. (send (new type-check-Lvec-class) type-check-program p))
  11520. \end{lstlisting}
  11521. \fi}
  11522. {\if\edition\pythonEd\pythonColor
  11523. \begin{lstlisting}
  11524. class TypeCheckLtup(TypeCheckLwhile):
  11525. def type_check_exp(self, e, env):
  11526. match e:
  11527. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11528. l = self.type_check_exp(left, env)
  11529. r = self.type_check_exp(right, env)
  11530. check_type_equal(l, r, e)
  11531. return bool
  11532. case Tuple(es, Load()):
  11533. ts = [self.type_check_exp(e, env) for e in es]
  11534. e.has_type = TupleType(ts)
  11535. return e.has_type
  11536. case Subscript(tup, Constant(i), Load()):
  11537. tup_ty = self.type_check_exp(tup, env)
  11538. i_ty = self.type_check_exp(Constant(i), env)
  11539. check_type_equal(i_ty, int, i)
  11540. match tup_ty:
  11541. case TupleType(ts):
  11542. return ts[i]
  11543. case _:
  11544. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11545. case _:
  11546. return super().type_check_exp(e, env)
  11547. \end{lstlisting}
  11548. \fi}
  11549. \end{tcolorbox}
  11550. \caption{Type checker for the \LangVec{} language.}
  11551. \label{fig:type-check-Lvec}
  11552. \end{figure}
  11553. \section{Garbage Collection}
  11554. \label{sec:GC}
  11555. Garbage collection is a runtime technique for reclaiming space on the
  11556. heap that will not be used in the future of the running program. We
  11557. use the term \emph{object}\index{subject}{object} to refer to any
  11558. value that is stored in the heap, which for now includes only
  11559. tuples.%
  11560. %
  11561. \footnote{The term \emph{object} as it is used in the context of
  11562. object-oriented programming has a more specific meaning than the
  11563. way in which we use the term here.}
  11564. %
  11565. Unfortunately, it is impossible to know precisely which objects will
  11566. be accessed in the future and which will not. Instead, garbage
  11567. collectors overapproximate the set of objects that will be accessed by
  11568. identifying which objects can possibly be accessed. The running
  11569. program can directly access objects that are in registers and on the
  11570. procedure call stack. It can also transitively access the elements of
  11571. tuples, starting with a tuple whose address is in a register or on the
  11572. procedure call stack. We define the \emph{root
  11573. set}\index{subject}{root set} to be all the tuple addresses that are
  11574. in registers or on the procedure call stack. We define the \emph{live
  11575. objects}\index{subject}{live objects} to be the objects that are
  11576. reachable from the root set. Garbage collectors reclaim the space that
  11577. is allocated to objects that are no longer live. \index{subject}{allocate}
  11578. That means that some objects may not get reclaimed as soon as they could be,
  11579. but at least
  11580. garbage collectors do not reclaim the space dedicated to objects that
  11581. will be accessed in the future! The programmer can influence which
  11582. objects get reclaimed by causing them to become unreachable.
  11583. So the goal of the garbage collector is twofold:
  11584. \begin{enumerate}
  11585. \item to preserve all the live objects, and
  11586. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11587. \end{enumerate}
  11588. \subsection{Two-Space Copying Collector}
  11589. Here we study a relatively simple algorithm for garbage collection
  11590. that is the basis of many state-of-the-art garbage
  11591. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11592. particular, we describe a two-space copying
  11593. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11594. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11595. collector} \index{subject}{two-space copying collector}
  11596. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11597. what happens in a two-space collector, showing two time steps, prior
  11598. to garbage collection (on the top) and after garbage collection (on
  11599. the bottom). In a two-space collector, the heap is divided into two
  11600. parts named the FromSpace\index{subject}{FromSpace} and the
  11601. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11602. FromSpace until there is not enough room for the next allocation
  11603. request. At that point, the garbage collector goes to work to make
  11604. room for the next allocation.
  11605. A copying collector makes more room by copying all the live objects
  11606. from the FromSpace into the ToSpace and then performs a sleight of
  11607. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11608. as the new ToSpace. In the example shown in
  11609. figure~\ref{fig:copying-collector}, the root set consists of three
  11610. pointers, one in a register and two on the stack. All the live
  11611. objects have been copied to the ToSpace (the right-hand side of
  11612. figure~\ref{fig:copying-collector}) in a way that preserves the
  11613. pointer relationships. For example, the pointer in the register still
  11614. points to a tuple that in turn points to two other tuples. There are
  11615. four tuples that are not reachable from the root set and therefore do
  11616. not get copied into the ToSpace.
  11617. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11618. created by a well-typed program in \LangVec{} because it contains a
  11619. cycle. However, creating cycles will be possible once we get to
  11620. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11621. to deal with cycles to begin with, so we will not need to revisit this
  11622. issue.
  11623. \begin{figure}[tbp]
  11624. \centering
  11625. \begin{tcolorbox}[colback=white]
  11626. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11627. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11628. \\[5ex]
  11629. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11630. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11631. \end{tcolorbox}
  11632. \caption{A copying collector in action.}
  11633. \label{fig:copying-collector}
  11634. \end{figure}
  11635. \subsection{Graph Copying via Cheney's Algorithm}
  11636. \label{sec:cheney}
  11637. \index{subject}{Cheney's algorithm}
  11638. Let us take a closer look at the copying of the live objects. The
  11639. allocated\index{subject}{allocate} objects and pointers can be viewed
  11640. as a graph, and we need to copy the part of the graph that is
  11641. reachable from the root set. To make sure that we copy all the
  11642. reachable vertices in the graph, we need an exhaustive graph traversal
  11643. algorithm, such as depth-first search or breadth-first
  11644. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11645. take into account the possibility of cycles by marking which vertices
  11646. have already been visited, so to ensure termination of the
  11647. algorithm. These search algorithms also use a data structure such as a
  11648. stack or queue as a to-do list to keep track of the vertices that need
  11649. to be visited. We use breadth-first search and a trick due to
  11650. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11651. copying tuples into the ToSpace.
  11652. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11653. copy progresses. The queue is represented by a chunk of contiguous
  11654. memory at the beginning of the ToSpace, using two pointers to track
  11655. the front and the back of the queue, called the \emph{free pointer}
  11656. and the \emph{scan pointer}, respectively. The algorithm starts by
  11657. copying all tuples that are immediately reachable from the root set
  11658. into the ToSpace to form the initial queue. When we copy a tuple, we
  11659. mark the old tuple to indicate that it has been visited. We discuss
  11660. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11661. that any pointers inside the copied tuples in the queue still point
  11662. back to the FromSpace. Once the initial queue has been created, the
  11663. algorithm enters a loop in which it repeatedly processes the tuple at
  11664. the front of the queue and pops it off the queue. To process a tuple,
  11665. the algorithm copies all the objects that are directly reachable from it
  11666. to the ToSpace, placing them at the back of the queue. The algorithm
  11667. then updates the pointers in the popped tuple so that they point to the
  11668. newly copied objects.
  11669. \begin{figure}[tbp]
  11670. \centering
  11671. \begin{tcolorbox}[colback=white]
  11672. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  11673. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  11674. \end{tcolorbox}
  11675. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11676. \label{fig:cheney}
  11677. \end{figure}
  11678. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11679. tuple whose second element is $42$ to the back of the queue. The other
  11680. pointer goes to a tuple that has already been copied, so we do not
  11681. need to copy it again, but we do need to update the pointer to the new
  11682. location. This can be accomplished by storing a \emph{forwarding
  11683. pointer}\index{subject}{forwarding pointer} to the new location in the
  11684. old tuple, when we initially copied the tuple into the
  11685. ToSpace. This completes one step of the algorithm. The algorithm
  11686. continues in this way until the queue is empty; that is, when the scan
  11687. pointer catches up with the free pointer.
  11688. \subsection{Data Representation}
  11689. \label{sec:data-rep-gc}
  11690. The garbage collector places some requirements on the data
  11691. representations used by our compiler. First, the garbage collector
  11692. needs to distinguish between pointers and other kinds of data such as
  11693. integers. The following are several ways to accomplish this:
  11694. \begin{enumerate}
  11695. \item Attach a tag to each object that identifies what type of
  11696. object it is~\citep{McCarthy:1960dz}.
  11697. \item Store different types of objects in different
  11698. regions~\citep{Steele:1977ab}.
  11699. \item Use type information from the program to either (a) generate
  11700. type-specific code for collecting, or (b) generate tables that
  11701. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11702. \end{enumerate}
  11703. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11704. need to tag objects in any case, so option 1 is a natural choice for those
  11705. languages. However, \LangVec{} is a statically typed language, so it
  11706. would be unfortunate to require tags on every object, especially small
  11707. and pervasive objects like integers and Booleans. Option 3 is the
  11708. best-performing choice for statically typed languages, but it comes with
  11709. a relatively high implementation complexity. To keep this chapter
  11710. within a reasonable scope of complexity, we recommend a combination of options
  11711. 1 and 2, using separate strategies for the stack and the heap.
  11712. Regarding the stack, we recommend using a separate stack for pointers,
  11713. which we call the \emph{root stack}\index{subject}{root stack}
  11714. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11715. That is, when a local variable needs to be spilled and is of type
  11716. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11717. root stack instead of putting it on the procedure call
  11718. stack. Furthermore, we always spill tuple-typed variables if they are
  11719. live during a call to the collector, thereby ensuring that no pointers
  11720. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11721. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11722. contrasts it with the data layout using a root stack. The root stack
  11723. contains the two pointers from the regular stack and also the pointer
  11724. in the second register.
  11725. \begin{figure}[tbp]
  11726. \centering
  11727. \begin{tcolorbox}[colback=white]
  11728. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11729. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11730. \end{tcolorbox}
  11731. \caption{Maintaining a root stack to facilitate garbage collection.}
  11732. \label{fig:shadow-stack}
  11733. \end{figure}
  11734. The problem of distinguishing between pointers and other kinds of data
  11735. also arises inside each tuple on the heap. We solve this problem by
  11736. attaching a tag, an extra 64 bits, to each
  11737. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11738. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11739. Note that we have drawn the bits in a big-endian way, from right to left,
  11740. with bit location 0 (the least significant bit) on the far right,
  11741. which corresponds to the direction of the x86 shifting instructions
  11742. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11743. is dedicated to specifying which elements of the tuple are pointers,
  11744. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11745. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11746. data. The pointer mask starts at bit location 7. We limit tuples to a
  11747. maximum size of fifty elements, so we need 50 bits for the pointer
  11748. mask.%
  11749. %
  11750. \footnote{A production-quality compiler would handle
  11751. arbitrarily sized tuples and use a more complex approach.}
  11752. %
  11753. The tag also contains two other pieces of information. The length of
  11754. the tuple (number of elements) is stored in bits at locations 1 through
  11755. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11756. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11757. has not yet been copied. If the bit has value 0, then the entire tag
  11758. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11759. zero in any case, because our tuples are 8-byte aligned.)
  11760. \begin{figure}[tbp]
  11761. \centering
  11762. \begin{tcolorbox}[colback=white]
  11763. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11764. \end{tcolorbox}
  11765. \caption{Representation of tuples in the heap.}
  11766. \label{fig:tuple-rep}
  11767. \end{figure}
  11768. \subsection{Implementation of the Garbage Collector}
  11769. \label{sec:organize-gz}
  11770. \index{subject}{prelude}
  11771. An implementation of the copying collector is provided in the
  11772. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11773. interface to the garbage collector that is used by the compiler. The
  11774. \code{initialize} function creates the FromSpace, ToSpace, and root
  11775. stack and should be called in the prelude of the \code{main}
  11776. function. The arguments of \code{initialize} are the root stack size
  11777. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11778. good choice for both. The \code{initialize} function puts the address
  11779. of the beginning of the FromSpace into the global variable
  11780. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11781. the address that is one past the last element of the FromSpace. We use
  11782. half-open intervals to represent chunks of
  11783. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11784. points to the first element of the root stack.
  11785. As long as there is room left in the FromSpace, your generated code
  11786. can allocate\index{subject}{allocate} tuples simply by moving the
  11787. \code{free\_ptr} forward.
  11788. %
  11789. The amount of room left in the FromSpace is the difference between the
  11790. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11791. function should be called when there is not enough room left in the
  11792. FromSpace for the next allocation. The \code{collect} function takes
  11793. a pointer to the current top of the root stack (one past the last item
  11794. that was pushed) and the number of bytes that need to be
  11795. allocated. The \code{collect} function performs the copying collection
  11796. and leaves the heap in a state such that there is enough room for the
  11797. next allocation.
  11798. \begin{figure}[tbp]
  11799. \begin{tcolorbox}[colback=white]
  11800. \begin{lstlisting}
  11801. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11802. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11803. int64_t* free_ptr;
  11804. int64_t* fromspace_begin;
  11805. int64_t* fromspace_end;
  11806. int64_t** rootstack_begin;
  11807. \end{lstlisting}
  11808. \end{tcolorbox}
  11809. \caption{The compiler's interface to the garbage collector.}
  11810. \label{fig:gc-header}
  11811. \end{figure}
  11812. %% \begin{exercise}
  11813. %% In the file \code{runtime.c} you will find the implementation of
  11814. %% \code{initialize} and a partial implementation of \code{collect}.
  11815. %% The \code{collect} function calls another function, \code{cheney},
  11816. %% to perform the actual copy, and that function is left to the reader
  11817. %% to implement. The following is the prototype for \code{cheney}.
  11818. %% \begin{lstlisting}
  11819. %% static void cheney(int64_t** rootstack_ptr);
  11820. %% \end{lstlisting}
  11821. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11822. %% rootstack (which is an array of pointers). The \code{cheney} function
  11823. %% also communicates with \code{collect} through the global
  11824. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11825. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11826. %% the ToSpace:
  11827. %% \begin{lstlisting}
  11828. %% static int64_t* tospace_begin;
  11829. %% static int64_t* tospace_end;
  11830. %% \end{lstlisting}
  11831. %% The job of the \code{cheney} function is to copy all the live
  11832. %% objects (reachable from the root stack) into the ToSpace, update
  11833. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11834. %% update the root stack so that it points to the objects in the
  11835. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11836. %% and ToSpace.
  11837. %% \end{exercise}
  11838. The introduction of garbage collection has a nontrivial impact on our
  11839. compiler passes. We introduce a new compiler pass named
  11840. \code{expose\_allocation} that elaborates the code for allocating
  11841. tuples. We also make significant changes to
  11842. \code{select\_instructions}, \code{build\_interference},
  11843. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11844. make minor changes in several more passes.
  11845. The following program serves as our running example. It creates
  11846. two tuples, one nested inside the other. Both tuples have length
  11847. one. The program accesses the element in the inner tuple.
  11848. % tests/vectors_test_17.rkt
  11849. {\if\edition\racketEd
  11850. \begin{lstlisting}
  11851. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11852. \end{lstlisting}
  11853. \fi}
  11854. {\if\edition\pythonEd\pythonColor
  11855. \begin{lstlisting}
  11856. print( ((42,),)[0][0] )
  11857. \end{lstlisting}
  11858. \fi}
  11859. %% {\if\edition\racketEd
  11860. %% \section{Shrink}
  11861. %% \label{sec:shrink-Lvec}
  11862. %% Recall that the \code{shrink} pass translates the primitives operators
  11863. %% into a smaller set of primitives.
  11864. %% %
  11865. %% This pass comes after type checking, and the type checker adds a
  11866. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11867. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11868. %% \fi}
  11869. \section{Expose Allocation}
  11870. \label{sec:expose-allocation}
  11871. The pass \code{expose\_allocation} lowers tuple creation into making a
  11872. conditional call to the collector followed by allocating the
  11873. appropriate amount of memory and initializing it. We choose to place
  11874. the \code{expose\_allocation} pass before
  11875. \code{remove\_complex\_operands} because it generates
  11876. code that contains complex operands.
  11877. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11878. that replaces tuple creation with new lower-level forms that we use in the
  11879. translation of tuple creation.
  11880. %
  11881. {\if\edition\racketEd
  11882. \[
  11883. \begin{array}{lcl}
  11884. \Exp &::=& \cdots
  11885. \MID (\key{collect} \,\itm{int})
  11886. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11887. \MID (\key{global-value} \,\itm{name})
  11888. \end{array}
  11889. \]
  11890. \fi}
  11891. {\if\edition\pythonEd\pythonColor
  11892. \[
  11893. \begin{array}{lcl}
  11894. \Exp &::=& \cdots\\
  11895. &\MID& \key{collect}(\itm{int})
  11896. \MID \key{allocate}(\itm{int},\itm{type})
  11897. \MID \key{global\_value}(\itm{name}) \\
  11898. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  11899. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11900. \end{array}
  11901. \]
  11902. \fi}
  11903. %
  11904. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11905. make sure that there are $n$ bytes ready to be allocated. During
  11906. instruction selection\index{subject}{instruction selection},
  11907. the \CCOLLECT{$n$} form will become a call to
  11908. the \code{collect} function in \code{runtime.c}.
  11909. %
  11910. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11911. space at the front for the 64-bit tag), but the elements are not
  11912. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11913. of the tuple:
  11914. %
  11915. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11916. %
  11917. where $\Type_i$ is the type of the $i$th element.
  11918. %
  11919. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11920. variable, such as \code{free\_ptr}.
  11921. %
  11922. \python{The \code{begin} form is an expression that executes a
  11923. sequence of statements and then produces the value of the expression
  11924. at the end.}
  11925. \racket{
  11926. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11927. can be obtained by running the
  11928. \code{type-check-Lvec-has-type} type checker immediately before the
  11929. \code{expose\_allocation} pass. This version of the type checker
  11930. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11931. around each tuple creation. The concrete syntax
  11932. for \code{HasType} is \code{has-type}.}
  11933. The following shows the transformation of tuple creation into (1) a
  11934. sequence of temporary variable bindings for the initializing
  11935. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11936. \code{allocate}, and (4) the initialization of the tuple. The
  11937. \itm{len} placeholder refers to the length of the tuple, and
  11938. \itm{bytes} is the total number of bytes that need to be allocated for
  11939. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11940. %
  11941. \python{The \itm{type} needed for the second argument of the
  11942. \code{allocate} form can be obtained from the \code{has\_type} field
  11943. of the tuple AST node, which is stored there by running the type
  11944. checker for \LangVec{} immediately before this pass.}
  11945. %
  11946. \begin{center}
  11947. \begin{minipage}{\textwidth}
  11948. {\if\edition\racketEd
  11949. \begin{lstlisting}
  11950. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11951. |$\Longrightarrow$|
  11952. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11953. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11954. (global-value fromspace_end))
  11955. (void)
  11956. (collect |\itm{bytes}|))])
  11957. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11958. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11959. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11960. |$v$|) ... )))) ...)
  11961. \end{lstlisting}
  11962. \fi}
  11963. {\if\edition\pythonEd\pythonColor
  11964. \begin{lstlisting}
  11965. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11966. |$\Longrightarrow$|
  11967. begin:
  11968. |$x_0$| = |$e_0$|
  11969. |$\vdots$|
  11970. |$x_{n-1}$| = |$e_{n-1}$|
  11971. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11972. 0
  11973. else:
  11974. collect(|\itm{bytes}|)
  11975. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11976. |$v$|[0] = |$x_0$|
  11977. |$\vdots$|
  11978. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11979. |$v$|
  11980. \end{lstlisting}
  11981. \fi}
  11982. \end{minipage}
  11983. \end{center}
  11984. %
  11985. \noindent The sequencing of the initializing expressions
  11986. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  11987. they may trigger garbage collection and we cannot have an allocated
  11988. but uninitialized tuple on the heap during a collection.
  11989. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11990. \code{expose\_allocation} pass on our running example.
  11991. \begin{figure}[tbp]
  11992. \begin{tcolorbox}[colback=white]
  11993. % tests/s2_17.rkt
  11994. {\if\edition\racketEd
  11995. \begin{lstlisting}
  11996. (vector-ref
  11997. (vector-ref
  11998. (let ([vecinit6
  11999. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12000. (global-value fromspace_end))
  12001. (void)
  12002. (collect 16))])
  12003. (let ([alloc2 (allocate 1 (Vector Integer))])
  12004. (let ([_3 (vector-set! alloc2 0 42)])
  12005. alloc2)))])
  12006. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12007. (global-value fromspace_end))
  12008. (void)
  12009. (collect 16))])
  12010. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12011. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12012. alloc5))))
  12013. 0)
  12014. 0)
  12015. \end{lstlisting}
  12016. \fi}
  12017. {\if\edition\pythonEd\pythonColor
  12018. \begin{lstlisting}
  12019. print( |$T_1$|[0][0] )
  12020. \end{lstlisting}
  12021. where $T_1$ is
  12022. \begin{lstlisting}
  12023. begin:
  12024. tmp.1 = |$T_2$|
  12025. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  12026. 0
  12027. else:
  12028. collect(16)
  12029. tmp.2 = allocate(1, TupleType(TupleType([int])))
  12030. tmp.2[0] = tmp.1
  12031. tmp.2
  12032. \end{lstlisting}
  12033. and $T_2$ is
  12034. \begin{lstlisting}
  12035. begin:
  12036. tmp.3 = 42
  12037. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  12038. 0
  12039. else:
  12040. collect(16)
  12041. tmp.4 = allocate(1, TupleType([int]))
  12042. tmp.4[0] = tmp.3
  12043. tmp.4
  12044. \end{lstlisting}
  12045. \fi}
  12046. \end{tcolorbox}
  12047. \caption{Output of the \code{expose\_allocation} pass.}
  12048. \label{fig:expose-alloc-output}
  12049. \end{figure}
  12050. \section{Remove Complex Operands}
  12051. \label{sec:remove-complex-opera-Lvec}
  12052. {\if\edition\racketEd
  12053. %
  12054. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12055. should be treated as complex operands.
  12056. %
  12057. \fi}
  12058. %
  12059. {\if\edition\pythonEd\pythonColor
  12060. %
  12061. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  12062. and tuple access should be treated as complex operands. The
  12063. sub-expressions of tuple access must be atomic.
  12064. %
  12065. \fi}
  12066. %% A new case for
  12067. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12068. %% handled carefully to prevent the \code{Prim} node from being separated
  12069. %% from its enclosing \code{HasType}.
  12070. Figure~\ref{fig:Lvec-anf-syntax}
  12071. shows the grammar for the output language \LangAllocANF{} of this
  12072. pass, which is \LangAlloc{} in monadic normal form.
  12073. \newcommand{\LtupMonadASTRacket}{
  12074. \begin{array}{rcl}
  12075. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12076. \MID \GLOBALVALUE{\Var}
  12077. \end{array}
  12078. }
  12079. \newcommand{\LtupMonadASTPython}{
  12080. \begin{array}{rcl}
  12081. \Exp &::=& \GET{\Atm}{\Atm} \\
  12082. &\MID& \LEN{\Atm}\\
  12083. &\MID& \ALLOCATE{\Int}{\Type}
  12084. \MID \GLOBALVALUE{\Var} \\
  12085. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12086. &\MID& \COLLECT{\Int}
  12087. \end{array}
  12088. }
  12089. \begin{figure}[tp]
  12090. \centering
  12091. \begin{tcolorbox}[colback=white]
  12092. \small
  12093. {\if\edition\racketEd
  12094. \[
  12095. \begin{array}{l}
  12096. \gray{\LvarMonadASTRacket} \\ \hline
  12097. \gray{\LifMonadASTRacket} \\ \hline
  12098. \gray{\LwhileMonadASTRacket} \\ \hline
  12099. \LtupMonadASTRacket \\
  12100. \begin{array}{rcl}
  12101. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12102. \end{array}
  12103. \end{array}
  12104. \]
  12105. \fi}
  12106. {\if\edition\pythonEd\pythonColor
  12107. \[
  12108. \begin{array}{l}
  12109. \gray{\LvarMonadASTPython} \\ \hline
  12110. \gray{\LifMonadASTPython} \\ \hline
  12111. \gray{\LwhileMonadASTPython} \\ \hline
  12112. \LtupMonadASTPython \\
  12113. \begin{array}{rcl}
  12114. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12115. \end{array}
  12116. \end{array}
  12117. \]
  12118. \fi}
  12119. \end{tcolorbox}
  12120. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12121. \label{fig:Lvec-anf-syntax}
  12122. \end{figure}
  12123. \section{Explicate Control and the \LangCVec{} Language}
  12124. \label{sec:explicate-control-r3}
  12125. \newcommand{\CtupASTRacket}{
  12126. \begin{array}{lcl}
  12127. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12128. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12129. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12130. &\MID& \VECLEN{\Atm} \\
  12131. &\MID& \GLOBALVALUE{\Var} \\
  12132. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12133. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12134. \end{array}
  12135. }
  12136. \newcommand{\CtupASTPython}{
  12137. \begin{array}{lcl}
  12138. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12139. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12140. \Stmt &::=& \COLLECT{\Int} \\
  12141. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12142. \end{array}
  12143. }
  12144. \begin{figure}[tp]
  12145. \begin{tcolorbox}[colback=white]
  12146. \small
  12147. {\if\edition\racketEd
  12148. \[
  12149. \begin{array}{l}
  12150. \gray{\CvarASTRacket} \\ \hline
  12151. \gray{\CifASTRacket} \\ \hline
  12152. \gray{\CloopASTRacket} \\ \hline
  12153. \CtupASTRacket \\
  12154. \begin{array}{lcl}
  12155. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12156. \end{array}
  12157. \end{array}
  12158. \]
  12159. \fi}
  12160. {\if\edition\pythonEd\pythonColor
  12161. \[
  12162. \begin{array}{l}
  12163. \gray{\CifASTPython} \\ \hline
  12164. \CtupASTPython \\
  12165. \begin{array}{lcl}
  12166. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  12167. \end{array}
  12168. \end{array}
  12169. \]
  12170. \fi}
  12171. \end{tcolorbox}
  12172. \caption{The abstract syntax of \LangCVec{}, extending
  12173. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12174. (figure~\ref{fig:c1-syntax})}.}
  12175. \label{fig:c2-syntax}
  12176. \end{figure}
  12177. The output of \code{explicate\_control} is a program in the
  12178. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12179. shows the definition of the abstract syntax.
  12180. %
  12181. %% \racket{(The concrete syntax is defined in
  12182. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12183. %
  12184. The new expressions of \LangCVec{} include \key{allocate},
  12185. %
  12186. \racket{\key{vector-ref}, and \key{vector-set!},}
  12187. %
  12188. \python{accessing tuple elements,}
  12189. %
  12190. and \key{global\_value}.
  12191. %
  12192. \python{\LangCVec{} also includes the \code{collect} statement and
  12193. assignment to a tuple element.}
  12194. %
  12195. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12196. %
  12197. The \code{explicate\_control} pass can treat these new forms much like
  12198. the other forms that we've already encountered. The output of the
  12199. \code{explicate\_control} pass on the running example is shown on the
  12200. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12201. section.
  12202. \section{Select Instructions and the \LangXGlobal{} Language}
  12203. \label{sec:select-instructions-gc}
  12204. \index{subject}{select instructions}
  12205. %% void (rep as zero)
  12206. %% allocate
  12207. %% collect (callq collect)
  12208. %% vector-ref
  12209. %% vector-set!
  12210. %% vector-length
  12211. %% global (postpone)
  12212. In this pass we generate x86 code for most of the new operations that
  12213. are needed to compile tuples, including \code{Allocate},
  12214. \code{Collect}, and accessing tuple elements.
  12215. %
  12216. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12217. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12218. \ref{fig:x86-2}). \index{subject}{x86}
  12219. The tuple read and write forms translate into \code{movq}
  12220. instructions. (The $+1$ in the offset serves to move past the tag at the
  12221. beginning of the tuple representation.)
  12222. %
  12223. \begin{center}
  12224. \begin{minipage}{\textwidth}
  12225. {\if\edition\racketEd
  12226. \begin{lstlisting}
  12227. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12228. |$\Longrightarrow$|
  12229. movq |$\itm{tup}'$|, %r11
  12230. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12231. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12232. |$\Longrightarrow$|
  12233. movq |$\itm{tup}'$|, %r11
  12234. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12235. movq $0, |$\itm{lhs'}$|
  12236. \end{lstlisting}
  12237. \fi}
  12238. {\if\edition\pythonEd\pythonColor
  12239. \begin{lstlisting}
  12240. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12241. |$\Longrightarrow$|
  12242. movq |$\itm{tup}'$|, %r11
  12243. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12244. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12245. |$\Longrightarrow$|
  12246. movq |$\itm{tup}'$|, %r11
  12247. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12248. \end{lstlisting}
  12249. \fi}
  12250. \end{minipage}
  12251. \end{center}
  12252. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12253. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12254. are obtained by translating from \LangCVec{} to x86.
  12255. %
  12256. The move of $\itm{tup}'$ to
  12257. register \code{r11} ensures that the offset expression
  12258. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12259. removing \code{r11} from consideration by the register allocating.
  12260. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12261. \code{rax}. Then the generated code for tuple assignment would be
  12262. \begin{lstlisting}
  12263. movq |$\itm{tup}'$|, %rax
  12264. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12265. \end{lstlisting}
  12266. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12267. \code{patch\_instructions} would insert a move through \code{rax}
  12268. as follows:
  12269. \begin{lstlisting}
  12270. movq |$\itm{tup}'$|, %rax
  12271. movq |$\itm{rhs}'$|, %rax
  12272. movq %rax, |$8(n+1)$|(%rax)
  12273. \end{lstlisting}
  12274. However, this sequence of instructions does not work because we're
  12275. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12276. $\itm{rhs}'$) at the same time!
  12277. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12278. be translated into a sequence of instructions that read the tag of the
  12279. tuple and extract the 6 bits that represent the tuple length, which
  12280. are the bits starting at index 1 and going up to and including bit 6.
  12281. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12282. (shift right) can be used to accomplish this.
  12283. We compile the \code{allocate} form to operations on the
  12284. \code{free\_ptr}, as shown next. This approach is called
  12285. \emph{inline allocation} because it implements allocation without a
  12286. function call by simply incrementing the allocation pointer. It is much
  12287. more efficient than calling a function for each allocation. The
  12288. address in the \code{free\_ptr} is the next free address in the
  12289. FromSpace, so we copy it into \code{r11} and then move it forward by
  12290. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12291. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12292. the tag. We then initialize the \itm{tag} and finally copy the
  12293. address in \code{r11} to the left-hand side. Refer to
  12294. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12295. %
  12296. \racket{We recommend using the Racket operations
  12297. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12298. during compilation.}
  12299. %
  12300. \python{We recommend using the bitwise-or operator \code{|} and the
  12301. shift-left operator \code{<<} to compute the tag during
  12302. compilation.}
  12303. %
  12304. The type annotation in the \code{allocate} form is used to determine
  12305. the pointer mask region of the tag.
  12306. %
  12307. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12308. address of the \code{free\_ptr} global variable using a special
  12309. instruction-pointer-relative addressing mode of the x86-64 processor.
  12310. In particular, the assembler computes the distance $d$ between the
  12311. address of \code{free\_ptr} and where the \code{rip} would be at that
  12312. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12313. \code{$d$(\%rip)}, which at runtime will compute the address of
  12314. \code{free\_ptr}.
  12315. %
  12316. {\if\edition\racketEd
  12317. \begin{lstlisting}
  12318. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12319. |$\Longrightarrow$|
  12320. movq free_ptr(%rip), %r11
  12321. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12322. movq $|$\itm{tag}$|, 0(%r11)
  12323. movq %r11, |$\itm{lhs}'$|
  12324. \end{lstlisting}
  12325. \fi}
  12326. {\if\edition\pythonEd\pythonColor
  12327. \begin{lstlisting}
  12328. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12329. |$\Longrightarrow$|
  12330. movq free_ptr(%rip), %r11
  12331. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12332. movq $|$\itm{tag}$|, 0(%r11)
  12333. movq %r11, |$\itm{lhs}'$|
  12334. \end{lstlisting}
  12335. \fi}
  12336. %
  12337. The \code{collect} form is compiled to a call to the \code{collect}
  12338. function in the runtime. The arguments to \code{collect} are (1) the
  12339. top of the root stack, and (2) the number of bytes that need to be
  12340. allocated. We use another dedicated register, \code{r15}, to store
  12341. the pointer to the top of the root stack. Therefore \code{r15} is not
  12342. available for use by the register allocator.
  12343. %
  12344. {\if\edition\racketEd
  12345. \begin{lstlisting}
  12346. (collect |$\itm{bytes}$|)
  12347. |$\Longrightarrow$|
  12348. movq %r15, %rdi
  12349. movq $|\itm{bytes}|, %rsi
  12350. callq collect
  12351. \end{lstlisting}
  12352. \fi}
  12353. {\if\edition\pythonEd\pythonColor
  12354. \begin{lstlisting}
  12355. collect(|$\itm{bytes}$|)
  12356. |$\Longrightarrow$|
  12357. movq %r15, %rdi
  12358. movq $|\itm{bytes}|, %rsi
  12359. callq collect
  12360. \end{lstlisting}
  12361. \fi}
  12362. \newcommand{\GrammarXGlobal}{
  12363. \begin{array}{lcl}
  12364. \Arg &::=& \itm{label} \key{(\%rip)}
  12365. \end{array}
  12366. }
  12367. \newcommand{\ASTXGlobalRacket}{
  12368. \begin{array}{lcl}
  12369. \Arg &::=& \GLOBAL{\itm{label}}
  12370. \end{array}
  12371. }
  12372. \begin{figure}[tp]
  12373. \begin{tcolorbox}[colback=white]
  12374. \[
  12375. \begin{array}{l}
  12376. \gray{\GrammarXInt} \\ \hline
  12377. \gray{\GrammarXIf} \\ \hline
  12378. \GrammarXGlobal \\
  12379. \begin{array}{lcl}
  12380. \LangXGlobalM{} &::= & \key{.globl main} \\
  12381. & & \key{main:} \; \Instr^{*}
  12382. \end{array}
  12383. \end{array}
  12384. \]
  12385. \end{tcolorbox}
  12386. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12387. \label{fig:x86-2-concrete}
  12388. \end{figure}
  12389. \begin{figure}[tp]
  12390. \begin{tcolorbox}[colback=white]
  12391. \small
  12392. \[
  12393. \begin{array}{l}
  12394. \gray{\ASTXIntRacket} \\ \hline
  12395. \gray{\ASTXIfRacket} \\ \hline
  12396. \ASTXGlobalRacket \\
  12397. \begin{array}{lcl}
  12398. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12399. \end{array}
  12400. \end{array}
  12401. \]
  12402. \end{tcolorbox}
  12403. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12404. \label{fig:x86-2}
  12405. \end{figure}
  12406. The definitions of the concrete and abstract syntax of the
  12407. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12408. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12409. of global variables.
  12410. %
  12411. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12412. \code{select\_instructions} pass on the running example.
  12413. \begin{figure}[tbp]
  12414. \centering
  12415. \begin{tcolorbox}[colback=white]
  12416. % tests/s2_17.rkt
  12417. \begin{tabular}{lll}
  12418. \begin{minipage}{0.5\textwidth}
  12419. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12420. start:
  12421. tmp9 = (global-value free_ptr);
  12422. tmp0 = (+ tmp9 16);
  12423. tmp1 = (global-value fromspace_end);
  12424. if (< tmp0 tmp1)
  12425. goto block0;
  12426. else
  12427. goto block1;
  12428. block0:
  12429. _4 = (void);
  12430. goto block9;
  12431. block1:
  12432. (collect 16)
  12433. goto block9;
  12434. block9:
  12435. alloc2 = (allocate 1 (Vector Integer));
  12436. _3 = (vector-set! alloc2 0 42);
  12437. vecinit6 = alloc2;
  12438. tmp2 = (global-value free_ptr);
  12439. tmp3 = (+ tmp2 16);
  12440. tmp4 = (global-value fromspace_end);
  12441. if (< tmp3 tmp4)
  12442. goto block7;
  12443. else
  12444. goto block8;
  12445. block7:
  12446. _8 = (void);
  12447. goto block6;
  12448. block8:
  12449. (collect 16)
  12450. goto block6;
  12451. block6:
  12452. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12453. _7 = (vector-set! alloc5 0 vecinit6);
  12454. tmp5 = (vector-ref alloc5 0);
  12455. return (vector-ref tmp5 0);
  12456. \end{lstlisting}
  12457. \end{minipage}
  12458. &$\Rightarrow$&
  12459. \begin{minipage}{0.4\textwidth}
  12460. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12461. start:
  12462. movq free_ptr(%rip), tmp9
  12463. movq tmp9, tmp0
  12464. addq $16, tmp0
  12465. movq fromspace_end(%rip), tmp1
  12466. cmpq tmp1, tmp0
  12467. jl block0
  12468. jmp block1
  12469. block0:
  12470. movq $0, _4
  12471. jmp block9
  12472. block1:
  12473. movq %r15, %rdi
  12474. movq $16, %rsi
  12475. callq collect
  12476. jmp block9
  12477. block9:
  12478. movq free_ptr(%rip), %r11
  12479. addq $16, free_ptr(%rip)
  12480. movq $3, 0(%r11)
  12481. movq %r11, alloc2
  12482. movq alloc2, %r11
  12483. movq $42, 8(%r11)
  12484. movq $0, _3
  12485. movq alloc2, vecinit6
  12486. movq free_ptr(%rip), tmp2
  12487. movq tmp2, tmp3
  12488. addq $16, tmp3
  12489. movq fromspace_end(%rip), tmp4
  12490. cmpq tmp4, tmp3
  12491. jl block7
  12492. jmp block8
  12493. block7:
  12494. movq $0, _8
  12495. jmp block6
  12496. block8:
  12497. movq %r15, %rdi
  12498. movq $16, %rsi
  12499. callq collect
  12500. jmp block6
  12501. block6:
  12502. movq free_ptr(%rip), %r11
  12503. addq $16, free_ptr(%rip)
  12504. movq $131, 0(%r11)
  12505. movq %r11, alloc5
  12506. movq alloc5, %r11
  12507. movq vecinit6, 8(%r11)
  12508. movq $0, _7
  12509. movq alloc5, %r11
  12510. movq 8(%r11), tmp5
  12511. movq tmp5, %r11
  12512. movq 8(%r11), %rax
  12513. jmp conclusion
  12514. \end{lstlisting}
  12515. \end{minipage}
  12516. \end{tabular}
  12517. \end{tcolorbox}
  12518. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  12519. \code{select\_instructions} (\emph{right}) passes on the running
  12520. example.}
  12521. \label{fig:select-instr-output-gc}
  12522. \end{figure}
  12523. \clearpage
  12524. \section{Register Allocation}
  12525. \label{sec:reg-alloc-gc}
  12526. \index{subject}{register allocation}
  12527. As discussed previously in this chapter, the garbage collector needs to
  12528. access all the pointers in the root set, that is, all variables that
  12529. are tuples. It will be the responsibility of the register allocator
  12530. to make sure that
  12531. \begin{enumerate}
  12532. \item the root stack is used for spilling tuple-typed variables, and
  12533. \item if a tuple-typed variable is live during a call to the
  12534. collector, it must be spilled to ensure that it is visible to the
  12535. collector.
  12536. \end{enumerate}
  12537. The latter responsibility can be handled during construction of the
  12538. interference graph, by adding interference edges between the call-live
  12539. tuple-typed variables and all the callee-saved registers. (They
  12540. already interfere with the caller-saved registers.)
  12541. %
  12542. \racket{The type information for variables is in the \code{Program}
  12543. form, so we recommend adding another parameter to the
  12544. \code{build\_interference} function to communicate this alist.}
  12545. %
  12546. \python{The type information for variables is generated by the type
  12547. checker for \LangCVec{}, stored a field named \code{var\_types} in
  12548. the \code{CProgram} AST mode. You'll need to propagate that
  12549. information so that it is available in this pass.}
  12550. The spilling of tuple-typed variables to the root stack can be handled
  12551. after graph coloring, in choosing how to assign the colors
  12552. (integers) to registers and stack locations. The
  12553. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12554. changes to also record the number of spills to the root stack.
  12555. % build-interference
  12556. %
  12557. % callq
  12558. % extra parameter for var->type assoc. list
  12559. % update 'program' and 'if'
  12560. % allocate-registers
  12561. % allocate spilled vectors to the rootstack
  12562. % don't change color-graph
  12563. % TODO:
  12564. %\section{Patch Instructions}
  12565. %[mention that global variables are memory references]
  12566. \section{Prelude and Conclusion}
  12567. \label{sec:print-x86-gc}
  12568. \label{sec:prelude-conclusion-x86-gc}
  12569. \index{subject}{prelude}\index{subject}{conclusion}
  12570. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12571. \code{prelude\_and\_conclusion} pass on the running example. In the
  12572. prelude of the \code{main} function, we allocate space
  12573. on the root stack to make room for the spills of tuple-typed
  12574. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12575. taking care that the root stack grows up instead of down. For the
  12576. running example, there was just one spill, so we increment \code{r15}
  12577. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12578. One issue that deserves special care is that there may be a call to
  12579. \code{collect} prior to the initializing assignments for all the
  12580. variables in the root stack. We do not want the garbage collector to
  12581. mistakenly determine that some uninitialized variable is a pointer that
  12582. needs to be followed. Thus, we zero out all locations on the root
  12583. stack in the prelude of \code{main}. In
  12584. figure~\ref{fig:print-x86-output-gc}, the instruction
  12585. %
  12586. \lstinline{movq $0, 0(%r15)}
  12587. %
  12588. is sufficient to accomplish this task because there is only one spill.
  12589. In general, we have to clear as many words as there are spills of
  12590. tuple-typed variables. The garbage collector tests each root to see
  12591. if it is null prior to dereferencing it.
  12592. \begin{figure}[htbp]
  12593. % TODO: Python Version -Jeremy
  12594. \begin{tcolorbox}[colback=white]
  12595. \begin{minipage}[t]{0.5\textwidth}
  12596. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12597. .globl main
  12598. main:
  12599. pushq %rbp
  12600. movq %rsp, %rbp
  12601. subq $0, %rsp
  12602. movq $65536, %rdi
  12603. movq $65536, %rsi
  12604. callq initialize
  12605. movq rootstack_begin(%rip), %r15
  12606. movq $0, 0(%r15)
  12607. addq $8, %r15
  12608. jmp start
  12609. conclusion:
  12610. subq $8, %r15
  12611. addq $0, %rsp
  12612. popq %rbp
  12613. retq
  12614. \end{lstlisting}
  12615. \end{minipage}
  12616. \end{tcolorbox}
  12617. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  12618. \label{fig:print-x86-output-gc}
  12619. \end{figure}
  12620. \begin{figure}[tbp]
  12621. \begin{tcolorbox}[colback=white]
  12622. {\if\edition\racketEd
  12623. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12624. \node (Lvec) at (0,2) {\large \LangVec{}};
  12625. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12626. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12627. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12628. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12629. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12630. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12631. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12632. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12633. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12634. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12635. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12636. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12637. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12638. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12639. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12640. \path[->,bend left=15] (Lvec-4) edge [right] node
  12641. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12642. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12643. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12644. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12645. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12646. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12647. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12648. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12649. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12650. \end{tikzpicture}
  12651. \fi}
  12652. {\if\edition\pythonEd\pythonColor
  12653. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12654. \node (Lvec) at (0,2) {\large \LangVec{}};
  12655. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12656. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12657. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12658. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12659. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12660. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12661. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12662. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12663. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12664. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12665. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12666. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12667. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12668. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12669. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12670. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12671. \end{tikzpicture}
  12672. \fi}
  12673. \end{tcolorbox}
  12674. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12675. \label{fig:Lvec-passes}
  12676. \end{figure}
  12677. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12678. for the compilation of \LangVec{}.
  12679. \clearpage
  12680. {\if\edition\racketEd
  12681. \section{Challenge: Simple Structures}
  12682. \label{sec:simple-structures}
  12683. \index{subject}{struct}
  12684. \index{subject}{structure}
  12685. The language \LangStruct{} extends \LangVec{} with support for simple
  12686. structures. The definition of its concrete syntax is shown in
  12687. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12688. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12689. in Typed Racket is a user-defined data type that contains named fields
  12690. and that is heap allocated\index{subject}{heap allocated},
  12691. similarly to a vector. The following is an
  12692. example of a structure definition, in this case the definition of a
  12693. \code{point} type:
  12694. \begin{lstlisting}
  12695. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12696. \end{lstlisting}
  12697. \newcommand{\LstructGrammarRacket}{
  12698. \begin{array}{lcl}
  12699. \Type &::=& \Var \\
  12700. \Exp &::=& (\Var\;\Exp \ldots)\\
  12701. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12702. \end{array}
  12703. }
  12704. \newcommand{\LstructASTRacket}{
  12705. \begin{array}{lcl}
  12706. \Type &::=& \VAR{\Var} \\
  12707. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12708. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12709. \end{array}
  12710. }
  12711. \begin{figure}[tbp]
  12712. \centering
  12713. \begin{tcolorbox}[colback=white]
  12714. \[
  12715. \begin{array}{l}
  12716. \gray{\LintGrammarRacket{}} \\ \hline
  12717. \gray{\LvarGrammarRacket{}} \\ \hline
  12718. \gray{\LifGrammarRacket{}} \\ \hline
  12719. \gray{\LwhileGrammarRacket} \\ \hline
  12720. \gray{\LtupGrammarRacket} \\ \hline
  12721. \LstructGrammarRacket \\
  12722. \begin{array}{lcl}
  12723. \LangStruct{} &::=& \Def \ldots \; \Exp
  12724. \end{array}
  12725. \end{array}
  12726. \]
  12727. \end{tcolorbox}
  12728. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12729. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12730. \label{fig:Lstruct-concrete-syntax}
  12731. \end{figure}
  12732. \begin{figure}[tbp]
  12733. \centering
  12734. \begin{tcolorbox}[colback=white]
  12735. \small
  12736. \[
  12737. \begin{array}{l}
  12738. \gray{\LintASTRacket{}} \\ \hline
  12739. \gray{\LvarASTRacket{}} \\ \hline
  12740. \gray{\LifASTRacket{}} \\ \hline
  12741. \gray{\LwhileASTRacket} \\ \hline
  12742. \gray{\LtupASTRacket} \\ \hline
  12743. \LstructASTRacket \\
  12744. \begin{array}{lcl}
  12745. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12746. \end{array}
  12747. \end{array}
  12748. \]
  12749. \end{tcolorbox}
  12750. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12751. (figure~\ref{fig:Lvec-syntax}).}
  12752. \label{fig:Lstruct-syntax}
  12753. \end{figure}
  12754. An instance of a structure is created using function-call syntax, with
  12755. the name of the structure in the function position, as follows:
  12756. \begin{lstlisting}
  12757. (point 7 12)
  12758. \end{lstlisting}
  12759. Function-call syntax is also used to read a field of a structure. The
  12760. function name is formed by the structure name, a dash, and the field
  12761. name. The following example uses \code{point-x} and \code{point-y} to
  12762. access the \code{x} and \code{y} fields of two point instances:
  12763. \begin{center}
  12764. \begin{lstlisting}
  12765. (let ([pt1 (point 7 12)])
  12766. (let ([pt2 (point 4 3)])
  12767. (+ (- (point-x pt1) (point-x pt2))
  12768. (- (point-y pt1) (point-y pt2)))))
  12769. \end{lstlisting}
  12770. \end{center}
  12771. Similarly, to write to a field of a structure, use its set function,
  12772. whose name starts with \code{set-}, followed by the structure name,
  12773. then a dash, then the field name, and finally with an exclamation
  12774. mark. The following example uses \code{set-point-x!} to change the
  12775. \code{x} field from \code{7} to \code{42}:
  12776. \begin{center}
  12777. \begin{lstlisting}
  12778. (let ([pt (point 7 12)])
  12779. (let ([_ (set-point-x! pt 42)])
  12780. (point-x pt)))
  12781. \end{lstlisting}
  12782. \end{center}
  12783. \begin{exercise}\normalfont\normalsize
  12784. Create a type checker for \LangStruct{} by extending the type
  12785. checker for \LangVec{}. Extend your compiler with support for simple
  12786. structures, compiling \LangStruct{} to x86 assembly code. Create
  12787. five new test cases that use structures, and test your compiler.
  12788. \end{exercise}
  12789. % TODO: create an interpreter for L_struct
  12790. \clearpage
  12791. \fi}
  12792. \section{Challenge: Arrays}
  12793. \label{sec:arrays}
  12794. % TODO mention trapped-error
  12795. In this chapter we have studied tuples, that is, heterogeneous
  12796. sequences of elements whose length is determined at compile time. This
  12797. challenge is also about sequences, but this time the length is
  12798. determined at runtime and all the elements have the same type (they
  12799. are homogeneous). We use the term \emph{array} for this latter kind of
  12800. sequence.
  12801. %
  12802. \racket{
  12803. The Racket language does not distinguish between tuples and arrays;
  12804. they are both represented by vectors. However, Typed Racket
  12805. distinguishes between tuples and arrays: the \code{Vector} type is for
  12806. tuples, and the \code{Vectorof} type is for arrays.}%
  12807. \python{Arrays correspond to the \code{list} type in Python language.}
  12808. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  12809. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  12810. presents the definition of the abstract syntax, extending \LangVec{}
  12811. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  12812. %
  12813. \racket{\code{make-vector} primitive operator for creating an array,
  12814. whose arguments are the length of the array and an initial value for
  12815. all the elements in the array.}
  12816. \python{bracket notation for creating an array literal.}
  12817. \racket{The \code{vector-length},
  12818. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12819. for tuples become overloaded for use with arrays.}
  12820. \python{
  12821. The subscript operator becomes overloaded for use with arrays and tuples
  12822. and now may appear on the left-hand side of an assignment.
  12823. Note that the index of the subscript, when applied to an array, may be an
  12824. arbitrary expression and not just a constant integer.
  12825. The \code{len} function is also applicable to arrays.
  12826. }
  12827. %
  12828. We include integer multiplication in \LangArray{} because it is
  12829. useful in many examples involving arrays such as computing the
  12830. inner product of two arrays (figure~\ref{fig:inner_product}).
  12831. \newcommand{\LarrayGrammarRacket}{
  12832. \begin{array}{lcl}
  12833. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12834. \Exp &::=& \CMUL{\Exp}{\Exp}
  12835. \MID \CMAKEVEC{\Exp}{\Exp}
  12836. \end{array}
  12837. }
  12838. \newcommand{\LarrayASTRacket}{
  12839. \begin{array}{lcl}
  12840. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12841. \Exp &::=& \MUL{\Exp}{\Exp}
  12842. \MID \MAKEVEC{\Exp}{\Exp}
  12843. \end{array}
  12844. }
  12845. \newcommand{\LarrayGrammarPython}{
  12846. \begin{array}{lcl}
  12847. \Type &::=& \key{list}\LS\Type\RS \\
  12848. \Exp &::=& \CMUL{\Exp}{\Exp}
  12849. \MID \CGET{\Exp}{\Exp}
  12850. \MID \LS \Exp \code{,} \ldots \RS \\
  12851. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  12852. \end{array}
  12853. }
  12854. \newcommand{\LarrayASTPython}{
  12855. \begin{array}{lcl}
  12856. \Type &::=& \key{ListType}\LP\Type\RP \\
  12857. \Exp &::=& \MUL{\Exp}{\Exp}
  12858. \MID \GET{\Exp}{\Exp} \\
  12859. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  12860. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  12861. \end{array}
  12862. }
  12863. \begin{figure}[tp]
  12864. \centering
  12865. \begin{tcolorbox}[colback=white]
  12866. \small
  12867. {\if\edition\racketEd
  12868. \[
  12869. \begin{array}{l}
  12870. \gray{\LintGrammarRacket{}} \\ \hline
  12871. \gray{\LvarGrammarRacket{}} \\ \hline
  12872. \gray{\LifGrammarRacket{}} \\ \hline
  12873. \gray{\LwhileGrammarRacket} \\ \hline
  12874. \gray{\LtupGrammarRacket} \\ \hline
  12875. \LarrayGrammarRacket \\
  12876. \begin{array}{lcl}
  12877. \LangArray{} &::=& \Exp
  12878. \end{array}
  12879. \end{array}
  12880. \]
  12881. \fi}
  12882. {\if\edition\pythonEd\pythonColor
  12883. \[
  12884. \begin{array}{l}
  12885. \gray{\LintGrammarPython{}} \\ \hline
  12886. \gray{\LvarGrammarPython{}} \\ \hline
  12887. \gray{\LifGrammarPython{}} \\ \hline
  12888. \gray{\LwhileGrammarPython} \\ \hline
  12889. \gray{\LtupGrammarPython} \\ \hline
  12890. \LarrayGrammarPython \\
  12891. \begin{array}{rcl}
  12892. \LangArrayM{} &::=& \Stmt^{*}
  12893. \end{array}
  12894. \end{array}
  12895. \]
  12896. \fi}
  12897. \end{tcolorbox}
  12898. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12899. \label{fig:Lvecof-concrete-syntax}
  12900. \end{figure}
  12901. \begin{figure}[tp]
  12902. \centering
  12903. \begin{tcolorbox}[colback=white]
  12904. \small
  12905. {\if\edition\racketEd
  12906. \[
  12907. \begin{array}{l}
  12908. \gray{\LintASTRacket{}} \\ \hline
  12909. \gray{\LvarASTRacket{}} \\ \hline
  12910. \gray{\LifASTRacket{}} \\ \hline
  12911. \gray{\LwhileASTRacket} \\ \hline
  12912. \gray{\LtupASTRacket} \\ \hline
  12913. \LarrayASTRacket \\
  12914. \begin{array}{lcl}
  12915. \LangArray{} &::=& \Exp
  12916. \end{array}
  12917. \end{array}
  12918. \]
  12919. \fi}
  12920. {\if\edition\pythonEd\pythonColor
  12921. \[
  12922. \begin{array}{l}
  12923. \gray{\LintASTPython{}} \\ \hline
  12924. \gray{\LvarASTPython{}} \\ \hline
  12925. \gray{\LifASTPython{}} \\ \hline
  12926. \gray{\LwhileASTPython} \\ \hline
  12927. \gray{\LtupASTPython} \\ \hline
  12928. \LarrayASTPython \\
  12929. \begin{array}{rcl}
  12930. \LangArrayM{} &::=& \Stmt^{*}
  12931. \end{array}
  12932. \end{array}
  12933. \]
  12934. \fi}
  12935. \end{tcolorbox}
  12936. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12937. \label{fig:Lvecof-syntax}
  12938. \end{figure}
  12939. \begin{figure}[tp]
  12940. \begin{tcolorbox}[colback=white]
  12941. {\if\edition\racketEd
  12942. % TODO: remove the function from the following example, like the python version -Jeremy
  12943. \begin{lstlisting}
  12944. (let ([A (make-vector 2 2)])
  12945. (let ([B (make-vector 2 3)])
  12946. (let ([i 0])
  12947. (let ([prod 0])
  12948. (begin
  12949. (while (< i n)
  12950. (begin
  12951. (set! prod (+ prod (* (vector-ref A i)
  12952. (vector-ref B i))))
  12953. (set! i (+ i 1))))
  12954. prod)))))
  12955. \end{lstlisting}
  12956. \fi}
  12957. {\if\edition\pythonEd\pythonColor
  12958. \begin{lstlisting}
  12959. A = [2, 2]
  12960. B = [3, 3]
  12961. i = 0
  12962. prod = 0
  12963. while i != len(A):
  12964. prod = prod + A[i] * B[i]
  12965. i = i + 1
  12966. print( prod )
  12967. \end{lstlisting}
  12968. \fi}
  12969. \end{tcolorbox}
  12970. \caption{Example program that computes the inner product.}
  12971. \label{fig:inner_product}
  12972. \end{figure}
  12973. {\if\edition\racketEd
  12974. %
  12975. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12976. checker for \LangArray{}. The result type of
  12977. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12978. of the initializing expression. The length expression is required to
  12979. have type \code{Integer}. The type checking of the operators
  12980. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12981. updated to handle the situation in which the vector has type
  12982. \code{Vectorof}. In these cases we translate the operators to their
  12983. \code{vectorof} form so that later passes can easily distinguish
  12984. between operations on tuples versus arrays. We override the
  12985. \code{operator-types} method to provide the type signature for
  12986. multiplication: it takes two integers and returns an integer. \fi}
  12987. {\if\edition\pythonEd\pythonColor
  12988. %
  12989. The type checker for \LangArray{} is defined in
  12990. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12991. is \code{list[T]} where \code{T} is the type of the initializing
  12992. expressions. The type checking of the \code{len} function and the
  12993. subscript operator is updated to handle lists. The type checker now
  12994. also handles a subscript on the left-hand side of an assignment.
  12995. Regarding multiplication, it takes two integers and returns an
  12996. integer.
  12997. %
  12998. \fi}
  12999. \begin{figure}[tbp]
  13000. \begin{tcolorbox}[colback=white]
  13001. {\if\edition\racketEd
  13002. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13003. (define type-check-Lvecof-class
  13004. (class type-check-Lvec-class
  13005. (super-new)
  13006. (inherit check-type-equal?)
  13007. (define/override (operator-types)
  13008. (append '((* . ((Integer Integer) . Integer)))
  13009. (super operator-types)))
  13010. (define/override (type-check-exp env)
  13011. (lambda (e)
  13012. (define recur (type-check-exp env))
  13013. (match e
  13014. [(Prim 'make-vector (list e1 e2))
  13015. (define-values (e1^ t1) (recur e1))
  13016. (define-values (e2^ elt-type) (recur e2))
  13017. (define vec-type `(Vectorof ,elt-type))
  13018. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13019. [(Prim 'vector-ref (list e1 e2))
  13020. (define-values (e1^ t1) (recur e1))
  13021. (define-values (e2^ t2) (recur e2))
  13022. (match* (t1 t2)
  13023. [(`(Vectorof ,elt-type) 'Integer)
  13024. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13025. [(other wise) ((super type-check-exp env) e)])]
  13026. [(Prim 'vector-set! (list e1 e2 e3) )
  13027. (define-values (e-vec t-vec) (recur e1))
  13028. (define-values (e2^ t2) (recur e2))
  13029. (define-values (e-arg^ t-arg) (recur e3))
  13030. (match t-vec
  13031. [`(Vectorof ,elt-type)
  13032. (check-type-equal? elt-type t-arg e)
  13033. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13034. [else ((super type-check-exp env) e)])]
  13035. [(Prim 'vector-length (list e1))
  13036. (define-values (e1^ t1) (recur e1))
  13037. (match t1
  13038. [`(Vectorof ,t)
  13039. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13040. [else ((super type-check-exp env) e)])]
  13041. [else ((super type-check-exp env) e)])))
  13042. ))
  13043. (define (type-check-Lvecof p)
  13044. (send (new type-check-Lvecof-class) type-check-program p))
  13045. \end{lstlisting}
  13046. \fi}
  13047. {\if\edition\pythonEd\pythonColor
  13048. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13049. class TypeCheckLarray(TypeCheckLtup):
  13050. def type_check_exp(self, e, env):
  13051. match e:
  13052. case ast.List(es, Load()):
  13053. ts = [self.type_check_exp(e, env) for e in es]
  13054. elt_ty = ts[0]
  13055. for (ty, elt) in zip(ts, es):
  13056. self.check_type_equal(elt_ty, ty, elt)
  13057. e.has_type = ListType(elt_ty)
  13058. return e.has_type
  13059. case Call(Name('len'), [tup]):
  13060. tup_t = self.type_check_exp(tup, env)
  13061. tup.has_type = tup_t
  13062. match tup_t:
  13063. case TupleType(ts):
  13064. return IntType()
  13065. case ListType(ty):
  13066. return IntType()
  13067. case _:
  13068. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13069. case Subscript(tup, index, Load()):
  13070. tup_ty = self.type_check_exp(tup, env)
  13071. index_ty = self.type_check_exp(index, env)
  13072. self.check_type_equal(index_ty, IntType(), index)
  13073. match tup_ty:
  13074. case TupleType(ts):
  13075. match index:
  13076. case Constant(i):
  13077. return ts[i]
  13078. case _:
  13079. raise Exception('subscript required constant integer index')
  13080. case ListType(ty):
  13081. return ty
  13082. case _:
  13083. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13084. case BinOp(left, Mult(), right):
  13085. l = self.type_check_exp(left, env)
  13086. self.check_type_equal(l, IntType(), left)
  13087. r = self.type_check_exp(right, env)
  13088. self.check_type_equal(r, IntType(), right)
  13089. return IntType()
  13090. case _:
  13091. return super().type_check_exp(e, env)
  13092. def type_check_stmts(self, ss, env):
  13093. if len(ss) == 0:
  13094. return VoidType()
  13095. match ss[0]:
  13096. case Assign([Subscript(tup, index, Store())], value):
  13097. tup_t = self.type_check_exp(tup, env)
  13098. value_t = self.type_check_exp(value, env)
  13099. index_ty = self.type_check_exp(index, env)
  13100. self.check_type_equal(index_ty, IntType(), index)
  13101. match tup_t:
  13102. case ListType(ty):
  13103. self.check_type_equal(ty, value_t, ss[0])
  13104. case TupleType(ts):
  13105. return self.type_check_stmts(ss, env)
  13106. case _:
  13107. raise Exception('type_check_stmts: '
  13108. 'expected tuple or list, not ' + repr(tup_t))
  13109. return self.type_check_stmts(ss[1:], env)
  13110. case _:
  13111. return super().type_check_stmts(ss, env)
  13112. \end{lstlisting}
  13113. \fi}
  13114. \end{tcolorbox}
  13115. \caption{Type checker for the \LangArray{} language.}
  13116. \label{fig:type-check-Lvecof}
  13117. \end{figure}
  13118. The definition of the interpreter for \LangArray{} is shown in
  13119. figure~\ref{fig:interp-Lvecof}.
  13120. \racket{The \code{make-vector} operator is
  13121. interpreted using Racket's \code{make-vector} function,
  13122. and multiplication is interpreted using \code{fx*},
  13123. which is multiplication for \code{fixnum} integers.
  13124. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13125. we translate array access operations
  13126. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13127. which we interpret using \code{vector} operations with additional
  13128. bounds checks that signal a \code{trapped-error}.
  13129. }
  13130. %
  13131. \python{We implement list creation with a Python list comprehension
  13132. and multiplication is implemented with Python multiplication. We
  13133. add a case to handle a subscript on the left-hand side of
  13134. assignment. Other uses of subscript can be handled by the existing
  13135. code for tuples.}
  13136. \begin{figure}[tbp]
  13137. \begin{tcolorbox}[colback=white]
  13138. {\if\edition\racketEd
  13139. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13140. (define interp-Lvecof-class
  13141. (class interp-Lvec-class
  13142. (super-new)
  13143. (define/override (interp-op op)
  13144. (match op
  13145. ['make-vector make-vector]
  13146. ['vectorof-length vector-length]
  13147. ['vectorof-ref
  13148. (lambda (v i)
  13149. (if (< i (vector-length v))
  13150. (vector-ref v i)
  13151. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13152. ['vectorof-set!
  13153. (lambda (v i e)
  13154. (if (< i (vector-length v))
  13155. (vector-set! v i e)
  13156. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13157. [else (super interp-op op)]))
  13158. ))
  13159. (define (interp-Lvecof p)
  13160. (send (new interp-Lvecof-class) interp-program p))
  13161. \end{lstlisting}
  13162. \fi}
  13163. {\if\edition\pythonEd\pythonColor
  13164. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13165. class InterpLarray(InterpLtup):
  13166. def interp_exp(self, e, env):
  13167. match e:
  13168. case ast.List(es, Load()):
  13169. return [self.interp_exp(e, env) for e in es]
  13170. case BinOp(left, Mult(), right):
  13171. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  13172. return l * r
  13173. case Subscript(tup, index, Load()):
  13174. t = self.interp_exp(tup, env)
  13175. n = self.interp_exp(index, env)
  13176. if n < len(t):
  13177. return t[n]
  13178. else:
  13179. raise TrappedError('array index out of bounds')
  13180. case _:
  13181. return super().interp_exp(e, env)
  13182. def interp_stmt(self, s, env, cont):
  13183. match s:
  13184. case Assign([Subscript(tup, index)], value):
  13185. t = self.interp_exp(tup, env)
  13186. n = self.interp_exp(index, env)
  13187. if n < len(t):
  13188. t[n] = self.interp_exp(value, env)
  13189. else:
  13190. raise TrappedError('array index out of bounds')
  13191. return self.interp_stmts(cont, env)
  13192. case _:
  13193. return super().interp_stmt(s, env, cont)
  13194. \end{lstlisting}
  13195. \fi}
  13196. \end{tcolorbox}
  13197. \caption{Interpreter for \LangArray{}.}
  13198. \label{fig:interp-Lvecof}
  13199. \end{figure}
  13200. \subsection{Data Representation}
  13201. \label{sec:array-rep}
  13202. Just as with tuples, we store arrays on the heap, which means that the
  13203. garbage collector will need to inspect arrays. An immediate thought is
  13204. to use the same representation for arrays that we use for tuples.
  13205. However, we limit tuples to a length of fifty so that their length and
  13206. pointer mask can fit into the 64-bit tag at the beginning of each
  13207. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13208. millions of elements, so we need more bits to store the length.
  13209. However, because arrays are homogeneous, we need only 1 bit for the
  13210. pointer mask instead of 1 bit per array element. Finally, the
  13211. garbage collector must be able to distinguish between tuples
  13212. and arrays, so we need to reserve one bit for that purpose. We
  13213. arrive at the following layout for the 64-bit tag at the beginning of
  13214. an array:
  13215. \begin{itemize}
  13216. \item The right-most bit is the forwarding bit, just as in a tuple.
  13217. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13218. that it is not.
  13219. \item The next bit to the left is the pointer mask. A $0$ indicates
  13220. that none of the elements are pointers to the heap, and a $1$
  13221. indicates that all the elements are pointers.
  13222. \item The next $60$ bits store the length of the array.
  13223. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13224. and an array ($1$).
  13225. \item The left-most bit is reserved as explained in
  13226. chapter~\ref{ch:Lgrad}.
  13227. \end{itemize}
  13228. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13229. %% differentiate the kinds of values that have been injected into the
  13230. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13231. %% to indicate that the value is an array.
  13232. In the following subsections we provide hints regarding how to update
  13233. the passes to handle arrays.
  13234. \subsection{Overload Resolution}
  13235. \label{sec:array-resolution}
  13236. As noted previously, with the addition of arrays, several operators
  13237. have become \emph{overloaded}; that is, they can be applied to values
  13238. of more than one type. In this case, the element access and length
  13239. operators can be applied to both tuples and arrays. This kind of
  13240. overloading is quite common in programming languages, so many
  13241. compilers perform \emph{overload resolution}\index{subject}{overload
  13242. resolution} to handle it. The idea is to translate each overloaded
  13243. operator into different operators for the different types.
  13244. Implement a new pass named \code{resolve}.
  13245. Translate the reading of an array element
  13246. into a call to
  13247. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13248. and the writing of an array element to
  13249. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13250. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13251. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13252. When these operators are applied to tuples, leave them as is.
  13253. %
  13254. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13255. field which can be inspected to determine whether the operator
  13256. is applied to a tuple or an array.}
  13257. \subsection{Bounds Checking}
  13258. Recall that the interpreter for \LangArray{} signals a
  13259. \code{trapped-error} when there is an array access that is out of
  13260. bounds. Therefore your compiler is obliged to also catch these errors
  13261. during execution and halt, signaling an error. We recommend inserting
  13262. a new pass named \code{check\_bounds} that inserts code around each
  13263. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13264. \python{subscript} operation to ensure that the index is greater than
  13265. or equal to zero and less than the array's length. If not, the program
  13266. should halt, for which we recommend using a new primitive operation
  13267. named \code{exit}.
  13268. %% \subsection{Reveal Casts}
  13269. %% The array-access operators \code{vectorof-ref} and
  13270. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13271. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13272. %% that the type checker cannot tell whether the index will be in bounds,
  13273. %% so the bounds check must be performed at run time. Recall that the
  13274. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13275. %% an \code{If} around a vector reference for update to check whether
  13276. %% the index is less than the length. You should do the same for
  13277. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13278. %% In addition, the handling of the \code{any-vector} operators in
  13279. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13280. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13281. %% generated code should test whether the tag is for tuples (\code{010})
  13282. %% or arrays (\code{110}) and then dispatch to either
  13283. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13284. %% we add a case in \code{select\_instructions} to generate the
  13285. %% appropriate instructions for accessing the array length from the
  13286. %% header of an array.
  13287. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13288. %% the generated code needs to check that the index is less than the
  13289. %% vector length, so like the code for \code{any-vector-length}, check
  13290. %% the tag to determine whether to use \code{any-vector-length} or
  13291. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13292. %% is complete, the generated code can use \code{any-vector-ref} and
  13293. %% \code{any-vector-set!} for both tuples and arrays because the
  13294. %% instructions used for those operators do not look at the tag at the
  13295. %% front of the tuple or array.
  13296. \subsection{Expose Allocation}
  13297. This pass should translate array creation into lower-level
  13298. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13299. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13300. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13301. array. The \code{AllocateArray} AST node allocates an array of the
  13302. length specified by the $\Exp$ (of type \INTTY), but does not
  13303. initialize the elements of the array. Generate code in this pass to
  13304. initialize the elements analogous to the case for tuples.
  13305. {\if\edition\racketEd
  13306. \section{Uncover \texttt{get!}}
  13307. \label{sec:uncover-get-bang-vecof}
  13308. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13309. \code{uncover-get!-exp}.
  13310. \fi}
  13311. \subsection{Remove Complex Operands}
  13312. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13313. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13314. complex, and its subexpression must be atomic.
  13315. \subsection{Explicate Control}
  13316. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13317. \code{explicate\_assign}.
  13318. \subsection{Select Instructions}
  13319. \index{subject}{select instructions}
  13320. Generate instructions for \code{AllocateArray} similar to those for
  13321. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13322. except that the tag at the front of the array should instead use the
  13323. representation discussed in section~\ref{sec:array-rep}.
  13324. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13325. extract the length from the tag.
  13326. The instructions generated for accessing an element of an array differ
  13327. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13328. that the index is not a constant so you need to generate instructions
  13329. that compute the offset at runtime.
  13330. Compile the \code{exit} primitive into a call to the \code{exit}
  13331. function of the C standard library, with an argument of $255$.
  13332. %% Also, note that assignment to an array element may appear in
  13333. %% as a stand-alone statement, so make sure to handle that situation in
  13334. %% this pass.
  13335. %% Finally, the instructions for \code{any-vectorof-length} should be
  13336. %% similar to those for \code{vectorof-length}, except that one must
  13337. %% first project the array by writing zeroes into the $3$-bit tag
  13338. \begin{exercise}\normalfont\normalsize
  13339. Implement a compiler for the \LangArray{} language by extending your
  13340. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13341. programs, including the one shown in figure~\ref{fig:inner_product}
  13342. and also a program that multiplies two matrices. Note that although
  13343. matrices are two-dimensional arrays, they can be encoded into
  13344. one-dimensional arrays by laying out each row in the array, one after
  13345. the next.
  13346. \end{exercise}
  13347. {\if\edition\racketEd
  13348. \section{Challenge: Generational Collection}
  13349. The copying collector described in section~\ref{sec:GC} can incur
  13350. significant runtime overhead because the call to \code{collect} takes
  13351. time proportional to all the live data. One way to reduce this
  13352. overhead is to reduce how much data is inspected in each call to
  13353. \code{collect}. In particular, researchers have observed that recently
  13354. allocated data is more likely to become garbage then data that has
  13355. survived one or more previous calls to \code{collect}. This insight
  13356. motivated the creation of \emph{generational garbage collectors}
  13357. \index{subject}{generational garbage collector} that
  13358. (1) segregate data according to its age into two or more generations;
  13359. (2) allocate less space for younger generations, so collecting them is
  13360. faster, and more space for the older generations; and (3) perform
  13361. collection on the younger generations more frequently than on older
  13362. generations~\citep{Wilson:1992fk}.
  13363. For this challenge assignment, the goal is to adapt the copying
  13364. collector implemented in \code{runtime.c} to use two generations, one
  13365. for young data and one for old data. Each generation consists of a
  13366. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13367. \code{collect} function to use the two generations:
  13368. \begin{enumerate}
  13369. \item Copy the young generation's FromSpace to its ToSpace and then
  13370. switch the role of the ToSpace and FromSpace.
  13371. \item If there is enough space for the requested number of bytes in
  13372. the young FromSpace, then return from \code{collect}.
  13373. \item If there is not enough space in the young FromSpace for the
  13374. requested bytes, then move the data from the young generation to the
  13375. old one with the following steps:
  13376. \begin{enumerate}
  13377. \item[a.] If there is enough room in the old FromSpace, copy the young
  13378. FromSpace to the old FromSpace and then return.
  13379. \item[b.] If there is not enough room in the old FromSpace, then collect
  13380. the old generation by copying the old FromSpace to the old ToSpace
  13381. and swap the roles of the old FromSpace and ToSpace.
  13382. \item[c.] If there is enough room now, copy the young FromSpace to the
  13383. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13384. and ToSpace for the old generation. Copy the young FromSpace and
  13385. the old FromSpace into the larger FromSpace for the old
  13386. generation and then return.
  13387. \end{enumerate}
  13388. \end{enumerate}
  13389. We recommend that you generalize the \code{cheney} function so that it
  13390. can be used for all the copies mentioned: between the young FromSpace
  13391. and ToSpace, between the old FromSpace and ToSpace, and between the
  13392. young FromSpace and old FromSpace. This can be accomplished by adding
  13393. parameters to \code{cheney} that replace its use of the global
  13394. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13395. \code{tospace\_begin}, and \code{tospace\_end}.
  13396. Note that the collection of the young generation does not traverse the
  13397. old generation. This introduces a potential problem: there may be
  13398. young data that is reachable only through pointers in the old
  13399. generation. If these pointers are not taken into account, the
  13400. collector could throw away young data that is live! One solution,
  13401. called \emph{pointer recording}, is to maintain a set of all the
  13402. pointers from the old generation into the new generation and consider
  13403. this set as part of the root set. To maintain this set, the compiler
  13404. must insert extra instructions around every \code{vector-set!}. If the
  13405. vector being modified is in the old generation, and if the value being
  13406. written is a pointer into the new generation, then that pointer must
  13407. be added to the set. Also, if the value being overwritten was a
  13408. pointer into the new generation, then that pointer should be removed
  13409. from the set.
  13410. \begin{exercise}\normalfont\normalsize
  13411. Adapt the \code{collect} function in \code{runtime.c} to implement
  13412. generational garbage collection, as outlined in this section.
  13413. Update the code generation for \code{vector-set!} to implement
  13414. pointer recording. Make sure that your new compiler and runtime
  13415. execute without error on your test suite.
  13416. \end{exercise}
  13417. \fi}
  13418. \section{Further Reading}
  13419. \citet{Appel90} describes many data representation approaches
  13420. including the ones used in the compilation of Standard ML.
  13421. There are many alternatives to copying collectors (and their bigger
  13422. siblings, the generational collectors) with regard to garbage
  13423. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13424. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13425. collectors are that allocation is fast (just a comparison and pointer
  13426. increment), there is no fragmentation, cyclic garbage is collected,
  13427. and the time complexity of collection depends only on the amount of
  13428. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13429. main disadvantages of a two-space copying collector is that it uses a
  13430. lot of extra space and takes a long time to perform the copy, though
  13431. these problems are ameliorated in generational collectors.
  13432. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13433. small objects and generate a lot of garbage, so copying and
  13434. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13435. Garbage collection is an active research topic, especially concurrent
  13436. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13437. developing new techniques and revisiting old
  13438. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13439. meet every year at the International Symposium on Memory Management to
  13440. present these findings.
  13441. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13442. \chapter{Functions}
  13443. \label{ch:Lfun}
  13444. \index{subject}{function}
  13445. \setcounter{footnote}{0}
  13446. This chapter studies the compilation of a subset of \racket{Typed
  13447. Racket}\python{Python} in which only top-level function definitions
  13448. are allowed. This kind of function appears in the C programming
  13449. language, and it serves as an important stepping-stone to implementing
  13450. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13451. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13452. \section{The \LangFun{} Language}
  13453. The concrete syntax and abstract syntax for function definitions and
  13454. function application are shown in
  13455. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13456. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13457. with zero or more function definitions. The function names from these
  13458. definitions are in scope for the entire program, including all the
  13459. function definitions, and therefore the ordering of function
  13460. definitions does not matter.
  13461. %
  13462. \python{The abstract syntax for function parameters in
  13463. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  13464. consists of a parameter name and its type. This design differs from
  13465. Python's \code{ast} module, which has a more complex structure for
  13466. function parameters to handle keyword parameters,
  13467. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13468. complex Python abstract syntax into the simpler syntax of
  13469. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13470. \code{FunctionDef} constructor are for decorators and a type
  13471. comment, neither of which are used by our compiler. We recommend
  13472. replacing them with \code{None} in the \code{shrink} pass.
  13473. }
  13474. %
  13475. The concrete syntax for function application
  13476. \index{subject}{function application}
  13477. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13478. where the first expression
  13479. must evaluate to a function and the remaining expressions are the arguments. The
  13480. abstract syntax for function application is
  13481. $\APPLY{\Exp}{\Exp^*}$.
  13482. %% The syntax for function application does not include an explicit
  13483. %% keyword, which is error prone when using \code{match}. To alleviate
  13484. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13485. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13486. Functions are first-class in the sense that a function pointer
  13487. \index{subject}{function pointer} is data and can be stored in memory or passed
  13488. as a parameter to another function. Thus, there is a function
  13489. type, written
  13490. {\if\edition\racketEd
  13491. \begin{lstlisting}
  13492. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13493. \end{lstlisting}
  13494. \fi}
  13495. {\if\edition\pythonEd\pythonColor
  13496. \begin{lstlisting}
  13497. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13498. \end{lstlisting}
  13499. \fi}
  13500. %
  13501. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13502. through $\Type_n$ and whose return type is $\Type_R$. The main
  13503. limitation of these functions (with respect to
  13504. \racket{Racket}\python{Python} functions) is that they are not
  13505. lexically scoped. That is, the only external entities that can be
  13506. referenced from inside a function body are other globally defined
  13507. functions. The syntax of \LangFun{} prevents function definitions from
  13508. being nested inside each other.
  13509. \newcommand{\LfunGrammarRacket}{
  13510. \begin{array}{lcl}
  13511. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13512. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13513. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13514. \end{array}
  13515. }
  13516. \newcommand{\LfunASTRacket}{
  13517. \begin{array}{lcl}
  13518. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13519. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13520. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13521. \end{array}
  13522. }
  13523. \newcommand{\LfunGrammarPython}{
  13524. \begin{array}{lcl}
  13525. \Type &::=& \key{int}
  13526. \MID \key{bool} \MID \key{void}
  13527. \MID \key{tuple}\LS \Type^+ \RS
  13528. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13529. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13530. \Stmt &::=& \CRETURN{\Exp} \\
  13531. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13532. \end{array}
  13533. }
  13534. \newcommand{\LfunASTPython}{
  13535. \begin{array}{lcl}
  13536. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13537. \MID \key{TupleType}\LS\Type^+\RS\\
  13538. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13539. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13540. \Stmt &::=& \RETURN{\Exp} \\
  13541. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13542. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13543. \end{array}
  13544. }
  13545. \begin{figure}[tp]
  13546. \centering
  13547. \begin{tcolorbox}[colback=white]
  13548. \small
  13549. {\if\edition\racketEd
  13550. \[
  13551. \begin{array}{l}
  13552. \gray{\LintGrammarRacket{}} \\ \hline
  13553. \gray{\LvarGrammarRacket{}} \\ \hline
  13554. \gray{\LifGrammarRacket{}} \\ \hline
  13555. \gray{\LwhileGrammarRacket} \\ \hline
  13556. \gray{\LtupGrammarRacket} \\ \hline
  13557. \LfunGrammarRacket \\
  13558. \begin{array}{lcl}
  13559. \LangFunM{} &::=& \Def \ldots \; \Exp
  13560. \end{array}
  13561. \end{array}
  13562. \]
  13563. \fi}
  13564. {\if\edition\pythonEd\pythonColor
  13565. \[
  13566. \begin{array}{l}
  13567. \gray{\LintGrammarPython{}} \\ \hline
  13568. \gray{\LvarGrammarPython{}} \\ \hline
  13569. \gray{\LifGrammarPython{}} \\ \hline
  13570. \gray{\LwhileGrammarPython} \\ \hline
  13571. \gray{\LtupGrammarPython} \\ \hline
  13572. \LfunGrammarPython \\
  13573. \begin{array}{rcl}
  13574. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13575. \end{array}
  13576. \end{array}
  13577. \]
  13578. \fi}
  13579. \end{tcolorbox}
  13580. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13581. \label{fig:Lfun-concrete-syntax}
  13582. \end{figure}
  13583. \begin{figure}[tp]
  13584. \centering
  13585. \begin{tcolorbox}[colback=white]
  13586. \small
  13587. {\if\edition\racketEd
  13588. \[
  13589. \begin{array}{l}
  13590. \gray{\LintOpAST} \\ \hline
  13591. \gray{\LvarASTRacket{}} \\ \hline
  13592. \gray{\LifASTRacket{}} \\ \hline
  13593. \gray{\LwhileASTRacket{}} \\ \hline
  13594. \gray{\LtupASTRacket{}} \\ \hline
  13595. \LfunASTRacket \\
  13596. \begin{array}{lcl}
  13597. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13598. \end{array}
  13599. \end{array}
  13600. \]
  13601. \fi}
  13602. {\if\edition\pythonEd\pythonColor
  13603. \[
  13604. \begin{array}{l}
  13605. \gray{\LintASTPython{}} \\ \hline
  13606. \gray{\LvarASTPython{}} \\ \hline
  13607. \gray{\LifASTPython{}} \\ \hline
  13608. \gray{\LwhileASTPython} \\ \hline
  13609. \gray{\LtupASTPython} \\ \hline
  13610. \LfunASTPython \\
  13611. \begin{array}{rcl}
  13612. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13613. \end{array}
  13614. \end{array}
  13615. \]
  13616. \fi}
  13617. \end{tcolorbox}
  13618. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13619. \label{fig:Lfun-syntax}
  13620. \end{figure}
  13621. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13622. representative example of defining and using functions in \LangFun{}.
  13623. We define a function \code{map} that applies some other function
  13624. \code{f} to both elements of a tuple and returns a new tuple
  13625. containing the results. We also define a function \code{inc}. The
  13626. program applies \code{map} to \code{inc} and
  13627. %
  13628. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13629. %
  13630. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13631. %
  13632. from which we return \code{42}.
  13633. \begin{figure}[tbp]
  13634. \begin{tcolorbox}[colback=white]
  13635. {\if\edition\racketEd
  13636. \begin{lstlisting}
  13637. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13638. : (Vector Integer Integer)
  13639. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13640. (define (inc [x : Integer]) : Integer
  13641. (+ x 1))
  13642. (vector-ref (map inc (vector 0 41)) 1)
  13643. \end{lstlisting}
  13644. \fi}
  13645. {\if\edition\pythonEd\pythonColor
  13646. \begin{lstlisting}
  13647. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13648. return f(v[0]), f(v[1])
  13649. def inc(x : int) -> int:
  13650. return x + 1
  13651. print( map(inc, (0, 41))[1] )
  13652. \end{lstlisting}
  13653. \fi}
  13654. \end{tcolorbox}
  13655. \caption{Example of using functions in \LangFun{}.}
  13656. \label{fig:Lfun-function-example}
  13657. \end{figure}
  13658. The definitional interpreter for \LangFun{} is shown in
  13659. figure~\ref{fig:interp-Lfun}. The case for the
  13660. %
  13661. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13662. %
  13663. AST is responsible for setting up the mutual recursion between the
  13664. top-level function definitions.
  13665. %
  13666. \racket{We use the classic back-patching
  13667. \index{subject}{back-patching} approach that uses mutable variables
  13668. and makes two passes over the function
  13669. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13670. top-level environment using a mutable cons cell for each function
  13671. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13672. for each function is incomplete; it does not yet include the environment.
  13673. Once the top-level environment has been constructed, we iterate over it and
  13674. update the \code{lambda} values to use the top-level environment.}
  13675. %
  13676. \python{We create a dictionary named \code{env} and fill it in
  13677. by mapping each function name to a new \code{Function} value,
  13678. each of which stores a reference to the \code{env}.
  13679. (We define the class \code{Function} for this purpose.)}
  13680. %
  13681. To interpret a function \racket{application}\python{call}, we match
  13682. the result of the function expression to obtain a function value. We
  13683. then extend the function's environment with the mapping of parameters to
  13684. argument values. Finally, we interpret the body of the function in
  13685. this extended environment.
  13686. \begin{figure}[tp]
  13687. \begin{tcolorbox}[colback=white]
  13688. {\if\edition\racketEd
  13689. \begin{lstlisting}
  13690. (define interp-Lfun-class
  13691. (class interp-Lvec-class
  13692. (super-new)
  13693. (define/override ((interp-exp env) e)
  13694. (define recur (interp-exp env))
  13695. (match e
  13696. [(Apply fun args)
  13697. (define fun-val (recur fun))
  13698. (define arg-vals (for/list ([e args]) (recur e)))
  13699. (match fun-val
  13700. [`(function (,xs ...) ,body ,fun-env)
  13701. (define params-args (for/list ([x xs] [arg arg-vals])
  13702. (cons x (box arg))))
  13703. (define new-env (append params-args fun-env))
  13704. ((interp-exp new-env) body)]
  13705. [else
  13706. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13707. [else ((super interp-exp env) e)]
  13708. ))
  13709. (define/public (interp-def d)
  13710. (match d
  13711. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13712. (cons f (box `(function ,xs ,body ())))]))
  13713. (define/override (interp-program p)
  13714. (match p
  13715. [(ProgramDefsExp info ds body)
  13716. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13717. (for/list ([f (in-dict-values top-level)])
  13718. (set-box! f (match (unbox f)
  13719. [`(function ,xs ,body ())
  13720. `(function ,xs ,body ,top-level)])))
  13721. ((interp-exp top-level) body))]))
  13722. ))
  13723. (define (interp-Lfun p)
  13724. (send (new interp-Lfun-class) interp-program p))
  13725. \end{lstlisting}
  13726. \fi}
  13727. {\if\edition\pythonEd\pythonColor
  13728. \begin{lstlisting}
  13729. class InterpLfun(InterpLtup):
  13730. def apply_fun(self, fun, args, e):
  13731. match fun:
  13732. case Function(name, xs, body, env):
  13733. new_env = env.copy().update(zip(xs, args))
  13734. return self.interp_stmts(body, new_env)
  13735. case _:
  13736. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13737. def interp_exp(self, e, env):
  13738. match e:
  13739. case Call(Name('input_int'), []):
  13740. return super().interp_exp(e, env)
  13741. case Call(func, args):
  13742. f = self.interp_exp(func, env)
  13743. vs = [self.interp_exp(arg, env) for arg in args]
  13744. return self.apply_fun(f, vs, e)
  13745. case _:
  13746. return super().interp_exp(e, env)
  13747. def interp_stmt(self, s, env, cont):
  13748. match s:
  13749. case Return(value):
  13750. return self.interp_exp(value, env)
  13751. case FunctionDef(name, params, bod, dl, returns, comment):
  13752. if isinstance(params, ast.arguments):
  13753. ps = [p.arg for p in params.args]
  13754. else:
  13755. ps = [x for (x,t) in params]
  13756. env[name] = Function(name, ps, bod, env)
  13757. return self.interp_stmts(cont, env)
  13758. case _:
  13759. return super().interp_stmt(s, env, cont)
  13760. def interp(self, p):
  13761. match p:
  13762. case Module(ss):
  13763. env = {}
  13764. self.interp_stmts(ss, env)
  13765. if 'main' in env.keys():
  13766. self.apply_fun(env['main'], [], None)
  13767. case _:
  13768. raise Exception('interp: unexpected ' + repr(p))
  13769. \end{lstlisting}
  13770. \fi}
  13771. \end{tcolorbox}
  13772. \caption{Interpreter for the \LangFun{} language.}
  13773. \label{fig:interp-Lfun}
  13774. \end{figure}
  13775. %\margincomment{TODO: explain type checker}
  13776. The type checker for \LangFun{} is shown in
  13777. figure~\ref{fig:type-check-Lfun}.
  13778. %
  13779. \python{(We omit the code that parses function parameters into the
  13780. simpler abstract syntax.)}
  13781. %
  13782. Similarly to the interpreter, the case for the
  13783. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13784. %
  13785. AST is responsible for setting up the mutual recursion between the
  13786. top-level function definitions. We begin by create a mapping
  13787. \code{env} from every function name to its type. We then type check
  13788. the program using this mapping.
  13789. %
  13790. In the case for function \racket{application}\python{call}, we match
  13791. the type of the function expression to a function type and check that
  13792. the types of the argument expressions are equal to the function's
  13793. parameter types. The type of the \racket{application}\python{call} as
  13794. a whole is the return type from the function type.
  13795. \begin{figure}[tp]
  13796. \begin{tcolorbox}[colback=white]
  13797. {\if\edition\racketEd
  13798. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13799. (define type-check-Lfun-class
  13800. (class type-check-Lvec-class
  13801. (super-new)
  13802. (inherit check-type-equal?)
  13803. (define/public (type-check-apply env e es)
  13804. (define-values (e^ ty) ((type-check-exp env) e))
  13805. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  13806. ((type-check-exp env) e)))
  13807. (match ty
  13808. [`(,ty^* ... -> ,rt)
  13809. (for ([arg-ty ty*] [param-ty ty^*])
  13810. (check-type-equal? arg-ty param-ty (Apply e es)))
  13811. (values e^ e* rt)]))
  13812. (define/override (type-check-exp env)
  13813. (lambda (e)
  13814. (match e
  13815. [(FunRef f n)
  13816. (values (FunRef f n) (dict-ref env f))]
  13817. [(Apply e es)
  13818. (define-values (e^ es^ rt) (type-check-apply env e es))
  13819. (values (Apply e^ es^) rt)]
  13820. [(Call e es)
  13821. (define-values (e^ es^ rt) (type-check-apply env e es))
  13822. (values (Call e^ es^) rt)]
  13823. [else ((super type-check-exp env) e)])))
  13824. (define/public (type-check-def env)
  13825. (lambda (e)
  13826. (match e
  13827. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  13828. (define new-env (append (map cons xs ps) env))
  13829. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13830. (check-type-equal? ty^ rt body)
  13831. (Def f p:t* rt info body^)])))
  13832. (define/public (fun-def-type d)
  13833. (match d
  13834. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  13835. (define/override (type-check-program e)
  13836. (match e
  13837. [(ProgramDefsExp info ds body)
  13838. (define env (for/list ([d ds])
  13839. (cons (Def-name d) (fun-def-type d))))
  13840. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  13841. (define-values (body^ ty) ((type-check-exp env) body))
  13842. (check-type-equal? ty 'Integer body)
  13843. (ProgramDefsExp info ds^ body^)]))))
  13844. (define (type-check-Lfun p)
  13845. (send (new type-check-Lfun-class) type-check-program p))
  13846. \end{lstlisting}
  13847. \fi}
  13848. {\if\edition\pythonEd\pythonColor
  13849. \begin{lstlisting}
  13850. class TypeCheckLfun(TypeCheckLtup):
  13851. def type_check_exp(self, e, env):
  13852. match e:
  13853. case Call(Name('input_int'), []):
  13854. return super().type_check_exp(e, env)
  13855. case Call(func, args):
  13856. func_t = self.type_check_exp(func, env)
  13857. args_t = [self.type_check_exp(arg, env) for arg in args]
  13858. match func_t:
  13859. case FunctionType(params_t, return_t):
  13860. for (arg_t, param_t) in zip(args_t, params_t):
  13861. check_type_equal(param_t, arg_t, e)
  13862. return return_t
  13863. case _:
  13864. raise Exception('type_check_exp: in call, unexpected ' +
  13865. repr(func_t))
  13866. case _:
  13867. return super().type_check_exp(e, env)
  13868. def type_check_stmts(self, ss, env):
  13869. if len(ss) == 0:
  13870. return
  13871. match ss[0]:
  13872. case FunctionDef(name, params, body, dl, returns, comment):
  13873. new_env = env.copy().update(params)
  13874. rt = self.type_check_stmts(body, new_env)
  13875. check_type_equal(returns, rt, ss[0])
  13876. return self.type_check_stmts(ss[1:], env)
  13877. case Return(value):
  13878. return self.type_check_exp(value, env)
  13879. case _:
  13880. return super().type_check_stmts(ss, env)
  13881. def type_check(self, p):
  13882. match p:
  13883. case Module(body):
  13884. env = {}
  13885. for s in body:
  13886. match s:
  13887. case FunctionDef(name, params, bod, dl, returns, comment):
  13888. if name in env:
  13889. raise Exception('type_check: function ' +
  13890. repr(name) + ' defined twice')
  13891. params_t = [t for (x,t) in params]
  13892. env[name] = FunctionType(params_t, returns)
  13893. self.type_check_stmts(body, env)
  13894. case _:
  13895. raise Exception('type_check: unexpected ' + repr(p))
  13896. \end{lstlisting}
  13897. \fi}
  13898. \end{tcolorbox}
  13899. \caption{Type checker for the \LangFun{} language.}
  13900. \label{fig:type-check-Lfun}
  13901. \end{figure}
  13902. \clearpage
  13903. \section{Functions in x86}
  13904. \label{sec:fun-x86}
  13905. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  13906. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  13907. %% \margincomment{\tiny Talk about the return address on the
  13908. %% stack and what callq and retq does.\\ --Jeremy }
  13909. The x86 architecture provides a few features to support the
  13910. implementation of functions. We have already seen that there are
  13911. labels in x86 so that one can refer to the location of an instruction,
  13912. as is needed for jump instructions. Labels can also be used to mark
  13913. the beginning of the instructions for a function. Going further, we
  13914. can obtain the address of a label by using the \key{leaq}
  13915. instruction. For example, the following puts the address of the
  13916. \code{inc} label into the \code{rbx} register:
  13917. \begin{lstlisting}
  13918. leaq inc(%rip), %rbx
  13919. \end{lstlisting}
  13920. Recall from section~\ref{sec:select-instructions-gc} that
  13921. \verb!inc(%rip)! is an example of instruction-pointer-relative
  13922. addressing.
  13923. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  13924. to functions whose locations were given by a label, such as
  13925. \code{read\_int}. To support function calls in this chapter we instead
  13926. jump to functions whose location are given by an address in
  13927. a register; that is, we use \emph{indirect function calls}. The
  13928. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  13929. before the register name.\index{subject}{indirect function call}
  13930. \begin{lstlisting}
  13931. callq *%rbx
  13932. \end{lstlisting}
  13933. \subsection{Calling Conventions}
  13934. \label{sec:calling-conventions-fun}
  13935. \index{subject}{calling conventions}
  13936. The \code{callq} instruction provides partial support for implementing
  13937. functions: it pushes the return address on the stack and it jumps to
  13938. the target. However, \code{callq} does not handle
  13939. \begin{enumerate}
  13940. \item parameter passing,
  13941. \item pushing frames on the procedure call stack and popping them off,
  13942. or
  13943. \item determining how registers are shared by different functions.
  13944. \end{enumerate}
  13945. Regarding parameter passing, recall that the x86-64 calling
  13946. convention for Unix-based systems uses the following six registers to
  13947. pass arguments to a function, in the given order:
  13948. \begin{lstlisting}
  13949. rdi rsi rdx rcx r8 r9
  13950. \end{lstlisting}
  13951. If there are more than six arguments, then the calling convention
  13952. mandates using space on the frame of the caller for the rest of the
  13953. arguments. However, to ease the implementation of efficient tail calls
  13954. (section~\ref{sec:tail-call}), we arrange never to need more than six
  13955. arguments.
  13956. %
  13957. The return value of the function is stored in register \code{rax}.
  13958. Regarding frames \index{subject}{frame} and the procedure call stack,
  13959. \index{subject}{procedure call stack} recall from
  13960. section~\ref{sec:x86} that the stack grows down and each function call
  13961. uses a chunk of space on the stack called a frame. The caller sets the
  13962. stack pointer, register \code{rsp}, to the last data item in its
  13963. frame. The callee must not change anything in the caller's frame, that
  13964. is, anything that is at or above the stack pointer. The callee is free
  13965. to use locations that are below the stack pointer.
  13966. Recall that we store variables of tuple type on the root stack. So,
  13967. the prelude\index{subject}{prelude} of a function needs to move the
  13968. root stack pointer \code{r15} up according to the number of variables
  13969. of tuple type and the conclusion\index{subject}{conclusion} needs to
  13970. move the root stack pointer back down. Also, the prelude must
  13971. initialize to \code{0} this frame's slots in the root stack to signal
  13972. to the garbage collector that those slots do not yet contain a valid
  13973. pointer. Otherwise the garbage collector will interpret the garbage
  13974. bits in those slots as memory addresses and try to traverse them,
  13975. causing serious mayhem!
  13976. Regarding the sharing of registers between different functions, recall
  13977. from section~\ref{sec:calling-conventions} that the registers are
  13978. divided into two groups, the caller-saved registers and the
  13979. callee-saved registers. The caller should assume that all the
  13980. caller-saved registers are overwritten with arbitrary values by the
  13981. callee. For that reason we recommend in
  13982. section~\ref{sec:calling-conventions} that variables that are live
  13983. during a function call should not be assigned to caller-saved
  13984. registers.
  13985. On the flip side, if the callee wants to use a callee-saved register,
  13986. the callee must save the contents of those registers on their stack
  13987. frame and then put them back prior to returning to the caller. For
  13988. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13989. the register allocator assigns a variable to a callee-saved register,
  13990. then the prelude of the \code{main} function must save that register
  13991. to the stack and the conclusion of \code{main} must restore it. This
  13992. recommendation now generalizes to all functions.
  13993. Recall that the base pointer, register \code{rbp}, is used as a
  13994. point of reference within a frame, so that each local variable can be
  13995. accessed at a fixed offset from the base pointer
  13996. (section~\ref{sec:x86}).
  13997. %
  13998. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13999. and callee frames.
  14000. \begin{figure}[tbp]
  14001. \centering
  14002. \begin{tcolorbox}[colback=white]
  14003. \begin{tabular}{r|r|l|l} \hline
  14004. Caller View & Callee View & Contents & Frame \\ \hline
  14005. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14006. 0(\key{\%rbp}) & & old \key{rbp} \\
  14007. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14008. \ldots & & \ldots \\
  14009. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14010. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14011. \ldots & & \ldots \\
  14012. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14013. %% & & \\
  14014. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14015. %% & \ldots & \ldots \\
  14016. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14017. \hline
  14018. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14019. & 0(\key{\%rbp}) & old \key{rbp} \\
  14020. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14021. & \ldots & \ldots \\
  14022. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14023. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14024. & \ldots & \ldots \\
  14025. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14026. \end{tabular}
  14027. \end{tcolorbox}
  14028. \caption{Memory layout of caller and callee frames.}
  14029. \label{fig:call-frames}
  14030. \end{figure}
  14031. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14032. %% local variables and for storing the values of callee-saved registers
  14033. %% (we shall refer to all of these collectively as ``locals''), and that
  14034. %% at the beginning of a function we move the stack pointer \code{rsp}
  14035. %% down to make room for them.
  14036. %% We recommend storing the local variables
  14037. %% first and then the callee-saved registers, so that the local variables
  14038. %% can be accessed using \code{rbp} the same as before the addition of
  14039. %% functions.
  14040. %% To make additional room for passing arguments, we shall
  14041. %% move the stack pointer even further down. We count how many stack
  14042. %% arguments are needed for each function call that occurs inside the
  14043. %% body of the function and find their maximum. Adding this number to the
  14044. %% number of locals gives us how much the \code{rsp} should be moved at
  14045. %% the beginning of the function. In preparation for a function call, we
  14046. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14047. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14048. %% so on.
  14049. %% Upon calling the function, the stack arguments are retrieved by the
  14050. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14051. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14052. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14053. %% the layout of the caller and callee frames. Notice how important it is
  14054. %% that we correctly compute the maximum number of arguments needed for
  14055. %% function calls; if that number is too small then the arguments and
  14056. %% local variables will smash into each other!
  14057. \subsection{Efficient Tail Calls}
  14058. \label{sec:tail-call}
  14059. In general, the amount of stack space used by a program is determined
  14060. by the longest chain of nested function calls. That is, if function
  14061. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14062. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14063. large if functions are recursive. However, in some cases we can
  14064. arrange to use only a constant amount of space for a long chain of
  14065. nested function calls.
  14066. A \emph{tail call}\index{subject}{tail call} is a function call that
  14067. happens as the last action in a function body. For example, in the
  14068. following program, the recursive call to \code{tail\_sum} is a tail
  14069. call:
  14070. \begin{center}
  14071. {\if\edition\racketEd
  14072. \begin{lstlisting}
  14073. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14074. (if (eq? n 0)
  14075. r
  14076. (tail_sum (- n 1) (+ n r))))
  14077. (+ (tail_sum 3 0) 36)
  14078. \end{lstlisting}
  14079. \fi}
  14080. {\if\edition\pythonEd\pythonColor
  14081. \begin{lstlisting}
  14082. def tail_sum(n : int, r : int) -> int:
  14083. if n == 0:
  14084. return r
  14085. else:
  14086. return tail_sum(n - 1, n + r)
  14087. print( tail_sum(3, 0) + 36)
  14088. \end{lstlisting}
  14089. \fi}
  14090. \end{center}
  14091. At a tail call, the frame of the caller is no longer needed, so we can
  14092. pop the caller's frame before making the tail call. With this
  14093. approach, a recursive function that makes only tail calls ends up
  14094. using a constant amount of stack space. Functional languages like
  14095. Racket rely heavily on recursive functions, so the definition of
  14096. Racket \emph{requires} that all tail calls be optimized in this way.
  14097. \index{subject}{frame}
  14098. Some care is needed with regard to argument passing in tail calls. As
  14099. mentioned, for arguments beyond the sixth, the convention is to use
  14100. space in the caller's frame for passing arguments. However, for a
  14101. tail call we pop the caller's frame and can no longer use it. An
  14102. alternative is to use space in the callee's frame for passing
  14103. arguments. However, this option is also problematic because the caller
  14104. and callee's frames overlap in memory. As we begin to copy the
  14105. arguments from their sources in the caller's frame, the target
  14106. locations in the callee's frame might collide with the sources for
  14107. later arguments! We solve this problem by using the heap instead of
  14108. the stack for passing more than six arguments
  14109. (section~\ref{sec:limit-functions-r4}).
  14110. As mentioned, for a tail call we pop the caller's frame prior to
  14111. making the tail call. The instructions for popping a frame are the
  14112. instructions that we usually place in the conclusion of a
  14113. function. Thus, we also need to place such code immediately before
  14114. each tail call. These instructions include restoring the callee-saved
  14115. registers, so it is fortunate that the argument passing registers are
  14116. all caller-saved registers.
  14117. One note remains regarding which instruction to use to make the tail
  14118. call. When the callee is finished, it should not return to the current
  14119. function but instead return to the function that called the current
  14120. one. Thus, the return address that is already on the stack is the
  14121. right one, and we should not use \key{callq} to make the tail call
  14122. because that would overwrite the return address. Instead we simply use
  14123. the \key{jmp} instruction. As with the indirect function call, we write
  14124. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14125. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14126. jump target because the conclusion can overwrite just about everything
  14127. else.
  14128. \begin{lstlisting}
  14129. jmp *%rax
  14130. \end{lstlisting}
  14131. \section{Shrink \LangFun{}}
  14132. \label{sec:shrink-r4}
  14133. The \code{shrink} pass performs a minor modification to ease the
  14134. later passes. This pass introduces an explicit \code{main} function
  14135. that gobbles up all the top-level statements of the module.
  14136. %
  14137. \racket{It also changes the top \code{ProgramDefsExp} form to
  14138. \code{ProgramDefs}.}
  14139. {\if\edition\racketEd
  14140. \begin{lstlisting}
  14141. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14142. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14143. \end{lstlisting}
  14144. where $\itm{mainDef}$ is
  14145. \begin{lstlisting}
  14146. (Def 'main '() 'Integer '() |$\Exp'$|)
  14147. \end{lstlisting}
  14148. \fi}
  14149. {\if\edition\pythonEd\pythonColor
  14150. \begin{lstlisting}
  14151. Module(|$\Def\ldots\Stmt\ldots$|)
  14152. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14153. \end{lstlisting}
  14154. where $\itm{mainDef}$ is
  14155. \begin{lstlisting}
  14156. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14157. \end{lstlisting}
  14158. \fi}
  14159. \section{Reveal Functions and the \LangFunRef{} Language}
  14160. \label{sec:reveal-functions-r4}
  14161. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14162. in that it conflates the use of function names and local
  14163. variables. This is a problem because we need to compile the use of a
  14164. function name differently from the use of a local variable. In
  14165. particular, we use \code{leaq} to convert the function name (a label
  14166. in x86) to an address in a register. Thus, we create a new pass that
  14167. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14168. $n$ is the arity of the function.\python{\footnote{The arity is not
  14169. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14170. This pass is named \code{reveal\_functions} and the output language
  14171. is \LangFunRef{}.
  14172. %is defined in figure~\ref{fig:f1-syntax}.
  14173. %% The concrete syntax for a
  14174. %% function reference is $\CFUNREF{f}$.
  14175. %% \begin{figure}[tp]
  14176. %% \centering
  14177. %% \fbox{
  14178. %% \begin{minipage}{0.96\textwidth}
  14179. %% {\if\edition\racketEd
  14180. %% \[
  14181. %% \begin{array}{lcl}
  14182. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14183. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14184. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14185. %% \end{array}
  14186. %% \]
  14187. %% \fi}
  14188. %% {\if\edition\pythonEd\pythonColor
  14189. %% \[
  14190. %% \begin{array}{lcl}
  14191. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14192. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14193. %% \end{array}
  14194. %% \]
  14195. %% \fi}
  14196. %% \end{minipage}
  14197. %% }
  14198. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14199. %% (figure~\ref{fig:Lfun-syntax}).}
  14200. %% \label{fig:f1-syntax}
  14201. %% \end{figure}
  14202. %% Distinguishing between calls in tail position and non-tail position
  14203. %% requires the pass to have some notion of context. We recommend using
  14204. %% two mutually recursive functions, one for processing expressions in
  14205. %% tail position and another for the rest.
  14206. \racket{Placing this pass after \code{uniquify} will make sure that
  14207. there are no local variables and functions that share the same
  14208. name.}
  14209. %
  14210. The \code{reveal\_functions} pass should come before the
  14211. \code{remove\_complex\_operands} pass because function references
  14212. should be categorized as complex expressions.
  14213. \section{Limit Functions}
  14214. \label{sec:limit-functions-r4}
  14215. Recall that we wish to limit the number of function parameters to six
  14216. so that we do not need to use the stack for argument passing, which
  14217. makes it easier to implement efficient tail calls. However, because
  14218. the input language \LangFun{} supports arbitrary numbers of function
  14219. arguments, we have some work to do! The \code{limit\_functions} pass
  14220. transforms functions and function calls that involve more than six
  14221. arguments to pass the first five arguments as usual, but it packs the
  14222. rest of the arguments into a tuple and passes it as the sixth
  14223. argument.\footnote{The implementation this pass can be postponed to
  14224. last because you can test the rest of the passes on functions with
  14225. six or fewer parameters.}
  14226. Each function definition with seven or more parameters is transformed as
  14227. follows:
  14228. {\if\edition\racketEd
  14229. \begin{lstlisting}
  14230. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14231. |$\Rightarrow$|
  14232. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14233. \end{lstlisting}
  14234. \fi}
  14235. {\if\edition\pythonEd\pythonColor
  14236. \begin{lstlisting}
  14237. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14238. |$\Rightarrow$|
  14239. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14240. |$T_r$|, None, |$\itm{body}'$|, None)
  14241. \end{lstlisting}
  14242. \fi}
  14243. %
  14244. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14245. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14246. the $k$th element of the tuple, where $k = i - 6$.
  14247. %
  14248. {\if\edition\racketEd
  14249. \begin{lstlisting}
  14250. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14251. \end{lstlisting}
  14252. \fi}
  14253. {\if\edition\pythonEd\pythonColor
  14254. \begin{lstlisting}
  14255. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14256. \end{lstlisting}
  14257. \fi}
  14258. For function calls with too many arguments, the \code{limit\_functions}
  14259. pass transforms them in the following way:
  14260. \begin{tabular}{lll}
  14261. \begin{minipage}{0.3\textwidth}
  14262. {\if\edition\racketEd
  14263. \begin{lstlisting}
  14264. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14265. \end{lstlisting}
  14266. \fi}
  14267. {\if\edition\pythonEd\pythonColor
  14268. \begin{lstlisting}
  14269. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14270. \end{lstlisting}
  14271. \fi}
  14272. \end{minipage}
  14273. &
  14274. $\Rightarrow$
  14275. &
  14276. \begin{minipage}{0.5\textwidth}
  14277. {\if\edition\racketEd
  14278. \begin{lstlisting}
  14279. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14280. \end{lstlisting}
  14281. \fi}
  14282. {\if\edition\pythonEd\pythonColor
  14283. \begin{lstlisting}
  14284. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14285. \end{lstlisting}
  14286. \fi}
  14287. \end{minipage}
  14288. \end{tabular}
  14289. \section{Remove Complex Operands}
  14290. \label{sec:rco-r4}
  14291. The primary decisions to make for this pass are whether to classify
  14292. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14293. atomic or complex expressions. Recall that an atomic expression
  14294. ends up as an immediate argument of an x86 instruction. Function
  14295. application translates to a sequence of instructions, so
  14296. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14297. a complex expression. On the other hand, the arguments of
  14298. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14299. expressions.
  14300. %
  14301. Regarding \code{FunRef}, as discussed previously, the function label
  14302. needs to be converted to an address using the \code{leaq}
  14303. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14304. needs to be classified as a complex expression so that we generate an
  14305. assignment statement with a left-hand side that can serve as the
  14306. target of the \code{leaq}.
  14307. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14308. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14309. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14310. and augments programs to include a list of function definitions.
  14311. %
  14312. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14313. \newcommand{\LfunMonadASTRacket}{
  14314. \begin{array}{lcl}
  14315. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14316. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14317. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14318. \end{array}
  14319. }
  14320. \newcommand{\LfunMonadASTPython}{
  14321. \begin{array}{lcl}
  14322. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  14323. \MID \key{TupleType}\LS\Type^+\RS\\
  14324. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14325. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14326. \Stmt &::=& \RETURN{\Exp} \\
  14327. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14328. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14329. \end{array}
  14330. }
  14331. \begin{figure}[tp]
  14332. \centering
  14333. \begin{tcolorbox}[colback=white]
  14334. \small
  14335. {\if\edition\racketEd
  14336. \[
  14337. \begin{array}{l}
  14338. \gray{\LvarMonadASTRacket} \\ \hline
  14339. \gray{\LifMonadASTRacket} \\ \hline
  14340. \gray{\LwhileMonadASTRacket} \\ \hline
  14341. \gray{\LtupMonadASTRacket} \\ \hline
  14342. \LfunMonadASTRacket \\
  14343. \begin{array}{rcl}
  14344. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14345. \end{array}
  14346. \end{array}
  14347. \]
  14348. \fi}
  14349. {\if\edition\pythonEd\pythonColor
  14350. \[
  14351. \begin{array}{l}
  14352. \gray{\LvarMonadASTPython} \\ \hline
  14353. \gray{\LifMonadASTPython} \\ \hline
  14354. \gray{\LwhileMonadASTPython} \\ \hline
  14355. \gray{\LtupMonadASTPython} \\ \hline
  14356. \LfunMonadASTPython \\
  14357. \begin{array}{rcl}
  14358. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14359. \end{array}
  14360. \end{array}
  14361. \]
  14362. \fi}
  14363. \end{tcolorbox}
  14364. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14365. \label{fig:Lfun-anf-syntax}
  14366. \end{figure}
  14367. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14368. %% \LangFunANF{} of this pass.
  14369. %% \begin{figure}[tp]
  14370. %% \centering
  14371. %% \fbox{
  14372. %% \begin{minipage}{0.96\textwidth}
  14373. %% \small
  14374. %% \[
  14375. %% \begin{array}{rcl}
  14376. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14377. %% \MID \VOID{} } \\
  14378. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14379. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14380. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14381. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14382. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14383. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14384. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14385. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14386. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14387. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14388. %% \end{array}
  14389. %% \]
  14390. %% \end{minipage}
  14391. %% }
  14392. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14393. %% \label{fig:Lfun-anf-syntax}
  14394. %% \end{figure}
  14395. \section{Explicate Control and the \LangCFun{} Language}
  14396. \label{sec:explicate-control-r4}
  14397. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14398. output of \code{explicate\_control}.
  14399. %
  14400. %% \racket{(The concrete syntax is given in
  14401. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14402. %
  14403. The auxiliary functions for assignment\racket{ and tail contexts} should
  14404. be updated with cases for
  14405. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14406. function for predicate context should be updated for
  14407. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14408. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14409. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14410. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14411. auxiliary function for processing function definitions. This code is
  14412. similar to the case for \code{Program} in \LangVec{}. The top-level
  14413. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14414. form of \LangFun{} can then apply this new function to all the
  14415. function definitions.
  14416. {\if\edition\pythonEd\pythonColor
  14417. The translation of \code{Return} statements requires a new auxiliary
  14418. function to handle expressions in tail context, called
  14419. \code{explicate\_tail}. The function should take an expression and the
  14420. dictionary of basic blocks and produce a list of statements in the
  14421. \LangCFun{} language. The \code{explicate\_tail} function should
  14422. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  14423. and a default case for other kinds of expressions. The default case
  14424. should produce a \code{Return} statement. The case for \code{Call}
  14425. should change it into \code{TailCall}. The other cases should
  14426. recursively process their subexpressions and statements, choosing the
  14427. appropriate explicate functions for the various contexts.
  14428. \fi}
  14429. \newcommand{\CfunASTRacket}{
  14430. \begin{array}{lcl}
  14431. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14432. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14433. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14434. \end{array}
  14435. }
  14436. \newcommand{\CfunASTPython}{
  14437. \begin{array}{lcl}
  14438. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14439. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14440. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14441. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  14442. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14443. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14444. \end{array}
  14445. }
  14446. \begin{figure}[tp]
  14447. \begin{tcolorbox}[colback=white]
  14448. \small
  14449. {\if\edition\racketEd
  14450. \[
  14451. \begin{array}{l}
  14452. \gray{\CvarASTRacket} \\ \hline
  14453. \gray{\CifASTRacket} \\ \hline
  14454. \gray{\CloopASTRacket} \\ \hline
  14455. \gray{\CtupASTRacket} \\ \hline
  14456. \CfunASTRacket \\
  14457. \begin{array}{lcl}
  14458. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14459. \end{array}
  14460. \end{array}
  14461. \]
  14462. \fi}
  14463. {\if\edition\pythonEd\pythonColor
  14464. \[
  14465. \begin{array}{l}
  14466. \gray{\CifASTPython} \\ \hline
  14467. \gray{\CtupASTPython} \\ \hline
  14468. \CfunASTPython \\
  14469. \begin{array}{lcl}
  14470. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14471. \end{array}
  14472. \end{array}
  14473. \]
  14474. \fi}
  14475. \end{tcolorbox}
  14476. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14477. \label{fig:c3-syntax}
  14478. \end{figure}
  14479. \clearpage
  14480. \section{Select Instructions and the \LangXIndCall{} Language}
  14481. \label{sec:select-r4}
  14482. \index{subject}{select instructions}
  14483. The output of select instructions is a program in the \LangXIndCall{}
  14484. language; the definition of its concrete syntax is shown in
  14485. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14486. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14487. directive on the labels of function definitions to make sure the
  14488. bottom three bits are zero, which we put to use in
  14489. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14490. this section. \index{subject}{x86}
  14491. \newcommand{\GrammarXIndCall}{
  14492. \begin{array}{lcl}
  14493. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14494. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14495. \Block &::= & \Instr^{+} \\
  14496. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14497. \end{array}
  14498. }
  14499. \newcommand{\ASTXIndCallRacket}{
  14500. \begin{array}{lcl}
  14501. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14502. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14503. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14504. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14505. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14506. \end{array}
  14507. }
  14508. \begin{figure}[tp]
  14509. \begin{tcolorbox}[colback=white]
  14510. \small
  14511. \[
  14512. \begin{array}{l}
  14513. \gray{\GrammarXInt} \\ \hline
  14514. \gray{\GrammarXIf} \\ \hline
  14515. \gray{\GrammarXGlobal} \\ \hline
  14516. \GrammarXIndCall \\
  14517. \begin{array}{lcl}
  14518. \LangXIndCallM{} &::= & \Def^{*}
  14519. \end{array}
  14520. \end{array}
  14521. \]
  14522. \end{tcolorbox}
  14523. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14524. \label{fig:x86-3-concrete}
  14525. \end{figure}
  14526. \begin{figure}[tp]
  14527. \begin{tcolorbox}[colback=white]
  14528. \small
  14529. {\if\edition\racketEd
  14530. \[\arraycolsep=3pt
  14531. \begin{array}{l}
  14532. \gray{\ASTXIntRacket} \\ \hline
  14533. \gray{\ASTXIfRacket} \\ \hline
  14534. \gray{\ASTXGlobalRacket} \\ \hline
  14535. \ASTXIndCallRacket \\
  14536. \begin{array}{lcl}
  14537. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14538. \end{array}
  14539. \end{array}
  14540. \]
  14541. \fi}
  14542. {\if\edition\pythonEd\pythonColor
  14543. \[
  14544. \begin{array}{lcl}
  14545. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14546. \MID \BYTEREG{\Reg} } \\
  14547. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14548. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14549. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14550. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14551. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14552. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14553. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14554. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14555. \end{array}
  14556. \]
  14557. \fi}
  14558. \end{tcolorbox}
  14559. \caption{The abstract syntax of \LangXIndCall{} (extends
  14560. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14561. \label{fig:x86-3}
  14562. \end{figure}
  14563. An assignment of a function reference to a variable becomes a
  14564. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14565. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14566. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14567. node, whose concrete syntax is instruction-pointer-relative
  14568. addressing.
  14569. \begin{center}
  14570. \begin{tabular}{lcl}
  14571. \begin{minipage}{0.35\textwidth}
  14572. {\if\edition\racketEd
  14573. \begin{lstlisting}
  14574. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14575. \end{lstlisting}
  14576. \fi}
  14577. {\if\edition\pythonEd\pythonColor
  14578. \begin{lstlisting}
  14579. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14580. \end{lstlisting}
  14581. \fi}
  14582. \end{minipage}
  14583. &
  14584. $\Rightarrow$\qquad\qquad
  14585. &
  14586. \begin{minipage}{0.3\textwidth}
  14587. \begin{lstlisting}
  14588. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14589. \end{lstlisting}
  14590. \end{minipage}
  14591. \end{tabular}
  14592. \end{center}
  14593. Regarding function definitions, we need to remove the parameters and
  14594. instead perform parameter passing using the conventions discussed in
  14595. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14596. registers. We recommend turning the parameters into local variables
  14597. and generating instructions at the beginning of the function to move
  14598. from the argument-passing registers
  14599. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14600. {\if\edition\racketEd
  14601. \begin{lstlisting}
  14602. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14603. |$\Rightarrow$|
  14604. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14605. \end{lstlisting}
  14606. \fi}
  14607. {\if\edition\pythonEd\pythonColor
  14608. \begin{lstlisting}
  14609. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14610. |$\Rightarrow$|
  14611. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14612. \end{lstlisting}
  14613. \fi}
  14614. The basic blocks $B'$ are the same as $B$ except that the
  14615. \code{start} block is modified to add the instructions for moving from
  14616. the argument registers to the parameter variables. So the \code{start}
  14617. block of $B$ shown on the left of the following is changed to the code
  14618. on the right:
  14619. \begin{center}
  14620. \begin{minipage}{0.3\textwidth}
  14621. \begin{lstlisting}
  14622. start:
  14623. |$\itm{instr}_1$|
  14624. |$\cdots$|
  14625. |$\itm{instr}_n$|
  14626. \end{lstlisting}
  14627. \end{minipage}
  14628. $\Rightarrow$
  14629. \begin{minipage}{0.3\textwidth}
  14630. \begin{lstlisting}
  14631. |$f$|start:
  14632. movq %rdi, |$x_1$|
  14633. movq %rsi, |$x_2$|
  14634. |$\cdots$|
  14635. |$\itm{instr}_1$|
  14636. |$\cdots$|
  14637. |$\itm{instr}_n$|
  14638. \end{lstlisting}
  14639. \end{minipage}
  14640. \end{center}
  14641. Recall that we use the label \code{start} for the initial block of a
  14642. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14643. the conclusion of the program with \code{conclusion}, so that
  14644. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14645. by a jump to \code{conclusion}. With the addition of function
  14646. definitions, there is a start block and conclusion for each function,
  14647. but their labels need to be unique. We recommend prepending the
  14648. function's name to \code{start} and \code{conclusion}, respectively,
  14649. to obtain unique labels.
  14650. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14651. number of parameters the function expects, but the parameters are no
  14652. longer in the syntax of function definitions. Instead, add an entry
  14653. to $\itm{info}$ that maps \code{num-params} to the number of
  14654. parameters to construct $\itm{info}'$.}
  14655. By changing the parameters to local variables, we are giving the
  14656. register allocator control over which registers or stack locations to
  14657. use for them. If you implement the move-biasing challenge
  14658. (section~\ref{sec:move-biasing}), the register allocator will try to
  14659. assign the parameter variables to the corresponding argument register,
  14660. in which case the \code{patch\_instructions} pass will remove the
  14661. \code{movq} instruction. This happens in the example translation given
  14662. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14663. the \code{add} function.
  14664. %
  14665. Also, note that the register allocator will perform liveness analysis
  14666. on this sequence of move instructions and build the interference
  14667. graph. So, for example, $x_1$ will be marked as interfering with
  14668. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14669. which is good because otherwise the first \code{movq} would overwrite
  14670. the argument in \code{rsi} that is needed for $x_2$.
  14671. Next, consider the compilation of function calls. In the mirror image
  14672. of the handling of parameters in function definitions, the arguments
  14673. are moved to the argument-passing registers. Note that the function
  14674. is not given as a label, but its address is produced by the argument
  14675. $\itm{arg}_0$. So, we translate the call into an indirect function
  14676. call. The return value from the function is stored in \code{rax}, so
  14677. it needs to be moved into the \itm{lhs}.
  14678. \begin{lstlisting}
  14679. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14680. |$\Rightarrow$|
  14681. movq |$\itm{arg}_1$|, %rdi
  14682. movq |$\itm{arg}_2$|, %rsi
  14683. |$\vdots$|
  14684. callq *|$\itm{arg}_0$|
  14685. movq %rax, |$\itm{lhs}$|
  14686. \end{lstlisting}
  14687. The \code{IndirectCallq} AST node includes an integer for the arity of
  14688. the function, that is, the number of parameters. That information is
  14689. useful in the \code{uncover\_live} pass for determining which
  14690. argument-passing registers are potentially read during the call.
  14691. For tail calls, the parameter passing is the same as non-tail calls:
  14692. generate instructions to move the arguments into the argument-passing
  14693. registers. After that we need to pop the frame from the procedure
  14694. call stack. However, we do not yet know how big the frame is; that
  14695. gets determined during register allocation. So, instead of generating
  14696. those instructions here, we invent a new instruction that means ``pop
  14697. the frame and then do an indirect jump,'' which we name
  14698. \code{TailJmp}. The abstract syntax for this instruction includes an
  14699. argument that specifies where to jump and an integer that represents
  14700. the arity of the function being called.
  14701. \section{Register Allocation}
  14702. \label{sec:register-allocation-r4}
  14703. The addition of functions requires some changes to all three aspects
  14704. of register allocation, which we discuss in the following subsections.
  14705. \subsection{Liveness Analysis}
  14706. \label{sec:liveness-analysis-r4}
  14707. \index{subject}{liveness analysis}
  14708. %% The rest of the passes need only minor modifications to handle the new
  14709. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14710. %% \code{leaq}.
  14711. The \code{IndirectCallq} instruction should be treated like
  14712. \code{Callq} regarding its written locations $W$, in that they should
  14713. include all the caller-saved registers. Recall that the reason for
  14714. that is to force variables that are live across a function call to be assigned to callee-saved
  14715. registers or to be spilled to the stack.
  14716. Regarding the set of read locations $R$, the arity fields of
  14717. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14718. argument-passing registers should be considered as read by those
  14719. instructions. Also, the target field of \code{TailJmp} and
  14720. \code{IndirectCallq} should be included in the set of read locations
  14721. $R$.
  14722. \subsection{Build Interference Graph}
  14723. \label{sec:build-interference-r4}
  14724. With the addition of function definitions, we compute a separate interference
  14725. graph for each function (not just one for the whole program).
  14726. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14727. spill tuple-typed variables that are live during a call to
  14728. \code{collect}, the garbage collector. With the addition of functions
  14729. to our language, we need to revisit this issue. Functions that perform
  14730. allocation contain calls to the collector. Thus, we should not only
  14731. spill a tuple-typed variable when it is live during a call to
  14732. \code{collect}, but we should spill the variable if it is live during
  14733. a call to any user-defined function. Thus, in the
  14734. \code{build\_interference} pass, we recommend adding interference
  14735. edges between call-live tuple-typed variables and the callee-saved
  14736. registers (in addition to creating edges between
  14737. call-live variables and the caller-saved registers).
  14738. \subsection{Allocate Registers}
  14739. The primary change to the \code{allocate\_registers} pass is adding an
  14740. auxiliary function for handling definitions (the \Def{} nonterminal
  14741. shown in figure~\ref{fig:x86-3}) with one case for function
  14742. definitions. The logic is the same as described in
  14743. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14744. allocation is performed many times, once for each function definition,
  14745. instead of just once for the whole program.
  14746. \section{Patch Instructions}
  14747. In \code{patch\_instructions}, you should deal with the x86
  14748. idiosyncrasy that the destination argument of \code{leaq} must be a
  14749. register. Additionally, you should ensure that the argument of
  14750. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14751. trample many other registers before the tail call, as explained in the
  14752. next section.
  14753. \section{Prelude and Conclusion}
  14754. Now that register allocation is complete, we can translate the
  14755. \code{TailJmp} into a sequence of instructions. A naive translation of
  14756. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14757. before the jump we need to pop the current frame to achieve efficient
  14758. tail calls. This sequence of instructions is the same as the code for
  14759. the conclusion of a function, except that the \code{retq} is replaced with
  14760. \code{jmp *$\itm{arg}$}.
  14761. Regarding function definitions, we generate a prelude and conclusion
  14762. for each one. This code is similar to the prelude and conclusion
  14763. generated for the \code{main} function presented in
  14764. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14765. carry out the following steps:
  14766. % TODO: .align the functions!
  14767. \begin{enumerate}
  14768. %% \item Start with \code{.global} and \code{.align} directives followed
  14769. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14770. %% example.)
  14771. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14772. pointer.
  14773. \item Push to the stack all the callee-saved registers that were
  14774. used for register allocation.
  14775. \item Move the stack pointer \code{rsp} down to make room for the
  14776. regular spills (aligned to 16 bytes).
  14777. \item Move the root stack pointer \code{r15} up by the size of the
  14778. root-stack frame for this function, which depends on the number of
  14779. spilled tuple-typed variables. \label{root-stack-init}
  14780. \item Initialize to zero all new entries in the root-stack frame.
  14781. \item Jump to the start block.
  14782. \end{enumerate}
  14783. The prelude of the \code{main} function has an additional task: call
  14784. the \code{initialize} function to set up the garbage collector, and
  14785. then move the value of the global \code{rootstack\_begin} in
  14786. \code{r15}. This initialization should happen before step
  14787. \ref{root-stack-init}, which depends on \code{r15}.
  14788. The conclusion of every function should do the following:
  14789. \begin{enumerate}
  14790. \item Move the stack pointer back up past the regular spills.
  14791. \item Restore the callee-saved registers by popping them from the
  14792. stack.
  14793. \item Move the root stack pointer back down by the size of the
  14794. root-stack frame for this function.
  14795. \item Restore \code{rbp} by popping it from the stack.
  14796. \item Return to the caller with the \code{retq} instruction.
  14797. \end{enumerate}
  14798. The output of this pass is \LangXIndCallFlat{}, which differs from
  14799. \LangXIndCall{} in that there is no longer an AST node for function
  14800. definitions. Instead, a program is just an association list of basic
  14801. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  14802. \[
  14803. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  14804. \]
  14805. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  14806. compiling \LangFun{} to x86.
  14807. \begin{exercise}\normalfont\normalsize
  14808. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  14809. Create eight new programs that use functions including examples that
  14810. pass functions and return functions from other functions, recursive
  14811. functions, functions that create vectors, and functions that make tail
  14812. calls. Test your compiler on these new programs and all your
  14813. previously created test programs.
  14814. \end{exercise}
  14815. \begin{figure}[tbp]
  14816. \begin{tcolorbox}[colback=white]
  14817. {\if\edition\racketEd
  14818. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  14819. \node (Lfun) at (0,2) {\large \LangFun{}};
  14820. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  14821. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  14822. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  14823. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  14824. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  14825. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14826. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14827. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14828. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14829. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14830. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14831. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  14832. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  14833. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  14834. \path[->,bend left=15] (Lfun) edge [above] node
  14835. {\ttfamily\footnotesize shrink} (Lfun-1);
  14836. \path[->,bend left=15] (Lfun-1) edge [above] node
  14837. {\ttfamily\footnotesize uniquify} (Lfun-2);
  14838. \path[->,bend left=15] (Lfun-2) edge [above] node
  14839. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14840. \path[->,bend left=15] (F1-1) edge [left] node
  14841. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14842. \path[->,bend left=15] (F1-2) edge [below] node
  14843. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  14844. \path[->,bend left=15] (F1-3) edge [below] node
  14845. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  14846. \path[->,bend right=15] (F1-4) edge [above] node
  14847. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14848. \path[->,bend right=15] (F1-5) edge [right] node
  14849. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14850. \path[->,bend right=15] (C3-2) edge [right] node
  14851. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14852. \path[->,bend left=15] (x86-2) edge [right] node
  14853. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14854. \path[->,bend right=15] (x86-2-1) edge [below] node
  14855. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  14856. \path[->,bend right=15] (x86-2-2) edge [right] node
  14857. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  14858. \path[->,bend left=15] (x86-3) edge [above] node
  14859. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14860. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14861. \end{tikzpicture}
  14862. \fi}
  14863. {\if\edition\pythonEd\pythonColor
  14864. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  14865. \node (Lfun) at (0,2) {\large \LangFun{}};
  14866. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  14867. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  14868. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  14869. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14870. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14871. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14872. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14873. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14874. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14875. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  14876. \path[->,bend left=15] (Lfun) edge [above] node
  14877. {\ttfamily\footnotesize shrink} (Lfun-2);
  14878. \path[->,bend left=15] (Lfun-2) edge [above] node
  14879. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14880. \path[->,bend left=15] (F1-1) edge [above] node
  14881. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14882. \path[->,bend left=15] (F1-2) edge [right] node
  14883. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  14884. \path[->,bend right=15] (F1-4) edge [above] node
  14885. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14886. \path[->,bend right=15] (F1-5) edge [right] node
  14887. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14888. \path[->,bend left=15] (C3-2) edge [right] node
  14889. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14890. \path[->,bend right=15] (x86-2) edge [below] node
  14891. {\ttfamily\footnotesize assign\_homes} (x86-3);
  14892. \path[->,bend left=15] (x86-3) edge [above] node
  14893. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14894. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14895. \end{tikzpicture}
  14896. \fi}
  14897. \end{tcolorbox}
  14898. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  14899. \label{fig:Lfun-passes}
  14900. \end{figure}
  14901. \section{An Example Translation}
  14902. \label{sec:functions-example}
  14903. Figure~\ref{fig:add-fun} shows an example translation of a simple
  14904. function in \LangFun{} to x86. The figure also includes the results of the
  14905. \code{explicate\_control} and \code{select\_instructions} passes.
  14906. \begin{figure}[htbp]
  14907. \begin{tcolorbox}[colback=white]
  14908. \begin{tabular}{ll}
  14909. \begin{minipage}{0.4\textwidth}
  14910. % s3_2.rkt
  14911. {\if\edition\racketEd
  14912. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14913. (define (add [x : Integer]
  14914. [y : Integer])
  14915. : Integer
  14916. (+ x y))
  14917. (add 40 2)
  14918. \end{lstlisting}
  14919. \fi}
  14920. {\if\edition\pythonEd\pythonColor
  14921. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14922. def add(x:int, y:int) -> int:
  14923. return x + y
  14924. print(add(40, 2))
  14925. \end{lstlisting}
  14926. \fi}
  14927. $\Downarrow$
  14928. {\if\edition\racketEd
  14929. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14930. (define (add86 [x87 : Integer]
  14931. [y88 : Integer])
  14932. : Integer
  14933. add86start:
  14934. return (+ x87 y88);
  14935. )
  14936. (define (main) : Integer ()
  14937. mainstart:
  14938. tmp89 = (fun-ref add86 2);
  14939. (tail-call tmp89 40 2)
  14940. )
  14941. \end{lstlisting}
  14942. \fi}
  14943. {\if\edition\pythonEd\pythonColor
  14944. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14945. def add(x:int, y:int) -> int:
  14946. addstart:
  14947. return x + y
  14948. def main() -> int:
  14949. mainstart:
  14950. fun.0 = add
  14951. tmp.1 = fun.0(40, 2)
  14952. print(tmp.1)
  14953. return 0
  14954. \end{lstlisting}
  14955. \fi}
  14956. \end{minipage}
  14957. &
  14958. $\Rightarrow$
  14959. \begin{minipage}{0.5\textwidth}
  14960. {\if\edition\racketEd
  14961. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14962. (define (add86) : Integer
  14963. add86start:
  14964. movq %rdi, x87
  14965. movq %rsi, y88
  14966. movq x87, %rax
  14967. addq y88, %rax
  14968. jmp inc1389conclusion
  14969. )
  14970. (define (main) : Integer
  14971. mainstart:
  14972. leaq (fun-ref add86 2), tmp89
  14973. movq $40, %rdi
  14974. movq $2, %rsi
  14975. tail-jmp tmp89
  14976. )
  14977. \end{lstlisting}
  14978. \fi}
  14979. {\if\edition\pythonEd\pythonColor
  14980. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14981. def add() -> int:
  14982. addstart:
  14983. movq %rdi, x
  14984. movq %rsi, y
  14985. movq x, %rax
  14986. addq y, %rax
  14987. jmp addconclusion
  14988. def main() -> int:
  14989. mainstart:
  14990. leaq add, fun.0
  14991. movq $40, %rdi
  14992. movq $2, %rsi
  14993. callq *fun.0
  14994. movq %rax, tmp.1
  14995. movq tmp.1, %rdi
  14996. callq print_int
  14997. movq $0, %rax
  14998. jmp mainconclusion
  14999. \end{lstlisting}
  15000. \fi}
  15001. $\Downarrow$
  15002. \end{minipage}
  15003. \end{tabular}
  15004. \begin{tabular}{ll}
  15005. \begin{minipage}{0.3\textwidth}
  15006. {\if\edition\racketEd
  15007. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15008. .globl add86
  15009. .align 8
  15010. add86:
  15011. pushq %rbp
  15012. movq %rsp, %rbp
  15013. jmp add86start
  15014. add86start:
  15015. movq %rdi, %rax
  15016. addq %rsi, %rax
  15017. jmp add86conclusion
  15018. add86conclusion:
  15019. popq %rbp
  15020. retq
  15021. \end{lstlisting}
  15022. \fi}
  15023. {\if\edition\pythonEd\pythonColor
  15024. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15025. .align 8
  15026. add:
  15027. pushq %rbp
  15028. movq %rsp, %rbp
  15029. subq $0, %rsp
  15030. jmp addstart
  15031. addstart:
  15032. movq %rdi, %rdx
  15033. movq %rsi, %rcx
  15034. movq %rdx, %rax
  15035. addq %rcx, %rax
  15036. jmp addconclusion
  15037. addconclusion:
  15038. subq $0, %r15
  15039. addq $0, %rsp
  15040. popq %rbp
  15041. retq
  15042. \end{lstlisting}
  15043. \fi}
  15044. \end{minipage}
  15045. &
  15046. \begin{minipage}{0.5\textwidth}
  15047. {\if\edition\racketEd
  15048. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15049. .globl main
  15050. .align 8
  15051. main:
  15052. pushq %rbp
  15053. movq %rsp, %rbp
  15054. movq $16384, %rdi
  15055. movq $16384, %rsi
  15056. callq initialize
  15057. movq rootstack_begin(%rip), %r15
  15058. jmp mainstart
  15059. mainstart:
  15060. leaq add86(%rip), %rcx
  15061. movq $40, %rdi
  15062. movq $2, %rsi
  15063. movq %rcx, %rax
  15064. popq %rbp
  15065. jmp *%rax
  15066. mainconclusion:
  15067. popq %rbp
  15068. retq
  15069. \end{lstlisting}
  15070. \fi}
  15071. {\if\edition\pythonEd\pythonColor
  15072. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15073. .globl main
  15074. .align 8
  15075. main:
  15076. pushq %rbp
  15077. movq %rsp, %rbp
  15078. subq $0, %rsp
  15079. movq $65536, %rdi
  15080. movq $65536, %rsi
  15081. callq initialize
  15082. movq rootstack_begin(%rip), %r15
  15083. jmp mainstart
  15084. mainstart:
  15085. leaq add(%rip), %rcx
  15086. movq $40, %rdi
  15087. movq $2, %rsi
  15088. callq *%rcx
  15089. movq %rax, %rcx
  15090. movq %rcx, %rdi
  15091. callq print_int
  15092. movq $0, %rax
  15093. jmp mainconclusion
  15094. mainconclusion:
  15095. subq $0, %r15
  15096. addq $0, %rsp
  15097. popq %rbp
  15098. retq
  15099. \end{lstlisting}
  15100. \fi}
  15101. \end{minipage}
  15102. \end{tabular}
  15103. \end{tcolorbox}
  15104. \caption{Example compilation of a simple function to x86.}
  15105. \label{fig:add-fun}
  15106. \end{figure}
  15107. % Challenge idea: inlining! (simple version)
  15108. % Further Reading
  15109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15110. \chapter{Lexically Scoped Functions}
  15111. \label{ch:Llambda}
  15112. \setcounter{footnote}{0}
  15113. This chapter studies lexically scoped functions. Lexical
  15114. scoping\index{subject}{lexical scoping} means that a function's body
  15115. may refer to variables whose binding site is outside of the function,
  15116. in an enclosing scope.
  15117. %
  15118. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15119. in \LangLam{}, which extends \LangFun{} with the
  15120. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15121. functions. The body of the \key{lambda} refers to three variables:
  15122. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15123. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15124. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15125. function \code{f}}, and \code{x} is a parameter of function
  15126. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15127. result value. The main expression of the program includes two calls to
  15128. \code{f} with different arguments for \code{x}: first \code{5} and
  15129. then \code{3}. The functions returned from \code{f} are bound to
  15130. variables \code{g} and \code{h}. Even though these two functions were
  15131. created by the same \code{lambda}, they are really different functions
  15132. because they use different values for \code{x}. Applying \code{g} to
  15133. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15134. produces \code{22}, so the result of the program is \code{42}.
  15135. \begin{figure}[btp]
  15136. \begin{tcolorbox}[colback=white]
  15137. {\if\edition\racketEd
  15138. % lambda_test_21.rkt
  15139. \begin{lstlisting}
  15140. (define (f [x : Integer]) : (Integer -> Integer)
  15141. (let ([y 4])
  15142. (lambda: ([z : Integer]) : Integer
  15143. (+ x (+ y z)))))
  15144. (let ([g (f 5)])
  15145. (let ([h (f 3)])
  15146. (+ (g 11) (h 15))))
  15147. \end{lstlisting}
  15148. \fi}
  15149. {\if\edition\pythonEd\pythonColor
  15150. \begin{lstlisting}
  15151. def f(x : int) -> Callable[[int], int]:
  15152. y = 4
  15153. return lambda z: x + y + z
  15154. g = f(5)
  15155. h = f(3)
  15156. print( g(11) + h(15) )
  15157. \end{lstlisting}
  15158. \fi}
  15159. \end{tcolorbox}
  15160. \caption{Example of a lexically scoped function.}
  15161. \label{fig:lexical-scoping}
  15162. \end{figure}
  15163. The approach that we take for implementing lexically scoped functions
  15164. is to compile them into top-level function definitions, translating
  15165. from \LangLam{} into \LangFun{}. However, the compiler must give
  15166. special treatment to variable occurrences such as \code{x} and
  15167. \code{y} in the body of the \code{lambda} shown in
  15168. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15169. may not refer to variables defined outside of it. To identify such
  15170. variable occurrences, we review the standard notion of free variable.
  15171. \begin{definition}\normalfont
  15172. A variable is \emph{free in expression} $e$ if the variable occurs
  15173. inside $e$ but does not have an enclosing definition that is also in
  15174. $e$.\index{subject}{free variable}
  15175. \end{definition}
  15176. For example, in the expression
  15177. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15178. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15179. only \code{x} and \code{y} are free in the following expression,
  15180. because \code{z} is defined by the \code{lambda}
  15181. {\if\edition\racketEd
  15182. \begin{lstlisting}
  15183. (lambda: ([z : Integer]) : Integer
  15184. (+ x (+ y z)))
  15185. \end{lstlisting}
  15186. \fi}
  15187. {\if\edition\pythonEd\pythonColor
  15188. \begin{lstlisting}
  15189. lambda z: x + y + z
  15190. \end{lstlisting}
  15191. \fi}
  15192. %
  15193. \noindent Thus the free variables of a \code{lambda} are the ones that
  15194. need special treatment. We need to transport at runtime the values
  15195. of those variables from the point where the \code{lambda} was created
  15196. to the point where the \code{lambda} is applied. An efficient solution
  15197. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15198. values of the free variables together with a function pointer into a
  15199. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15200. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15201. closure}
  15202. %
  15203. By design, we have all the ingredients to make closures:
  15204. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15205. function pointers. The function pointer resides at index $0$, and the
  15206. values for the free variables fill in the rest of the tuple.
  15207. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15208. to see how closures work. It is a three-step dance. The program calls
  15209. function \code{f}, which creates a closure for the \code{lambda}. The
  15210. closure is a tuple whose first element is a pointer to the top-level
  15211. function that we will generate for the \code{lambda}; the second
  15212. element is the value of \code{x}, which is \code{5}; and the third
  15213. element is \code{4}, the value of \code{y}. The closure does not
  15214. contain an element for \code{z} because \code{z} is not a free
  15215. variable of the \code{lambda}. Creating the closure is step 1 of the
  15216. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15217. shown in figure~\ref{fig:closures}.
  15218. %
  15219. The second call to \code{f} creates another closure, this time with
  15220. \code{3} in the second slot (for \code{x}). This closure is also
  15221. returned from \code{f} but bound to \code{h}, which is also shown in
  15222. figure~\ref{fig:closures}.
  15223. \begin{figure}[tbp]
  15224. \centering
  15225. \begin{minipage}{0.65\textwidth}
  15226. \begin{tcolorbox}[colback=white]
  15227. \includegraphics[width=\textwidth]{figs/closures}
  15228. \end{tcolorbox}
  15229. \end{minipage}
  15230. \caption{Flat closure representations for the two functions
  15231. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15232. \label{fig:closures}
  15233. \end{figure}
  15234. Continuing with the example, consider the application of \code{g} to
  15235. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15236. closure, we obtain the function pointer from the first element of the
  15237. closure and call it, passing in the closure itself and then the
  15238. regular arguments, in this case \code{11}. This technique for applying
  15239. a closure is step 2 of the dance.
  15240. %
  15241. But doesn't this \code{lambda} take only one argument, for parameter
  15242. \code{z}? The third and final step of the dance is generating a
  15243. top-level function for a \code{lambda}. We add an additional
  15244. parameter for the closure and insert an initialization at the beginning
  15245. of the function for each free variable, to bind those variables to the
  15246. appropriate elements from the closure parameter.
  15247. %
  15248. This three-step dance is known as \emph{closure
  15249. conversion}\index{subject}{closure conversion}. We discuss the
  15250. details of closure conversion in section~\ref{sec:closure-conversion}
  15251. and show the code generated from the example in
  15252. section~\ref{sec:example-lambda}. First, we define the syntax and
  15253. semantics of \LangLam{} in section~\ref{sec:r5}.
  15254. \section{The \LangLam{} Language}
  15255. \label{sec:r5}
  15256. The definitions of the concrete syntax and abstract syntax for
  15257. \LangLam{}, a language with anonymous functions and lexical scoping,
  15258. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15259. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15260. for \LangFun{}, which already has syntax for function application.
  15261. %
  15262. \python{The syntax also includes an assignment statement that includes
  15263. a type annotation for the variable on the left-hand side, which
  15264. facilitates the type checking of \code{lambda} expressions that we
  15265. discuss later in this section.}
  15266. %
  15267. \racket{The \code{procedure-arity} operation returns the number of parameters
  15268. of a given function, an operation that we need for the translation
  15269. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  15270. %
  15271. \python{The \code{arity} operation returns the number of parameters of
  15272. a given function, an operation that we need for the translation
  15273. of dynamic typing in chapter~\ref{ch:Ldyn}.
  15274. The \code{arity} operation is not in Python, but the same functionality
  15275. is available in a more complex form. We include \code{arity} in the
  15276. \LangLam{} source language to enable testing.}
  15277. \newcommand{\LlambdaGrammarRacket}{
  15278. \begin{array}{lcl}
  15279. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15280. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15281. \end{array}
  15282. }
  15283. \newcommand{\LlambdaASTRacket}{
  15284. \begin{array}{lcl}
  15285. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15286. \itm{op} &::=& \code{procedure-arity}
  15287. \end{array}
  15288. }
  15289. \newcommand{\LlambdaGrammarPython}{
  15290. \begin{array}{lcl}
  15291. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15292. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15293. \end{array}
  15294. }
  15295. \newcommand{\LlambdaASTPython}{
  15296. \begin{array}{lcl}
  15297. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15298. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15299. \end{array}
  15300. }
  15301. % include AnnAssign in ASTPython
  15302. \begin{figure}[tp]
  15303. \centering
  15304. \begin{tcolorbox}[colback=white]
  15305. \small
  15306. {\if\edition\racketEd
  15307. \[
  15308. \begin{array}{l}
  15309. \gray{\LintGrammarRacket{}} \\ \hline
  15310. \gray{\LvarGrammarRacket{}} \\ \hline
  15311. \gray{\LifGrammarRacket{}} \\ \hline
  15312. \gray{\LwhileGrammarRacket} \\ \hline
  15313. \gray{\LtupGrammarRacket} \\ \hline
  15314. \gray{\LfunGrammarRacket} \\ \hline
  15315. \LlambdaGrammarRacket \\
  15316. \begin{array}{lcl}
  15317. \LangLamM{} &::=& \Def\ldots \; \Exp
  15318. \end{array}
  15319. \end{array}
  15320. \]
  15321. \fi}
  15322. {\if\edition\pythonEd\pythonColor
  15323. \[
  15324. \begin{array}{l}
  15325. \gray{\LintGrammarPython{}} \\ \hline
  15326. \gray{\LvarGrammarPython{}} \\ \hline
  15327. \gray{\LifGrammarPython{}} \\ \hline
  15328. \gray{\LwhileGrammarPython} \\ \hline
  15329. \gray{\LtupGrammarPython} \\ \hline
  15330. \gray{\LfunGrammarPython} \\ \hline
  15331. \LlambdaGrammarPython \\
  15332. \begin{array}{lcl}
  15333. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15334. \end{array}
  15335. \end{array}
  15336. \]
  15337. \fi}
  15338. \end{tcolorbox}
  15339. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15340. with \key{lambda}.}
  15341. \label{fig:Llam-concrete-syntax}
  15342. \end{figure}
  15343. \begin{figure}[tp]
  15344. \centering
  15345. \begin{tcolorbox}[colback=white]
  15346. \small
  15347. {\if\edition\racketEd
  15348. \[\arraycolsep=3pt
  15349. \begin{array}{l}
  15350. \gray{\LintOpAST} \\ \hline
  15351. \gray{\LvarASTRacket{}} \\ \hline
  15352. \gray{\LifASTRacket{}} \\ \hline
  15353. \gray{\LwhileASTRacket{}} \\ \hline
  15354. \gray{\LtupASTRacket{}} \\ \hline
  15355. \gray{\LfunASTRacket} \\ \hline
  15356. \LlambdaASTRacket \\
  15357. \begin{array}{lcl}
  15358. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15359. \end{array}
  15360. \end{array}
  15361. \]
  15362. \fi}
  15363. {\if\edition\pythonEd\pythonColor
  15364. \[
  15365. \begin{array}{l}
  15366. \gray{\LintASTPython} \\ \hline
  15367. \gray{\LvarASTPython{}} \\ \hline
  15368. \gray{\LifASTPython{}} \\ \hline
  15369. \gray{\LwhileASTPython{}} \\ \hline
  15370. \gray{\LtupASTPython{}} \\ \hline
  15371. \gray{\LfunASTPython} \\ \hline
  15372. \LlambdaASTPython \\
  15373. \begin{array}{lcl}
  15374. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15375. \end{array}
  15376. \end{array}
  15377. \]
  15378. \fi}
  15379. \end{tcolorbox}
  15380. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15381. \label{fig:Llam-syntax}
  15382. \end{figure}
  15383. Figure~\ref{fig:interp-Llambda} shows the definitional
  15384. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15385. \key{Lambda} saves the current environment inside the returned
  15386. function value. Recall that during function application, the
  15387. environment stored in the function value, extended with the mapping of
  15388. parameters to argument values, is used to interpret the body of the
  15389. function.
  15390. \begin{figure}[tbp]
  15391. \begin{tcolorbox}[colback=white]
  15392. {\if\edition\racketEd
  15393. \begin{lstlisting}
  15394. (define interp-Llambda-class
  15395. (class interp-Lfun-class
  15396. (super-new)
  15397. (define/override (interp-op op)
  15398. (match op
  15399. ['procedure-arity
  15400. (lambda (v)
  15401. (match v
  15402. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15403. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15404. [else (super interp-op op)]))
  15405. (define/override ((interp-exp env) e)
  15406. (define recur (interp-exp env))
  15407. (match e
  15408. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15409. `(function ,xs ,body ,env)]
  15410. [else ((super interp-exp env) e)]))
  15411. ))
  15412. (define (interp-Llambda p)
  15413. (send (new interp-Llambda-class) interp-program p))
  15414. \end{lstlisting}
  15415. \fi}
  15416. {\if\edition\pythonEd\pythonColor
  15417. \begin{lstlisting}
  15418. class InterpLlambda(InterpLfun):
  15419. def arity(self, v):
  15420. match v:
  15421. case Function(name, params, body, env):
  15422. return len(params)
  15423. case _:
  15424. raise Exception('Llambda arity unexpected ' + repr(v))
  15425. def interp_exp(self, e, env):
  15426. match e:
  15427. case Call(Name('arity'), [fun]):
  15428. f = self.interp_exp(fun, env)
  15429. return self.arity(f)
  15430. case Lambda(params, body):
  15431. return Function('lambda', params, [Return(body)], env)
  15432. case _:
  15433. return super().interp_exp(e, env)
  15434. def interp_stmt(self, s, env, cont):
  15435. match s:
  15436. case AnnAssign(lhs, typ, value, simple):
  15437. env[lhs.id] = self.interp_exp(value, env)
  15438. return self.interp_stmts(cont, env)
  15439. case Pass():
  15440. return self.interp_stmts(cont, env)
  15441. case _:
  15442. return super().interp_stmt(s, env, cont)
  15443. \end{lstlisting}
  15444. \fi}
  15445. \end{tcolorbox}
  15446. \caption{Interpreter for \LangLam{}.}
  15447. \label{fig:interp-Llambda}
  15448. \end{figure}
  15449. {\if\edition\racketEd
  15450. %
  15451. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15452. \key{lambda} form. The body of the \key{lambda} is checked in an
  15453. environment that includes the current environment (because it is
  15454. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15455. require the body's type to match the declared return type.
  15456. %
  15457. \fi}
  15458. {\if\edition\pythonEd\pythonColor
  15459. %
  15460. Figures~\ref{fig:type-check-Llambda} and
  15461. \ref{fig:type-check-Llambda-part2} define the type checker for
  15462. \LangLam{}, which is more complex than one might expect. The reason
  15463. for the added complexity is that the syntax of \key{lambda} does not
  15464. include type annotations for the parameters or return type. Instead
  15465. they must be inferred. There are many approaches of type inference to
  15466. choose from of varying degrees of complexity. We choose one of the
  15467. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  15468. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  15469. this book is compilation, not type inference.
  15470. The main idea of bidirectional type inference is to add an auxiliary
  15471. function, here named \code{check\_exp}, that takes an expected type
  15472. and checks whether the given expression is of that type. Thus, in
  15473. \code{check\_exp}, type information flows in a top-down manner with
  15474. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15475. function, where type information flows in a primarily bottom-up
  15476. manner.
  15477. %
  15478. The idea then is to use \code{check\_exp} in all the places where we
  15479. already know what the type of an expression should be, such as in the
  15480. \code{return} statement of a top-level function definition, or on the
  15481. right-hand side of an annotated assignment statement.
  15482. Getting back to \code{lambda}, it is straightforward to check a
  15483. \code{lambda} inside \code{check\_exp} because the expected type
  15484. provides the parameter types and the return type. On the other hand,
  15485. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15486. that we do not allow \code{lambda} in contexts where we don't already
  15487. know its type. This restriction does not incur a loss of
  15488. expressiveness for \LangLam{} because it is straightforward to modify
  15489. a program to sidestep the restriction, for example, by using an
  15490. annotated assignment statement to assign the \code{lambda} to a
  15491. temporary variable.
  15492. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15493. checker records their type in a \code{has\_type} field. This type
  15494. information is used later in this chapter.
  15495. %
  15496. \fi}
  15497. \begin{figure}[tbp]
  15498. \begin{tcolorbox}[colback=white]
  15499. {\if\edition\racketEd
  15500. \begin{lstlisting}
  15501. (define (type-check-Llambda env)
  15502. (lambda (e)
  15503. (match e
  15504. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15505. (define-values (new-body bodyT)
  15506. ((type-check-exp (append (map cons xs Ts) env)) body))
  15507. (define ty `(,@Ts -> ,rT))
  15508. (cond
  15509. [(equal? rT bodyT)
  15510. (values (HasType (Lambda params rT new-body) ty) ty)]
  15511. [else
  15512. (error "mismatch in return type" bodyT rT)])]
  15513. ...
  15514. )))
  15515. \end{lstlisting}
  15516. \fi}
  15517. {\if\edition\pythonEd\pythonColor
  15518. \begin{lstlisting}
  15519. class TypeCheckLlambda(TypeCheckLfun):
  15520. def type_check_exp(self, e, env):
  15521. match e:
  15522. case Name(id):
  15523. e.has_type = env[id]
  15524. return env[id]
  15525. case Lambda(params, body):
  15526. raise Exception('cannot synthesize a type for a lambda')
  15527. case Call(Name('arity'), [func]):
  15528. func_t = self.type_check_exp(func, env)
  15529. match func_t:
  15530. case FunctionType(params_t, return_t):
  15531. return IntType()
  15532. case _:
  15533. raise Exception('in arity, unexpected ' + repr(func_t))
  15534. case _:
  15535. return super().type_check_exp(e, env)
  15536. def check_exp(self, e, ty, env):
  15537. match e:
  15538. case Lambda(params, body):
  15539. e.has_type = ty
  15540. match ty:
  15541. case FunctionType(params_t, return_t):
  15542. new_env = env.copy().update(zip(params, params_t))
  15543. self.check_exp(body, return_t, new_env)
  15544. case _:
  15545. raise Exception('lambda does not have type ' + str(ty))
  15546. case Call(func, args):
  15547. func_t = self.type_check_exp(func, env)
  15548. match func_t:
  15549. case FunctionType(params_t, return_t):
  15550. for (arg, param_t) in zip(args, params_t):
  15551. self.check_exp(arg, param_t, env)
  15552. self.check_type_equal(return_t, ty, e)
  15553. case _:
  15554. raise Exception('type_check_exp: in call, unexpected ' + \
  15555. repr(func_t))
  15556. case _:
  15557. t = self.type_check_exp(e, env)
  15558. self.check_type_equal(t, ty, e)
  15559. \end{lstlisting}
  15560. \fi}
  15561. \end{tcolorbox}
  15562. \caption{Type checking \LangLam{}\python{, part 1}.}
  15563. \label{fig:type-check-Llambda}
  15564. \end{figure}
  15565. {\if\edition\pythonEd\pythonColor
  15566. \begin{figure}[tbp]
  15567. \begin{tcolorbox}[colback=white]
  15568. \begin{lstlisting}
  15569. def check_stmts(self, ss, return_ty, env):
  15570. if len(ss) == 0:
  15571. return
  15572. match ss[0]:
  15573. case FunctionDef(name, params, body, dl, returns, comment):
  15574. new_env = env.copy().update(params)
  15575. rt = self.check_stmts(body, returns, new_env)
  15576. self.check_stmts(ss[1:], return_ty, env)
  15577. case Return(value):
  15578. self.check_exp(value, return_ty, env)
  15579. case Assign([Name(id)], value):
  15580. if id in env:
  15581. self.check_exp(value, env[id], env)
  15582. else:
  15583. env[id] = self.type_check_exp(value, env)
  15584. self.check_stmts(ss[1:], return_ty, env)
  15585. case Assign([Subscript(tup, Constant(index), Store())], value):
  15586. tup_t = self.type_check_exp(tup, env)
  15587. match tup_t:
  15588. case TupleType(ts):
  15589. self.check_exp(value, ts[index], env)
  15590. case _:
  15591. raise Exception('expected a tuple, not ' + repr(tup_t))
  15592. self.check_stmts(ss[1:], return_ty, env)
  15593. case AnnAssign(Name(id), ty_annot, value, simple):
  15594. ss[0].annotation = ty_annot
  15595. if id in env:
  15596. self.check_type_equal(env[id], ty_annot)
  15597. else:
  15598. env[id] = ty_annot
  15599. self.check_exp(value, ty_annot, env)
  15600. self.check_stmts(ss[1:], return_ty, env)
  15601. case _:
  15602. self.type_check_stmts(ss, env)
  15603. def type_check(self, p):
  15604. match p:
  15605. case Module(body):
  15606. env = {}
  15607. for s in body:
  15608. match s:
  15609. case FunctionDef(name, params, bod, dl, returns, comment):
  15610. params_t = [t for (x,t) in params]
  15611. env[name] = FunctionType(params_t, returns)
  15612. self.check_stmts(body, int, env)
  15613. \end{lstlisting}
  15614. \end{tcolorbox}
  15615. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15616. \label{fig:type-check-Llambda-part2}
  15617. \end{figure}
  15618. \fi}
  15619. \clearpage
  15620. \section{Assignment and Lexically Scoped Functions}
  15621. \label{sec:assignment-scoping}
  15622. The combination of lexically scoped functions and assignment to
  15623. variables raises a challenge with the flat-closure approach to
  15624. implementing lexically scoped functions. Consider the following
  15625. example in which function \code{f} has a free variable \code{x} that
  15626. is changed after \code{f} is created but before the call to \code{f}.
  15627. % loop_test_11.rkt
  15628. {\if\edition\racketEd
  15629. \begin{lstlisting}
  15630. (let ([x 0])
  15631. (let ([y 0])
  15632. (let ([z 20])
  15633. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15634. (begin
  15635. (set! x 10)
  15636. (set! y 12)
  15637. (f y))))))
  15638. \end{lstlisting}
  15639. \fi}
  15640. {\if\edition\pythonEd\pythonColor
  15641. % box_free_assign.py
  15642. \begin{lstlisting}
  15643. def g(z : int) -> int:
  15644. x = 0
  15645. y = 0
  15646. f : Callable[[int],int] = lambda a: a + x + z
  15647. x = 10
  15648. y = 12
  15649. return f(y)
  15650. print( g(20) )
  15651. \end{lstlisting}
  15652. \fi} The correct output for this example is \code{42} because the call
  15653. to \code{f} is required to use the current value of \code{x} (which is
  15654. \code{10}). Unfortunately, the closure conversion pass
  15655. (section~\ref{sec:closure-conversion}) generates code for the
  15656. \code{lambda} that copies the old value of \code{x} into a
  15657. closure. Thus, if we naively applied closure conversion, the output of
  15658. this program would be \code{32}.
  15659. A first attempt at solving this problem would be to save a pointer to
  15660. \code{x} in the closure and change the occurrences of \code{x} inside
  15661. the lambda to dereference the pointer. Of course, this would require
  15662. assigning \code{x} to the stack and not to a register. However, the
  15663. problem goes a bit deeper.
  15664. Consider the following example that returns a function that refers to
  15665. a local variable of the enclosing function:
  15666. \begin{center}
  15667. \begin{minipage}{\textwidth}
  15668. {\if\edition\racketEd
  15669. \begin{lstlisting}
  15670. (define (f) : ( -> Integer)
  15671. (let ([x 0])
  15672. (let ([g (lambda: () : Integer x)])
  15673. (begin
  15674. (set! x 42)
  15675. g))))
  15676. ((f))
  15677. \end{lstlisting}
  15678. \fi}
  15679. {\if\edition\pythonEd\pythonColor
  15680. % counter.py
  15681. \begin{lstlisting}
  15682. def f():
  15683. x = 0
  15684. g = lambda: x
  15685. x = 42
  15686. return g
  15687. print( f()() )
  15688. \end{lstlisting}
  15689. \fi}
  15690. \end{minipage}
  15691. \end{center}
  15692. In this example, the lifetime of \code{x} extends beyond the lifetime
  15693. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15694. stack frame for the call to \code{f}, it would be gone by the time we
  15695. called \code{g}, leaving us with dangling pointers for
  15696. \code{x}. This example demonstrates that when a variable occurs free
  15697. inside a function, its lifetime becomes indefinite. Thus, the value of
  15698. the variable needs to live on the heap. The verb
  15699. \emph{box}\index{subject}{box} is often used for allocating a single
  15700. value on the heap, producing a pointer, and
  15701. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15702. %
  15703. We introduce a new pass named \code{convert\_assignments} to address
  15704. this challenge.
  15705. %
  15706. \python{But before diving into that, we have one more
  15707. problem to discuss.}
  15708. {\if\edition\pythonEd\pythonColor
  15709. \section{Uniquify Variables}
  15710. \label{sec:uniquify-lambda}
  15711. With the addition of \code{lambda} we have a complication to deal
  15712. with: name shadowing. Consider the following program with a function
  15713. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15714. \code{lambda} expressions. The first \code{lambda} has a parameter
  15715. that is also named \code{x}.
  15716. \begin{lstlisting}
  15717. def f(x:int, y:int) -> Callable[[int], int]:
  15718. g : Callable[[int],int] = (lambda x: x + y)
  15719. h : Callable[[int],int] = (lambda y: x + y)
  15720. x = input_int()
  15721. return g
  15722. print(f(0, 10)(32))
  15723. \end{lstlisting}
  15724. Many of our compiler passes rely on being able to connect variable
  15725. uses with their definitions using just the name of the variable,
  15726. including new passes in this chapter. However, in the above example
  15727. the name of the variable does not uniquely determine its
  15728. definition. To solve this problem we recommend implementing a pass
  15729. named \code{uniquify} that renames every variable in the program to
  15730. make sure they are all unique.
  15731. The following shows the result of \code{uniquify} for the above
  15732. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  15733. and the \code{x} parameter of the \code{lambda} is renamed to
  15734. \code{x\_4}.
  15735. \begin{lstlisting}
  15736. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15737. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15738. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15739. x_0 = input_int()
  15740. return g_2
  15741. def main() -> int :
  15742. print(f(0, 10)(32))
  15743. return 0
  15744. \end{lstlisting}
  15745. \fi} % pythonEd
  15746. %% \section{Reveal Functions}
  15747. %% \label{sec:reveal-functions-r5}
  15748. %% \racket{To support the \code{procedure-arity} operator we need to
  15749. %% communicate the arity of a function to the point of closure
  15750. %% creation.}
  15751. %% %
  15752. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15753. %% function at runtime. Thus, we need to communicate the arity of a
  15754. %% function to the point of closure creation.}
  15755. %% %
  15756. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15757. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15758. %% \[
  15759. %% \begin{array}{lcl}
  15760. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15761. %% \end{array}
  15762. %% \]
  15763. \section{Assignment Conversion}
  15764. \label{sec:convert-assignments}
  15765. The purpose of the \code{convert\_assignments} pass is to address the
  15766. challenge regarding the interaction between variable assignments and
  15767. closure conversion. First we identify which variables need to be
  15768. boxed, and then we transform the program to box those variables. In
  15769. general, boxing introduces runtime overhead that we would like to
  15770. avoid, so we should box as few variables as possible. We recommend
  15771. boxing the variables in the intersection of the following two sets of
  15772. variables:
  15773. \begin{enumerate}
  15774. \item The variables that are free in a \code{lambda}.
  15775. \item The variables that appear on the left-hand side of an
  15776. assignment.
  15777. \end{enumerate}
  15778. The first condition is a must but the second condition is
  15779. conservative. It is possible to develop a more liberal condition using
  15780. static program analysis.
  15781. Consider again the first example from
  15782. section~\ref{sec:assignment-scoping}:
  15783. %
  15784. {\if\edition\racketEd
  15785. \begin{lstlisting}
  15786. (let ([x 0])
  15787. (let ([y 0])
  15788. (let ([z 20])
  15789. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15790. (begin
  15791. (set! x 10)
  15792. (set! y 12)
  15793. (f y))))))
  15794. \end{lstlisting}
  15795. \fi}
  15796. {\if\edition\pythonEd\pythonColor
  15797. \begin{lstlisting}
  15798. def g(z : int) -> int:
  15799. x = 0
  15800. y = 0
  15801. f : Callable[[int],int] = lambda a: a + x + z
  15802. x = 10
  15803. y = 12
  15804. return f(y)
  15805. print( g(20) )
  15806. \end{lstlisting}
  15807. \fi}
  15808. %
  15809. \noindent The variables \code{x} and \code{y} appear on the left-hand
  15810. side of assignments. The variables \code{x} and \code{z} occur free
  15811. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  15812. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  15813. three transformations: initialize \code{x} with a tuple whose elements
  15814. are uninitialized, replace reads from \code{x} with tuple reads, and
  15815. replace each assignment to \code{x} with a tuple write. The output of
  15816. \code{convert\_assignments} for this example is as follows:
  15817. %
  15818. {\if\edition\racketEd
  15819. \begin{lstlisting}
  15820. (define (main) : Integer
  15821. (let ([x0 (vector 0)])
  15822. (let ([y1 0])
  15823. (let ([z2 20])
  15824. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  15825. (+ a3 (+ (vector-ref x0 0) z2)))])
  15826. (begin
  15827. (vector-set! x0 0 10)
  15828. (set! y1 12)
  15829. (f4 y1)))))))
  15830. \end{lstlisting}
  15831. \fi}
  15832. %
  15833. {\if\edition\pythonEd\pythonColor
  15834. \begin{lstlisting}
  15835. def g(z : int)-> int:
  15836. x = (uninitialized(int),)
  15837. x[0] = 0
  15838. y = 0
  15839. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  15840. x[0] = 10
  15841. y = 12
  15842. return f(y)
  15843. def main() -> int:
  15844. print(g(20))
  15845. return 0
  15846. \end{lstlisting}
  15847. \fi}
  15848. To compute the free variables of all the \code{lambda} expressions, we
  15849. recommend defining the following two auxiliary functions:
  15850. \begin{enumerate}
  15851. \item \code{free\_variables} computes the free variables of an expression, and
  15852. \item \code{free\_in\_lambda} collects all the variables that are
  15853. free in any of the \code{lambda} expressions, using
  15854. \code{free\_variables} in the case for each \code{lambda}.
  15855. \end{enumerate}
  15856. {\if\edition\racketEd
  15857. %
  15858. To compute the variables that are assigned to, we recommend updating
  15859. the \code{collect-set!} function that we introduced in
  15860. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  15861. as \code{Lambda}.
  15862. %
  15863. \fi}
  15864. {\if\edition\pythonEd\pythonColor
  15865. %
  15866. To compute the variables that are assigned to, we recommend defining
  15867. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  15868. the set of variables that occur in the left-hand side of an assignment
  15869. statement, and otherwise returns the empty set.
  15870. %
  15871. \fi}
  15872. Let $\mathit{AF}$ be the intersection of the set of variables that are
  15873. free in a \code{lambda} and that are assigned to in the enclosing
  15874. function definition.
  15875. Next we discuss the \code{convert\_assignments} pass. In the case for
  15876. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  15877. $\VAR{x}$ to a tuple read.
  15878. %
  15879. {\if\edition\racketEd
  15880. \begin{lstlisting}
  15881. (Var |$x$|)
  15882. |$\Rightarrow$|
  15883. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  15884. \end{lstlisting}
  15885. \fi}
  15886. %
  15887. {\if\edition\pythonEd\pythonColor
  15888. \begin{lstlisting}
  15889. Name(|$x$|)
  15890. |$\Rightarrow$|
  15891. Subscript(Name(|$x$|), Constant(0), Load())
  15892. \end{lstlisting}
  15893. \fi}
  15894. %
  15895. \noindent In the case for assignment, recursively process the
  15896. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  15897. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  15898. as follows:
  15899. %
  15900. {\if\edition\racketEd
  15901. \begin{lstlisting}
  15902. (SetBang |$x$| |$\itm{rhs}$|)
  15903. |$\Rightarrow$|
  15904. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  15905. \end{lstlisting}
  15906. \fi}
  15907. {\if\edition\pythonEd\pythonColor
  15908. \begin{lstlisting}
  15909. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  15910. |$\Rightarrow$|
  15911. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  15912. \end{lstlisting}
  15913. \fi}
  15914. %
  15915. {\if\edition\racketEd
  15916. The case for \code{Lambda} is nontrivial, but it is similar to the
  15917. case for function definitions, which we discuss next.
  15918. \fi}
  15919. %
  15920. To translate a function definition, we first compute $\mathit{AF}$,
  15921. the intersection of the variables that are free in a \code{lambda} and
  15922. that are assigned to. We then apply assignment conversion to the body
  15923. of the function definition. Finally, we box the parameters of this
  15924. function definition that are in $\mathit{AF}$. For example,
  15925. the parameter \code{x} of the following function \code{g}
  15926. needs to be boxed:
  15927. {\if\edition\racketEd
  15928. \begin{lstlisting}
  15929. (define (g [x : Integer]) : Integer
  15930. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  15931. (begin
  15932. (set! x 10)
  15933. (f 32))))
  15934. \end{lstlisting}
  15935. \fi}
  15936. %
  15937. {\if\edition\pythonEd\pythonColor
  15938. \begin{lstlisting}
  15939. def g(x : int) -> int:
  15940. f : Callable[[int],int] = lambda a: a + x
  15941. x = 10
  15942. return f(32)
  15943. \end{lstlisting}
  15944. \fi}
  15945. %
  15946. \noindent We box parameter \code{x} by creating a local variable named
  15947. \code{x} that is initialized to a tuple whose contents is the value of
  15948. the parameter, which has been renamed to \code{x\_0}.
  15949. %
  15950. {\if\edition\racketEd
  15951. \begin{lstlisting}
  15952. (define (g [x_0 : Integer]) : Integer
  15953. (let ([x (vector x_0)])
  15954. (let ([f (lambda: ([a : Integer]) : Integer
  15955. (+ a (vector-ref x 0)))])
  15956. (begin
  15957. (vector-set! x 0 10)
  15958. (f 32)))))
  15959. \end{lstlisting}
  15960. \fi}
  15961. %
  15962. {\if\edition\pythonEd\pythonColor
  15963. \begin{lstlisting}
  15964. def g(x_0 : int)-> int:
  15965. x = (x_0,)
  15966. f : Callable[[int], int] = (lambda a: a + x[0])
  15967. x[0] = 10
  15968. return f(32)
  15969. \end{lstlisting}
  15970. \fi}
  15971. \section{Closure Conversion}
  15972. \label{sec:closure-conversion}
  15973. \index{subject}{closure conversion}
  15974. The compiling of lexically scoped functions into top-level function
  15975. definitions and flat closures is accomplished in the pass
  15976. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15977. and before \code{limit\_functions}.
  15978. As usual, we implement the pass as a recursive function over the
  15979. AST. The interesting cases are for \key{lambda} and function
  15980. application. We transform a \key{lambda} expression into an expression
  15981. that creates a closure, that is, a tuple for which the first element
  15982. is a function pointer and the rest of the elements are the values of
  15983. the free variables of the \key{lambda}.
  15984. %
  15985. However, we use the \code{Closure} AST node instead of using a tuple
  15986. so that we can record the arity.
  15987. %
  15988. In the generated code that follows, \itm{fvs} is the free variables of
  15989. the lambda and \itm{name} is a unique symbol generated to identify the
  15990. lambda.
  15991. %
  15992. \racket{The \itm{arity} is the number of parameters (the length of
  15993. \itm{ps}).}
  15994. %
  15995. {\if\edition\racketEd
  15996. \begin{lstlisting}
  15997. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15998. |$\Rightarrow$|
  15999. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16000. \end{lstlisting}
  16001. \fi}
  16002. %
  16003. {\if\edition\pythonEd\pythonColor
  16004. \begin{lstlisting}
  16005. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16006. |$\Rightarrow$|
  16007. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  16008. \end{lstlisting}
  16009. \fi}
  16010. %
  16011. In addition to transforming each \key{Lambda} AST node into a
  16012. tuple, we create a top-level function definition for each
  16013. \key{Lambda}, as shown next.\\
  16014. \begin{minipage}{0.8\textwidth}
  16015. {\if\edition\racketEd
  16016. \begin{lstlisting}
  16017. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16018. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16019. ...
  16020. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16021. |\itm{body'}|)...))
  16022. \end{lstlisting}
  16023. \fi}
  16024. {\if\edition\pythonEd\pythonColor
  16025. \begin{lstlisting}
  16026. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  16027. |$\itm{fvs}_1$| = clos[1]
  16028. |$\ldots$|
  16029. |$\itm{fvs}_n$| = clos[|$n$|]
  16030. |\itm{body'}|
  16031. \end{lstlisting}
  16032. \fi}
  16033. \end{minipage}\\
  16034. The \code{clos} parameter refers to the closure. Translate the type
  16035. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16036. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  16037. \itm{closTy} is a tuple type for which the first element type is
  16038. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  16039. the element types are the types of the free variables in the
  16040. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16041. is nontrivial to give a type to the function in the closure's type.%
  16042. %
  16043. \footnote{To give an accurate type to a closure, we would need to add
  16044. existential types to the type checker~\citep{Minamide:1996ys}.}
  16045. %
  16046. %% The dummy type is considered to be equal to any other type during type
  16047. %% checking.
  16048. The free variables become local variables that are initialized with
  16049. their values in the closure.
  16050. Closure conversion turns every function into a tuple, so the type
  16051. annotations in the program must also be translated. We recommend
  16052. defining an auxiliary recursive function for this purpose. Function
  16053. types should be translated as follows:
  16054. %
  16055. {\if\edition\racketEd
  16056. \begin{lstlisting}
  16057. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16058. |$\Rightarrow$|
  16059. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16060. \end{lstlisting}
  16061. \fi}
  16062. {\if\edition\pythonEd\pythonColor
  16063. \begin{lstlisting}
  16064. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16065. |$\Rightarrow$|
  16066. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16067. \end{lstlisting}
  16068. \fi}
  16069. %
  16070. This type indicates that the first thing in the tuple is a
  16071. function. The first parameter of the function is a tuple (a closure)
  16072. and the rest of the parameters are the ones from the original
  16073. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16074. omits the types of the free variables because (1) those types are not
  16075. available in this context, and (2) we do not need them in the code that
  16076. is generated for function application. So this type describes only the
  16077. first component of the closure tuple. At runtime the tuple may have
  16078. more components, but we ignore them at this point.
  16079. We transform function application into code that retrieves the
  16080. function from the closure and then calls the function, passing the
  16081. closure as the first argument. We place $e'$ in a temporary variable
  16082. to avoid code duplication.
  16083. \begin{center}
  16084. \begin{minipage}{\textwidth}
  16085. {\if\edition\racketEd
  16086. \begin{lstlisting}
  16087. (Apply |$e$| |$\itm{es}$|)
  16088. |$\Rightarrow$|
  16089. (Let |$\itm{tmp}$| |$e'$|
  16090. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16091. \end{lstlisting}
  16092. \fi}
  16093. %
  16094. {\if\edition\pythonEd\pythonColor
  16095. \begin{lstlisting}
  16096. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16097. |$\Rightarrow$|
  16098. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16099. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16100. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16101. \end{lstlisting}
  16102. \fi}
  16103. \end{minipage}
  16104. \end{center}
  16105. There is also the question of what to do with references to top-level
  16106. function definitions. To maintain a uniform translation of function
  16107. application, we turn function references into closures.
  16108. \begin{tabular}{lll}
  16109. \begin{minipage}{0.2\textwidth}
  16110. {\if\edition\racketEd
  16111. \begin{lstlisting}
  16112. (FunRef |$f$| |$n$|)
  16113. \end{lstlisting}
  16114. \fi}
  16115. {\if\edition\pythonEd\pythonColor
  16116. \begin{lstlisting}
  16117. FunRef(|$f$|, |$n$|)
  16118. \end{lstlisting}
  16119. \fi}
  16120. \end{minipage}
  16121. &
  16122. $\Rightarrow\qquad$
  16123. &
  16124. \begin{minipage}{0.5\textwidth}
  16125. {\if\edition\racketEd
  16126. \begin{lstlisting}
  16127. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16128. \end{lstlisting}
  16129. \fi}
  16130. {\if\edition\pythonEd\pythonColor
  16131. \begin{lstlisting}
  16132. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16133. \end{lstlisting}
  16134. \fi}
  16135. \end{minipage}
  16136. \end{tabular} \\
  16137. We no longer need the annotated assignment statement \code{AnnAssign}
  16138. to support the type checking of \code{lambda} expressions, so we
  16139. translate it to a regular \code{Assign} statement.
  16140. The top-level function definitions need to be updated to take an extra
  16141. closure parameter, but that parameter is ignored in the body of those
  16142. functions.
  16143. \section{An Example Translation}
  16144. \label{sec:example-lambda}
  16145. Figure~\ref{fig:lexical-functions-example} shows the result of
  16146. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16147. program demonstrating lexical scoping that we discussed at the
  16148. beginning of this chapter.
  16149. \begin{figure}[tbp]
  16150. \begin{tcolorbox}[colback=white]
  16151. \begin{minipage}{0.8\textwidth}
  16152. {\if\edition\racketEd
  16153. % tests/lambda_test_6.rkt
  16154. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16155. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16156. (let ([y8 4])
  16157. (lambda: ([z9 : Integer]) : Integer
  16158. (+ x7 (+ y8 z9)))))
  16159. (define (main) : Integer
  16160. (let ([g0 ((fun-ref f6 1) 5)])
  16161. (let ([h1 ((fun-ref f6 1) 3)])
  16162. (+ (g0 11) (h1 15)))))
  16163. \end{lstlisting}
  16164. $\Rightarrow$
  16165. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16166. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16167. (let ([y8 4])
  16168. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16169. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16170. (let ([x7 (vector-ref fvs3 1)])
  16171. (let ([y8 (vector-ref fvs3 2)])
  16172. (+ x7 (+ y8 z9)))))
  16173. (define (main) : Integer
  16174. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16175. ((vector-ref clos5 0) clos5 5))])
  16176. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16177. ((vector-ref clos6 0) clos6 3))])
  16178. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16179. \end{lstlisting}
  16180. \fi}
  16181. %
  16182. {\if\edition\pythonEd\pythonColor
  16183. % free_var.py
  16184. \begin{lstlisting}
  16185. def f(x : int) -> Callable[[int], int]:
  16186. y = 4
  16187. return lambda z: x + y + z
  16188. g = f(5)
  16189. h = f(3)
  16190. print( g(11) + h(15) )
  16191. \end{lstlisting}
  16192. $\Rightarrow$
  16193. \begin{lstlisting}
  16194. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  16195. x = fvs_1[1]
  16196. y = fvs_1[2]
  16197. return x + y[0] + z
  16198. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  16199. y = (777,)
  16200. y[0] = 4
  16201. return (lambda_0, x, y)
  16202. def main() -> int:
  16203. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  16204. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  16205. print((let clos_5 = g in clos_5[0](clos_5, 11))
  16206. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  16207. return 0
  16208. \end{lstlisting}
  16209. \fi}
  16210. \end{minipage}
  16211. \end{tcolorbox}
  16212. \caption{Example of closure conversion.}
  16213. \label{fig:lexical-functions-example}
  16214. \end{figure}
  16215. \begin{exercise}\normalfont\normalsize
  16216. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16217. Create five new programs that use \key{lambda} functions and make use of
  16218. lexical scoping. Test your compiler on these new programs and all
  16219. your previously created test programs.
  16220. \end{exercise}
  16221. \section{Expose Allocation}
  16222. \label{sec:expose-allocation-r5}
  16223. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16224. that allocates and initializes a tuple, similar to the translation of
  16225. the tuple creation in section~\ref{sec:expose-allocation}.
  16226. The only difference is replacing the use of
  16227. \ALLOC{\itm{len}}{\itm{type}} with
  16228. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16229. \section{Explicate Control and \LangCLam{}}
  16230. \label{sec:explicate-r5}
  16231. The output language of \code{explicate\_control} is \LangCLam{}; the
  16232. definition of its abstract syntax is shown in
  16233. figure~\ref{fig:Clam-syntax}.
  16234. %
  16235. \racket{The only differences with respect to \LangCFun{} are the
  16236. addition of the \code{AllocateClosure} form to the grammar for
  16237. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16238. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16239. similar to the handling of other expressions such as primitive
  16240. operators.}
  16241. %
  16242. \python{The differences with respect to \LangCFun{} are the
  16243. additions of \code{Uninitialized}, \code{AllocateClosure},
  16244. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16245. \code{explicate\_control} pass is similar to the handling of other
  16246. expressions such as primitive operators.}
  16247. \newcommand{\ClambdaASTRacket}{
  16248. \begin{array}{lcl}
  16249. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16250. \itm{op} &::= & \code{procedure-arity}
  16251. \end{array}
  16252. }
  16253. \newcommand{\ClambdaASTPython}{
  16254. \begin{array}{lcl}
  16255. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16256. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16257. &\MID& \ARITY{\Atm}
  16258. \end{array}
  16259. }
  16260. \begin{figure}[tp]
  16261. \begin{tcolorbox}[colback=white]
  16262. \small
  16263. {\if\edition\racketEd
  16264. \[
  16265. \begin{array}{l}
  16266. \gray{\CvarASTRacket} \\ \hline
  16267. \gray{\CifASTRacket} \\ \hline
  16268. \gray{\CloopASTRacket} \\ \hline
  16269. \gray{\CtupASTRacket} \\ \hline
  16270. \gray{\CfunASTRacket} \\ \hline
  16271. \ClambdaASTRacket \\
  16272. \begin{array}{lcl}
  16273. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16274. \end{array}
  16275. \end{array}
  16276. \]
  16277. \fi}
  16278. {\if\edition\pythonEd\pythonColor
  16279. \[
  16280. \begin{array}{l}
  16281. \gray{\CifASTPython} \\ \hline
  16282. \gray{\CtupASTPython} \\ \hline
  16283. \gray{\CfunASTPython} \\ \hline
  16284. \ClambdaASTPython \\
  16285. \begin{array}{lcl}
  16286. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16287. \end{array}
  16288. \end{array}
  16289. \]
  16290. \fi}
  16291. \end{tcolorbox}
  16292. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16293. \label{fig:Clam-syntax}
  16294. \end{figure}
  16295. \section{Select Instructions}
  16296. \label{sec:select-instructions-Llambda}
  16297. \index{subject}{select instructions}
  16298. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16299. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16300. (section~\ref{sec:select-instructions-gc}). The only difference is
  16301. that you should place the \itm{arity} in the tag that is stored at
  16302. position $0$ of the vector. Recall that in
  16303. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16304. was not used. We store the arity in the $5$ bits starting at position
  16305. $58$.
  16306. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16307. instructions that access the tag from position $0$ of the vector and
  16308. extract the $5$ bits starting at position $58$ from the tag.}
  16309. %
  16310. \python{Compile a call to the \code{arity} operator to a sequence of
  16311. instructions that access the tag from position $0$ of the tuple
  16312. (representing a closure) and extract the $5$-bits starting at position
  16313. $58$ from the tag.}
  16314. \begin{figure}[p]
  16315. \begin{tcolorbox}[colback=white]
  16316. {\if\edition\racketEd
  16317. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16318. \node (Lfun) at (0,2) {\large \LangLam{}};
  16319. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16320. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16321. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16322. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16323. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16324. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16325. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16326. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16327. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16328. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16329. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16330. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16331. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16332. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16333. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16334. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16335. \path[->,bend left=15] (Lfun) edge [above] node
  16336. {\ttfamily\footnotesize shrink} (Lfun-2);
  16337. \path[->,bend left=15] (Lfun-2) edge [above] node
  16338. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16339. \path[->,bend left=15] (Lfun-3) edge [above] node
  16340. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16341. \path[->,bend left=15] (F1-0) edge [left] node
  16342. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16343. \path[->,bend left=15] (F1-1) edge [below] node
  16344. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16345. \path[->,bend right=15] (F1-2) edge [above] node
  16346. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16347. \path[->,bend right=15] (F1-3) edge [above] node
  16348. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16349. \path[->,bend left=15] (F1-4) edge [right] node
  16350. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16351. \path[->,bend right=15] (F1-5) edge [below] node
  16352. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16353. \path[->,bend left=15] (F1-6) edge [above] node
  16354. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16355. \path[->] (C3-2) edge [right] node
  16356. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16357. \path[->,bend right=15] (x86-2) edge [right] node
  16358. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16359. \path[->,bend right=15] (x86-2-1) edge [below] node
  16360. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16361. \path[->,bend right=15] (x86-2-2) edge [right] node
  16362. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16363. \path[->,bend left=15] (x86-3) edge [above] node
  16364. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16365. \path[->,bend left=15] (x86-4) edge [right] node
  16366. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16367. \end{tikzpicture}
  16368. \fi}
  16369. {\if\edition\pythonEd\pythonColor
  16370. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16371. \node (Lfun) at (0,2) {\large \LangLam{}};
  16372. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16373. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16374. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16375. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16376. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16377. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16378. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16379. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16380. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16381. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16382. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16383. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16384. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16385. \path[->,bend left=15] (Lfun) edge [above] node
  16386. {\ttfamily\footnotesize shrink} (Lfun-2);
  16387. \path[->,bend left=15] (Lfun-2) edge [above] node
  16388. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16389. \path[->,bend left=15] (Lfun-3) edge [above] node
  16390. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16391. \path[->,bend left=15] (F1-0) edge [left] node
  16392. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16393. \path[->,bend left=15] (F1-1) edge [below] node
  16394. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16395. \path[->,bend left=15] (F1-2) edge [below] node
  16396. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16397. \path[->,bend right=15] (F1-3) edge [above] node
  16398. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16399. \path[->,bend right=15] (F1-5) edge [right] node
  16400. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16401. \path[->,bend left=15] (F1-6) edge [right] node
  16402. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16403. \path[->,bend right=15] (C3-2) edge [right] node
  16404. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16405. \path[->,bend right=15] (x86-2) edge [below] node
  16406. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16407. \path[->,bend right=15] (x86-3) edge [below] node
  16408. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16409. \path[->,bend left=15] (x86-4) edge [above] node
  16410. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16411. \end{tikzpicture}
  16412. \fi}
  16413. \end{tcolorbox}
  16414. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16415. functions.}
  16416. \label{fig:Llambda-passes}
  16417. \end{figure}
  16418. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16419. needed for the compilation of \LangLam{}.
  16420. \clearpage
  16421. \section{Challenge: Optimize Closures}
  16422. \label{sec:optimize-closures}
  16423. In this chapter we compile lexically scoped functions into a
  16424. relatively efficient representation: flat closures. However, even this
  16425. representation comes with some overhead. For example, consider the
  16426. following program with a function \code{tail\_sum} that does not have
  16427. any free variables and where all the uses of \code{tail\_sum} are in
  16428. applications in which we know that only \code{tail\_sum} is being applied
  16429. (and not any other functions):
  16430. \begin{center}
  16431. \begin{minipage}{0.95\textwidth}
  16432. {\if\edition\racketEd
  16433. \begin{lstlisting}
  16434. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16435. (if (eq? n 0)
  16436. s
  16437. (tail_sum (- n 1) (+ n s))))
  16438. (+ (tail_sum 3 0) 36)
  16439. \end{lstlisting}
  16440. \fi}
  16441. {\if\edition\pythonEd\pythonColor
  16442. \begin{lstlisting}
  16443. def tail_sum(n : int, s : int) -> int:
  16444. if n == 0:
  16445. return s
  16446. else:
  16447. return tail_sum(n - 1, n + s)
  16448. print( tail_sum(3, 0) + 36)
  16449. \end{lstlisting}
  16450. \fi}
  16451. \end{minipage}
  16452. \end{center}
  16453. As described in this chapter, we uniformly apply closure conversion to
  16454. all functions, obtaining the following output for this program:
  16455. \begin{center}
  16456. \begin{minipage}{0.95\textwidth}
  16457. {\if\edition\racketEd
  16458. \begin{lstlisting}
  16459. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16460. (if (eq? n2 0)
  16461. s3
  16462. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16463. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16464. (define (main) : Integer
  16465. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16466. ((vector-ref clos6 0) clos6 3 0)) 27))
  16467. \end{lstlisting}
  16468. \fi}
  16469. {\if\edition\pythonEd\pythonColor
  16470. \begin{lstlisting}
  16471. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16472. if n_0 == 0:
  16473. return s_1
  16474. else:
  16475. return (let clos_2 = (tail_sum,)
  16476. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16477. def main() -> int :
  16478. print((let clos_4 = (tail_sum,)
  16479. in clos_4[0](clos_4, 3, 0)) + 36)
  16480. return 0
  16481. \end{lstlisting}
  16482. \fi}
  16483. \end{minipage}
  16484. \end{center}
  16485. If this program were compiled according to the previous chapter, there
  16486. would be no allocation and the calls to \code{tail\_sum} would be
  16487. direct calls. In contrast, the program presented here allocates memory
  16488. for each closure and the calls to \code{tail\_sum} are indirect. These
  16489. two differences incur considerable overhead in a program such as this,
  16490. in which the allocations and indirect calls occur inside a tight loop.
  16491. One might think that this problem is trivial to solve: can't we just
  16492. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16493. and compile them to direct calls instead of treating it like a call to
  16494. a closure? We would also drop the new \code{fvs} parameter of
  16495. \code{tail\_sum}.
  16496. %
  16497. However, this problem is not so trivial, because a global function may
  16498. \emph{escape} and become involved in applications that also involve
  16499. closures. Consider the following example in which the application
  16500. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16501. application because the \code{lambda} may flow into \code{f}, but the
  16502. \code{inc} function might also flow into \code{f}:
  16503. \begin{center}
  16504. \begin{minipage}{\textwidth}
  16505. % lambda_test_30.rkt
  16506. {\if\edition\racketEd
  16507. \begin{lstlisting}
  16508. (define (inc [x : Integer]) : Integer
  16509. (+ x 1))
  16510. (let ([y (read)])
  16511. (let ([f (if (eq? (read) 0)
  16512. inc
  16513. (lambda: ([x : Integer]) : Integer (- x y)))])
  16514. (f 41)))
  16515. \end{lstlisting}
  16516. \fi}
  16517. {\if\edition\pythonEd\pythonColor
  16518. \begin{lstlisting}
  16519. def add1(x : int) -> int:
  16520. return x + 1
  16521. y = input_int()
  16522. g : Callable[[int], int] = lambda x: x - y
  16523. f = add1 if input_int() == 0 else g
  16524. print( f(41) )
  16525. \end{lstlisting}
  16526. \fi}
  16527. \end{minipage}
  16528. \end{center}
  16529. If a global function name is used in any way other than as the
  16530. operator in a direct call, then we say that the function
  16531. \emph{escapes}. If a global function does not escape, then we do not
  16532. need to perform closure conversion on the function.
  16533. \begin{exercise}\normalfont\normalsize
  16534. Implement an auxiliary function for detecting which global
  16535. functions escape. Using that function, implement an improved version
  16536. of closure conversion that does not apply closure conversion to
  16537. global functions that do not escape but instead compiles them as
  16538. regular functions. Create several new test cases that check whether
  16539. your compiler properly detects whether global functions escape or not.
  16540. \end{exercise}
  16541. So far we have reduced the overhead of calling global functions, but
  16542. it would also be nice to reduce the overhead of calling a
  16543. \code{lambda} when we can determine at compile time which
  16544. \code{lambda} will be called. We refer to such calls as \emph{known
  16545. calls}. Consider the following example in which a \code{lambda} is
  16546. bound to \code{f} and then applied.
  16547. {\if\edition\racketEd
  16548. % lambda_test_9.rkt
  16549. \begin{lstlisting}
  16550. (let ([y (read)])
  16551. (let ([f (lambda: ([x : Integer]) : Integer
  16552. (+ x y))])
  16553. (f 21)))
  16554. \end{lstlisting}
  16555. \fi}
  16556. {\if\edition\pythonEd\pythonColor
  16557. \begin{lstlisting}
  16558. y = input_int()
  16559. f : Callable[[int],int] = lambda x: x + y
  16560. print( f(21) )
  16561. \end{lstlisting}
  16562. \fi}
  16563. %
  16564. \noindent Closure conversion compiles the application
  16565. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16566. %
  16567. {\if\edition\racketEd
  16568. \begin{lstlisting}
  16569. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16570. (let ([y2 (vector-ref fvs6 1)])
  16571. (+ x3 y2)))
  16572. (define (main) : Integer
  16573. (let ([y2 (read)])
  16574. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16575. ((vector-ref f4 0) f4 21))))
  16576. \end{lstlisting}
  16577. \fi}
  16578. {\if\edition\pythonEd\pythonColor
  16579. \begin{lstlisting}
  16580. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16581. y_1 = fvs_4[1]
  16582. return x_2 + y_1[0]
  16583. def main() -> int:
  16584. y_1 = (777,)
  16585. y_1[0] = input_int()
  16586. f_0 = (lambda_3, y_1)
  16587. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16588. return 0
  16589. \end{lstlisting}
  16590. \fi}
  16591. %
  16592. \noindent However, we can instead compile the application
  16593. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16594. %
  16595. {\if\edition\racketEd
  16596. \begin{lstlisting}
  16597. (define (main) : Integer
  16598. (let ([y2 (read)])
  16599. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16600. ((fun-ref lambda5 1) f4 21))))
  16601. \end{lstlisting}
  16602. \fi}
  16603. {\if\edition\pythonEd\pythonColor
  16604. \begin{lstlisting}
  16605. def main() -> int:
  16606. y_1 = (777,)
  16607. y_1[0] = input_int()
  16608. f_0 = (lambda_3, y_1)
  16609. print(lambda_3(f_0, 21))
  16610. return 0
  16611. \end{lstlisting}
  16612. \fi}
  16613. The problem of determining which \code{lambda} will be called from a
  16614. particular application is quite challenging in general and the topic
  16615. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16616. following exercise we recommend that you compile an application to a
  16617. direct call when the operator is a variable and \racket{the variable
  16618. is \code{let}-bound to a closure}\python{the previous assignment to
  16619. the variable is a closure}. This can be accomplished by maintaining
  16620. an environment that maps variables to function names. Extend the
  16621. environment whenever you encounter a closure on the right-hand side of
  16622. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  16623. name of the global function for the closure. This pass should come
  16624. after closure conversion.
  16625. \begin{exercise}\normalfont\normalsize
  16626. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16627. compiles known calls into direct calls. Verify that your compiler is
  16628. successful in this regard on several example programs.
  16629. \end{exercise}
  16630. These exercises only scratch the surface of closure optimization. A
  16631. good next step for the interested reader is to look at the work of
  16632. \citet{Keep:2012ab}.
  16633. \section{Further Reading}
  16634. The notion of lexically scoped functions predates modern computers by
  16635. about a decade. They were invented by \citet{Church:1932aa}, who
  16636. proposed the lambda calculus as a foundation for logic. Anonymous
  16637. functions were included in the LISP~\citep{McCarthy:1960dz}
  16638. programming language but were initially dynamically scoped. The Scheme
  16639. dialect of LISP adopted lexical scoping, and
  16640. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16641. Scheme programs. However, environments were represented as linked
  16642. lists, so variable look-up was linear in the size of the
  16643. environment. \citet{Appel91} gives a detailed description of several
  16644. closure representations. In this chapter we represent environments
  16645. using flat closures, which were invented by
  16646. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16647. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16648. closures, variable look-up is constant time but the time to create a
  16649. closure is proportional to the number of its free variables. Flat
  16650. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16651. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16652. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16653. % compilers)
  16654. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16655. \chapter{Dynamic Typing}
  16656. \label{ch:Ldyn}
  16657. \index{subject}{dynamic typing}
  16658. \setcounter{footnote}{0}
  16659. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16660. typed language that is a subset of \racket{Racket}\python{Python}. The
  16661. focus on dynamic typing is in contrast to the previous chapters, which
  16662. have studied the compilation of statically typed languages. In
  16663. dynamically typed languages such as \LangDyn{}, a particular
  16664. expression may produce a value of a different type each time it is
  16665. executed. Consider the following example with a conditional \code{if}
  16666. expression that may return a Boolean or an integer depending on the
  16667. input to the program:
  16668. % part of dynamic_test_25.rkt
  16669. {\if\edition\racketEd
  16670. \begin{lstlisting}
  16671. (not (if (eq? (read) 1) #f 0))
  16672. \end{lstlisting}
  16673. \fi}
  16674. {\if\edition\pythonEd\pythonColor
  16675. \begin{lstlisting}
  16676. not (False if input_int() == 1 else 0)
  16677. \end{lstlisting}
  16678. \fi}
  16679. Languages that allow expressions to produce different kinds of values
  16680. are called \emph{polymorphic}, a word composed of the Greek roots
  16681. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16682. There are several kinds of polymorphism in programming languages, such as
  16683. subtype polymorphism\index{subject}{subtype polymorphism} and
  16684. parametric polymorphism\index{subject}{parametric polymorphism}
  16685. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16686. study in this chapter does not have a special name; it is the kind
  16687. that arises in dynamically typed languages.
  16688. Another characteristic of dynamically typed languages is that
  16689. their primitive operations, such as \code{not}, are often defined to operate
  16690. on many different types of values. In fact, in
  16691. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16692. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16693. given anything else it returns \FALSE{}.
  16694. Furthermore, even when primitive operations restrict their inputs to
  16695. values of a certain type, this restriction is enforced at runtime
  16696. instead of during compilation. For example, the tuple read
  16697. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16698. results in a runtime error because the first argument must
  16699. be a tuple, not a Boolean.
  16700. \section{The \LangDyn{} Language}
  16701. \newcommand{\LdynGrammarRacket}{
  16702. \begin{array}{rcl}
  16703. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16704. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16705. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16706. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16707. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16708. \end{array}
  16709. }
  16710. \newcommand{\LdynASTRacket}{
  16711. \begin{array}{lcl}
  16712. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16713. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16714. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16715. \end{array}
  16716. }
  16717. \begin{figure}[tp]
  16718. \centering
  16719. \begin{tcolorbox}[colback=white]
  16720. \small
  16721. {\if\edition\racketEd
  16722. \[
  16723. \begin{array}{l}
  16724. \gray{\LintGrammarRacket{}} \\ \hline
  16725. \gray{\LvarGrammarRacket{}} \\ \hline
  16726. \gray{\LifGrammarRacket{}} \\ \hline
  16727. \gray{\LwhileGrammarRacket} \\ \hline
  16728. \gray{\LtupGrammarRacket} \\ \hline
  16729. \LdynGrammarRacket \\
  16730. \begin{array}{rcl}
  16731. \LangDynM{} &::=& \Def\ldots\; \Exp
  16732. \end{array}
  16733. \end{array}
  16734. \]
  16735. \fi}
  16736. {\if\edition\pythonEd\pythonColor
  16737. \[
  16738. \begin{array}{rcl}
  16739. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16740. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16741. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16742. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16743. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16744. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16745. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16746. \MID \CLEN{\Exp} \\
  16747. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16748. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16749. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16750. \MID \Var\mathop{\key{=}}\Exp \\
  16751. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16752. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16753. &\MID& \CRETURN{\Exp} \\
  16754. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16755. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16756. \end{array}
  16757. \]
  16758. \fi}
  16759. \end{tcolorbox}
  16760. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16761. \label{fig:r7-concrete-syntax}
  16762. \end{figure}
  16763. \begin{figure}[tp]
  16764. \centering
  16765. \begin{tcolorbox}[colback=white]
  16766. \small
  16767. {\if\edition\racketEd
  16768. \[
  16769. \begin{array}{l}
  16770. \gray{\LintASTRacket{}} \\ \hline
  16771. \gray{\LvarASTRacket{}} \\ \hline
  16772. \gray{\LifASTRacket{}} \\ \hline
  16773. \gray{\LwhileASTRacket} \\ \hline
  16774. \gray{\LtupASTRacket} \\ \hline
  16775. \LdynASTRacket \\
  16776. \begin{array}{lcl}
  16777. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16778. \end{array}
  16779. \end{array}
  16780. \]
  16781. \fi}
  16782. {\if\edition\pythonEd\pythonColor
  16783. \[
  16784. \begin{array}{rcl}
  16785. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16786. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16787. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16788. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16789. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16790. &\MID & \code{Is()} \\
  16791. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16792. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16793. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  16794. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  16795. \MID \VAR{\Var{}} \\
  16796. &\MID& \BOOL{\itm{bool}}
  16797. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  16798. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  16799. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  16800. &\MID& \LEN{\Exp} \\
  16801. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  16802. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  16803. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  16804. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  16805. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  16806. &\MID& \RETURN{\Exp} \\
  16807. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  16808. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  16809. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16810. \end{array}
  16811. \]
  16812. \fi}
  16813. \end{tcolorbox}
  16814. \caption{The abstract syntax of \LangDyn{}.}
  16815. \label{fig:r7-syntax}
  16816. \end{figure}
  16817. The definitions of the concrete and abstract syntax of \LangDyn{} are
  16818. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  16819. %
  16820. There is no type checker for \LangDyn{} because it checks types only
  16821. at runtime.
  16822. The definitional interpreter for \LangDyn{} is presented in
  16823. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  16824. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  16825. \INT{n}. Instead of simply returning the integer \code{n} (as
  16826. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  16827. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  16828. value} that combines an underlying value with a tag that identifies
  16829. what kind of value it is. We define the following \racket{struct}\python{class}
  16830. to represent tagged values:
  16831. %
  16832. {\if\edition\racketEd
  16833. \begin{lstlisting}
  16834. (struct Tagged (value tag) #:transparent)
  16835. \end{lstlisting}
  16836. \fi}
  16837. {\if\edition\pythonEd\pythonColor
  16838. \begin{minipage}{\textwidth}
  16839. \begin{lstlisting}
  16840. @dataclass(eq=True)
  16841. class Tagged(Value):
  16842. value : Value
  16843. tag : str
  16844. def __str__(self):
  16845. return str(self.value)
  16846. \end{lstlisting}
  16847. \end{minipage}
  16848. \fi}
  16849. %
  16850. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  16851. \code{Vector}, and \code{Procedure}.}
  16852. %
  16853. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  16854. \code{'tuple'}, and \code{'function'}.}
  16855. %
  16856. Tags are closely related to types but do not always capture all the
  16857. information that a type does.
  16858. %
  16859. \racket{For example, a vector of type \code{(Vector Any Any)} is
  16860. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  16861. Any)} is tagged with \code{Procedure}.}
  16862. %
  16863. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  16864. is tagged with \code{'tuple'} and a function of type
  16865. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  16866. is tagged with \code{'function'}.}
  16867. Next consider the match case for accessing the element of a tuple.
  16868. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  16869. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  16870. argument is a tuple and the second is an integer.
  16871. \racket{
  16872. If they are not, a \code{trapped-error} is raised. Recall from
  16873. section~\ref{sec:interp_Lint} that when a definition interpreter
  16874. raises a \code{trapped-error} error, the compiled code must also
  16875. signal an error by exiting with return code \code{255}. A
  16876. \code{trapped-error} is also raised if the index is not less than the
  16877. length of the vector.
  16878. }
  16879. %
  16880. \python{If they are not, an exception is raised. The compiled code
  16881. must also signal an error by exiting with return code \code{255}. A
  16882. exception is also raised if the index is not less than the length of the
  16883. tuple or if it is negative.}
  16884. \begin{figure}[tbp]
  16885. \begin{tcolorbox}[colback=white]
  16886. {\if\edition\racketEd
  16887. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16888. (define ((interp-Ldyn-exp env) ast)
  16889. (define recur (interp-Ldyn-exp env))
  16890. (match ast
  16891. [(Var x) (dict-ref env x)]
  16892. [(Int n) (Tagged n 'Integer)]
  16893. [(Bool b) (Tagged b 'Boolean)]
  16894. [(Lambda xs rt body)
  16895. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  16896. [(Prim 'vector es)
  16897. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  16898. [(Prim 'vector-ref (list e1 e2))
  16899. (define vec (recur e1)) (define i (recur e2))
  16900. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16901. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16902. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16903. (vector-ref (Tagged-value vec) (Tagged-value i))]
  16904. [(Prim 'vector-set! (list e1 e2 e3))
  16905. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  16906. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16907. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16908. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16909. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  16910. (Tagged (void) 'Void)]
  16911. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  16912. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  16913. [(Prim 'or (list e1 e2))
  16914. (define v1 (recur e1))
  16915. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  16916. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  16917. [(Prim op (list e1))
  16918. #:when (set-member? type-predicates op)
  16919. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  16920. [(Prim op es)
  16921. (define args (map recur es))
  16922. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  16923. (unless (for/or ([expected-tags (op-tags op)])
  16924. (equal? expected-tags tags))
  16925. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  16926. (tag-value
  16927. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  16928. [(If q t f)
  16929. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  16930. [(Apply f es)
  16931. (define new-f (recur f)) (define args (map recur es))
  16932. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  16933. (match f-val
  16934. [`(function ,xs ,body ,lam-env)
  16935. (unless (eq? (length xs) (length args))
  16936. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  16937. (define new-env (append (map cons xs args) lam-env))
  16938. ((interp-Ldyn-exp new-env) body)]
  16939. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  16940. \end{lstlisting}
  16941. \fi}
  16942. {\if\edition\pythonEd\pythonColor
  16943. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16944. class InterpLdyn(InterpLlambda):
  16945. def interp_exp(self, e, env):
  16946. match e:
  16947. case Constant(n):
  16948. return self.tag(super().interp_exp(e, env))
  16949. case Tuple(es, Load()):
  16950. return self.tag(super().interp_exp(e, env))
  16951. case Lambda(params, body):
  16952. return self.tag(super().interp_exp(e, env))
  16953. case Call(Name('input_int'), []):
  16954. return self.tag(super().interp_exp(e, env))
  16955. case BinOp(left, Add(), right):
  16956. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16957. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16958. case BinOp(left, Sub(), right):
  16959. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16960. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16961. case UnaryOp(USub(), e1):
  16962. v = self.interp_exp(e1, env)
  16963. return self.tag(- self.untag(v, 'int', e))
  16964. case IfExp(test, body, orelse):
  16965. v = self.interp_exp(test, env)
  16966. if self.untag(v, 'bool', e):
  16967. return self.interp_exp(body, env)
  16968. else:
  16969. return self.interp_exp(orelse, env)
  16970. case UnaryOp(Not(), e1):
  16971. v = self.interp_exp(e1, env)
  16972. return self.tag(not self.untag(v, 'bool', e))
  16973. case BoolOp(And(), values):
  16974. left = values[0]; right = values[1]
  16975. l = self.interp_exp(left, env)
  16976. if self.untag(l, 'bool', e):
  16977. return self.interp_exp(right, env)
  16978. else:
  16979. return self.tag(False)
  16980. case BoolOp(Or(), values):
  16981. left = values[0]; right = values[1]
  16982. l = self.interp_exp(left, env)
  16983. if self.untag(l, 'bool', e):
  16984. return self.tag(True)
  16985. else:
  16986. return self.interp_exp(right, env)
  16987. case Compare(left, [cmp], [right]):
  16988. l = self.interp_exp(left, env)
  16989. r = self.interp_exp(right, env)
  16990. if l.tag == r.tag:
  16991. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16992. else:
  16993. raise Exception('interp Compare unexpected '
  16994. + repr(l) + ' ' + repr(r))
  16995. case Subscript(tup, index, Load()):
  16996. t = self.interp_exp(tup, env)
  16997. n = self.interp_exp(index, env)
  16998. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16999. case Call(Name('len'), [tup]):
  17000. t = self.interp_exp(tup, env)
  17001. return self.tag(len(self.untag(t, 'tuple', e)))
  17002. case _:
  17003. return self.tag(super().interp_exp(e, env))
  17004. \end{lstlisting}
  17005. \fi}
  17006. \end{tcolorbox}
  17007. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17008. \label{fig:interp-Ldyn}
  17009. \end{figure}
  17010. {\if\edition\pythonEd\pythonColor
  17011. \begin{figure}[tbp]
  17012. \begin{tcolorbox}[colback=white]
  17013. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17014. class InterpLdyn(InterpLlambda):
  17015. def interp_stmt(self, s, env, cont):
  17016. match s:
  17017. case If(test, body, orelse):
  17018. v = self.interp_exp(test, env)
  17019. match self.untag(v, 'bool', s):
  17020. case True:
  17021. return self.interp_stmts(body + cont, env)
  17022. case False:
  17023. return self.interp_stmts(orelse + cont, env)
  17024. case While(test, body, []):
  17025. v = self.interp_exp(test, env)
  17026. if self.untag(v, 'bool', test):
  17027. self.interp_stmts(body + [s] + cont, env)
  17028. else:
  17029. return self.interp_stmts(cont, env)
  17030. case Assign([Subscript(tup, index)], value):
  17031. tup = self.interp_exp(tup, env)
  17032. index = self.interp_exp(index, env)
  17033. tup_v = self.untag(tup, 'tuple', s)
  17034. index_v = self.untag(index, 'int', s)
  17035. tup_v[index_v] = self.interp_exp(value, env)
  17036. return self.interp_stmts(cont, env)
  17037. case FunctionDef(name, params, bod, dl, returns, comment):
  17038. if isinstance(params, ast.arguments):
  17039. ps = [p.arg for p in params.args]
  17040. else:
  17041. ps = [x for (x,t) in params]
  17042. env[name] = self.tag(Function(name, ps, bod, env))
  17043. return self.interp_stmts(cont, env)
  17044. case _:
  17045. return super().interp_stmt(s, env, cont)
  17046. \end{lstlisting}
  17047. \end{tcolorbox}
  17048. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17049. \label{fig:interp-Ldyn-2}
  17050. \end{figure}
  17051. \fi}
  17052. \begin{figure}[tbp]
  17053. \begin{tcolorbox}[colback=white]
  17054. {\if\edition\racketEd
  17055. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17056. (define (interp-op op)
  17057. (match op
  17058. ['+ fx+]
  17059. ['- fx-]
  17060. ['read read-fixnum]
  17061. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17062. ['< (lambda (v1 v2)
  17063. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17064. ['<= (lambda (v1 v2)
  17065. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17066. ['> (lambda (v1 v2)
  17067. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17068. ['>= (lambda (v1 v2)
  17069. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17070. ['boolean? boolean?]
  17071. ['integer? fixnum?]
  17072. ['void? void?]
  17073. ['vector? vector?]
  17074. ['vector-length vector-length]
  17075. ['procedure? (match-lambda
  17076. [`(functions ,xs ,body ,env) #t] [else #f])]
  17077. [else (error 'interp-op "unknown operator" op)]))
  17078. (define (op-tags op)
  17079. (match op
  17080. ['+ '((Integer Integer))]
  17081. ['- '((Integer Integer) (Integer))]
  17082. ['read '(())]
  17083. ['not '((Boolean))]
  17084. ['< '((Integer Integer))]
  17085. ['<= '((Integer Integer))]
  17086. ['> '((Integer Integer))]
  17087. ['>= '((Integer Integer))]
  17088. ['vector-length '((Vector))]))
  17089. (define type-predicates
  17090. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17091. (define (tag-value v)
  17092. (cond [(boolean? v) (Tagged v 'Boolean)]
  17093. [(fixnum? v) (Tagged v 'Integer)]
  17094. [(procedure? v) (Tagged v 'Procedure)]
  17095. [(vector? v) (Tagged v 'Vector)]
  17096. [(void? v) (Tagged v 'Void)]
  17097. [else (error 'tag-value "unidentified value ~a" v)]))
  17098. (define (check-tag val expected ast)
  17099. (define tag (Tagged-tag val))
  17100. (unless (eq? tag expected)
  17101. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17102. \end{lstlisting}
  17103. \fi}
  17104. {\if\edition\pythonEd\pythonColor
  17105. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17106. class InterpLdyn(InterpLlambda):
  17107. def tag(self, v):
  17108. if v is True or v is False:
  17109. return Tagged(v, 'bool')
  17110. elif isinstance(v, int):
  17111. return Tagged(v, 'int')
  17112. elif isinstance(v, Function):
  17113. return Tagged(v, 'function')
  17114. elif isinstance(v, tuple):
  17115. return Tagged(v, 'tuple')
  17116. elif isinstance(v, type(None)):
  17117. return Tagged(v, 'none')
  17118. else:
  17119. raise Exception('tag: unexpected ' + repr(v))
  17120. def untag(self, v, expected_tag, ast):
  17121. match v:
  17122. case Tagged(val, tag) if tag == expected_tag:
  17123. return val
  17124. case _:
  17125. raise TrappedError('expected Tagged value with '
  17126. + expected_tag + ', not ' + ' ' + repr(v))
  17127. def apply_fun(self, fun, args, e):
  17128. f = self.untag(fun, 'function', e)
  17129. return super().apply_fun(f, args, e)
  17130. \end{lstlisting}
  17131. \fi}
  17132. \end{tcolorbox}
  17133. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17134. \label{fig:interp-Ldyn-aux}
  17135. \end{figure}
  17136. \clearpage
  17137. \section{Representation of Tagged Values}
  17138. The interpreter for \LangDyn{} introduced a new kind of value: the
  17139. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17140. represent tagged values at the bit level. Because almost every
  17141. operation in \LangDyn{} involves manipulating tagged values, the
  17142. representation must be efficient. Recall that all our values are 64
  17143. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17144. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17145. $011$ for procedures, and $101$ for the void value\python{,
  17146. \key{None}}. We define the following auxiliary function for mapping
  17147. types to tag codes:
  17148. %
  17149. {\if\edition\racketEd
  17150. \begin{align*}
  17151. \itm{tagof}(\key{Integer}) &= 001 \\
  17152. \itm{tagof}(\key{Boolean}) &= 100 \\
  17153. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17154. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17155. \itm{tagof}(\key{Void}) &= 101
  17156. \end{align*}
  17157. \fi}
  17158. {\if\edition\pythonEd\pythonColor
  17159. \begin{align*}
  17160. \itm{tagof}(\key{IntType()}) &= 001 \\
  17161. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17162. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17163. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17164. \itm{tagof}(\key{type(None)}) &= 101
  17165. \end{align*}
  17166. \fi}
  17167. %
  17168. This stealing of 3 bits comes at some price: integers are now restricted
  17169. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17170. affect tuples and procedures because those values are addresses, and
  17171. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17172. they are always $000$. Thus, we do not lose information by overwriting
  17173. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17174. to recover the original address.
  17175. To make tagged values into first-class entities, we can give them a
  17176. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  17177. operations such as \code{Inject} and \code{Project} for creating and
  17178. using them, yielding the statically typed \LangAny{} intermediate
  17179. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17180. section~\ref{sec:compile-r7}; in the next section we describe the
  17181. \LangAny{} language in greater detail.
  17182. \section{The \LangAny{} Language}
  17183. \label{sec:Rany-lang}
  17184. \newcommand{\LanyASTRacket}{
  17185. \begin{array}{lcl}
  17186. \Type &::= & \ANYTY \\
  17187. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17188. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17189. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17190. \itm{op} &::= & \code{any-vector-length}
  17191. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17192. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17193. \MID \code{procedure?} \MID \code{void?} \\
  17194. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17195. \end{array}
  17196. }
  17197. \newcommand{\LanyASTPython}{
  17198. \begin{array}{lcl}
  17199. \Type &::= & \key{AnyType()} \\
  17200. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17201. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17202. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17203. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17204. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  17205. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  17206. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  17207. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17208. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  17209. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  17210. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  17211. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  17212. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  17213. \end{array}
  17214. }
  17215. \begin{figure}[tp]
  17216. \centering
  17217. \begin{tcolorbox}[colback=white]
  17218. \small
  17219. {\if\edition\racketEd
  17220. \[
  17221. \begin{array}{l}
  17222. \gray{\LintOpAST} \\ \hline
  17223. \gray{\LvarASTRacket{}} \\ \hline
  17224. \gray{\LifASTRacket{}} \\ \hline
  17225. \gray{\LwhileASTRacket{}} \\ \hline
  17226. \gray{\LtupASTRacket{}} \\ \hline
  17227. \gray{\LfunASTRacket} \\ \hline
  17228. \gray{\LlambdaASTRacket} \\ \hline
  17229. \LanyASTRacket \\
  17230. \begin{array}{lcl}
  17231. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17232. \end{array}
  17233. \end{array}
  17234. \]
  17235. \fi}
  17236. {\if\edition\pythonEd\pythonColor
  17237. \[
  17238. \begin{array}{l}
  17239. \gray{\LintASTPython} \\ \hline
  17240. \gray{\LvarASTPython{}} \\ \hline
  17241. \gray{\LifASTPython{}} \\ \hline
  17242. \gray{\LwhileASTPython{}} \\ \hline
  17243. \gray{\LtupASTPython{}} \\ \hline
  17244. \gray{\LfunASTPython} \\ \hline
  17245. \gray{\LlambdaASTPython} \\ \hline
  17246. \LanyASTPython \\
  17247. \begin{array}{lcl}
  17248. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17249. \end{array}
  17250. \end{array}
  17251. \]
  17252. \fi}
  17253. \end{tcolorbox}
  17254. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17255. \label{fig:Lany-syntax}
  17256. \end{figure}
  17257. The definition of the abstract syntax of \LangAny{} is given in
  17258. figure~\ref{fig:Lany-syntax}.
  17259. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17260. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17261. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17262. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17263. converts the tagged value produced by expression $e$ into a value of
  17264. type $T$ or halts the program if the type tag does not match $T$.
  17265. %
  17266. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17267. restricted to be a flat type (the nonterminal $\FType$) which
  17268. simplifies the implementation and complies with the needs for
  17269. compiling \LangDyn{}.
  17270. The \racket{\code{any-vector}} operators
  17271. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17272. operations so that they can be applied to a value of type
  17273. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17274. tuple operations in that the index is not restricted to a literal
  17275. integer in the grammar but is allowed to be any expression.
  17276. \racket{The type predicates such as
  17277. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17278. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17279. the predicate and return {\FALSE} otherwise.}
  17280. The type checker for \LangAny{} is shown in
  17281. figure~\ref{fig:type-check-Lany}
  17282. %
  17283. \racket{ and uses the auxiliary functions presented in
  17284. figure~\ref{fig:type-check-Lany-aux}}.
  17285. %
  17286. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17287. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17288. \begin{figure}[btp]
  17289. \begin{tcolorbox}[colback=white]
  17290. {\if\edition\racketEd
  17291. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17292. (define type-check-Lany-class
  17293. (class type-check-Llambda-class
  17294. (super-new)
  17295. (inherit check-type-equal?)
  17296. (define/override (type-check-exp env)
  17297. (lambda (e)
  17298. (define recur (type-check-exp env))
  17299. (match e
  17300. [(Inject e1 ty)
  17301. (unless (flat-ty? ty)
  17302. (error 'type-check "may only inject from flat type, not ~a" ty))
  17303. (define-values (new-e1 e-ty) (recur e1))
  17304. (check-type-equal? e-ty ty e)
  17305. (values (Inject new-e1 ty) 'Any)]
  17306. [(Project e1 ty)
  17307. (unless (flat-ty? ty)
  17308. (error 'type-check "may only project to flat type, not ~a" ty))
  17309. (define-values (new-e1 e-ty) (recur e1))
  17310. (check-type-equal? e-ty 'Any e)
  17311. (values (Project new-e1 ty) ty)]
  17312. [(Prim 'any-vector-length (list e1))
  17313. (define-values (e1^ t1) (recur e1))
  17314. (check-type-equal? t1 'Any e)
  17315. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17316. [(Prim 'any-vector-ref (list e1 e2))
  17317. (define-values (e1^ t1) (recur e1))
  17318. (define-values (e2^ t2) (recur e2))
  17319. (check-type-equal? t1 'Any e)
  17320. (check-type-equal? t2 'Integer e)
  17321. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17322. [(Prim 'any-vector-set! (list e1 e2 e3))
  17323. (define-values (e1^ t1) (recur e1))
  17324. (define-values (e2^ t2) (recur e2))
  17325. (define-values (e3^ t3) (recur e3))
  17326. (check-type-equal? t1 'Any e)
  17327. (check-type-equal? t2 'Integer e)
  17328. (check-type-equal? t3 'Any e)
  17329. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17330. [(Prim pred (list e1))
  17331. #:when (set-member? (type-predicates) pred)
  17332. (define-values (new-e1 e-ty) (recur e1))
  17333. (check-type-equal? e-ty 'Any e)
  17334. (values (Prim pred (list new-e1)) 'Boolean)]
  17335. [(Prim 'eq? (list arg1 arg2))
  17336. (define-values (e1 t1) (recur arg1))
  17337. (define-values (e2 t2) (recur arg2))
  17338. (match* (t1 t2)
  17339. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17340. [(other wise) (check-type-equal? t1 t2 e)])
  17341. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17342. [else ((super type-check-exp env) e)])))
  17343. ))
  17344. \end{lstlisting}
  17345. \fi}
  17346. {\if\edition\pythonEd\pythonColor
  17347. \begin{lstlisting}
  17348. class TypeCheckLany(TypeCheckLlambda):
  17349. def type_check_exp(self, e, env):
  17350. match e:
  17351. case Inject(value, typ):
  17352. self.check_exp(value, typ, env)
  17353. return AnyType()
  17354. case Project(value, typ):
  17355. self.check_exp(value, AnyType(), env)
  17356. return typ
  17357. case Call(Name('any_tuple_load'), [tup, index]):
  17358. self.check_exp(tup, AnyType(), env)
  17359. self.check_exp(index, IntType(), env)
  17360. return AnyType()
  17361. case Call(Name('any_len'), [tup]):
  17362. self.check_exp(tup, AnyType(), env)
  17363. return IntType()
  17364. case Call(Name('arity'), [fun]):
  17365. ty = self.type_check_exp(fun, env)
  17366. match ty:
  17367. case FunctionType(ps, rt):
  17368. return IntType()
  17369. case TupleType([FunctionType(ps,rs)]):
  17370. return IntType()
  17371. case _:
  17372. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  17373. case Call(Name('make_any'), [value, tag]):
  17374. self.type_check_exp(value, env)
  17375. self.check_exp(tag, IntType(), env)
  17376. return AnyType()
  17377. case AnnLambda(params, returns, body):
  17378. new_env = {x:t for (x,t) in env.items()}
  17379. for (x,t) in params:
  17380. new_env[x] = t
  17381. return_t = self.type_check_exp(body, new_env)
  17382. self.check_type_equal(returns, return_t, e)
  17383. return FunctionType([t for (x,t) in params], return_t)
  17384. case _:
  17385. return super().type_check_exp(e, env)
  17386. \end{lstlisting}
  17387. \fi}
  17388. \end{tcolorbox}
  17389. \caption{Type checker for the \LangAny{} language.}
  17390. \label{fig:type-check-Lany}
  17391. \end{figure}
  17392. {\if\edition\racketEd
  17393. \begin{figure}[tbp]
  17394. \begin{tcolorbox}[colback=white]
  17395. \begin{lstlisting}
  17396. (define/override (operator-types)
  17397. (append
  17398. '((integer? . ((Any) . Boolean))
  17399. (vector? . ((Any) . Boolean))
  17400. (procedure? . ((Any) . Boolean))
  17401. (void? . ((Any) . Boolean)))
  17402. (super operator-types)))
  17403. (define/public (type-predicates)
  17404. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17405. (define/public (flat-ty? ty)
  17406. (match ty
  17407. [(or `Integer `Boolean `Void) #t]
  17408. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17409. [`(,ts ... -> ,rt)
  17410. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17411. [else #f]))
  17412. \end{lstlisting}
  17413. \end{tcolorbox}
  17414. \caption{Auxiliary methods for type checking \LangAny{}.}
  17415. \label{fig:type-check-Lany-aux}
  17416. \end{figure}
  17417. \fi}
  17418. \begin{figure}[btp]
  17419. \begin{tcolorbox}[colback=white]
  17420. {\if\edition\racketEd
  17421. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17422. (define interp-Lany-class
  17423. (class interp-Llambda-class
  17424. (super-new)
  17425. (define/override (interp-op op)
  17426. (match op
  17427. ['boolean? (match-lambda
  17428. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17429. [else #f])]
  17430. ['integer? (match-lambda
  17431. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17432. [else #f])]
  17433. ['vector? (match-lambda
  17434. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17435. [else #f])]
  17436. ['procedure? (match-lambda
  17437. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17438. [else #f])]
  17439. ['eq? (match-lambda*
  17440. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17441. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17442. [ls (apply (super interp-op op) ls)])]
  17443. ['any-vector-ref (lambda (v i)
  17444. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17445. ['any-vector-set! (lambda (v i a)
  17446. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17447. ['any-vector-length (lambda (v)
  17448. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17449. [else (super interp-op op)]))
  17450. (define/override ((interp-exp env) e)
  17451. (define recur (interp-exp env))
  17452. (match e
  17453. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17454. [(Project e ty2) (apply-project (recur e) ty2)]
  17455. [else ((super interp-exp env) e)]))
  17456. ))
  17457. (define (interp-Lany p)
  17458. (send (new interp-Lany-class) interp-program p))
  17459. \end{lstlisting}
  17460. \fi}
  17461. {\if\edition\pythonEd\pythonColor
  17462. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17463. class InterpLany(InterpLlambda):
  17464. def interp_exp(self, e, env):
  17465. match e:
  17466. case Inject(value, typ):
  17467. v = self.interp_exp(value, env)
  17468. return Tagged(v, self.type_to_tag(typ))
  17469. case Project(value, typ):
  17470. v = self.interp_exp(value, env)
  17471. match v:
  17472. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17473. return val
  17474. case _:
  17475. raise Exception('interp project to ' + repr(typ)
  17476. + ' unexpected ' + repr(v))
  17477. case Call(Name('any_tuple_load'), [tup, index]):
  17478. tv = self.interp_exp(tup, env)
  17479. n = self.interp_exp(index, env)
  17480. match tv:
  17481. case Tagged(v, tag):
  17482. return v[n]
  17483. case _:
  17484. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  17485. case Call(Name('any_len'), [value]):
  17486. v = self.interp_exp(value, env)
  17487. match v:
  17488. case Tagged(value, tag):
  17489. return len(value)
  17490. case _:
  17491. raise Exception('interp any_len unexpected ' + repr(v))
  17492. case Call(Name('arity'), [fun]):
  17493. f = self.interp_exp(fun, env)
  17494. return self.arity(f)
  17495. case _:
  17496. return super().interp_exp(e, env)
  17497. \end{lstlisting}
  17498. \fi}
  17499. \end{tcolorbox}
  17500. \caption{Interpreter for \LangAny{}.}
  17501. \label{fig:interp-Lany}
  17502. \end{figure}
  17503. \begin{figure}[tbp]
  17504. \begin{tcolorbox}[colback=white]
  17505. {\if\edition\racketEd
  17506. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17507. (define/public (apply-inject v tg) (Tagged v tg))
  17508. (define/public (apply-project v ty2)
  17509. (define tag2 (any-tag ty2))
  17510. (match v
  17511. [(Tagged v1 tag1)
  17512. (cond
  17513. [(eq? tag1 tag2)
  17514. (match ty2
  17515. [`(Vector ,ts ...)
  17516. (define l1 ((interp-op 'vector-length) v1))
  17517. (cond
  17518. [(eq? l1 (length ts)) v1]
  17519. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17520. l1 (length ts))])]
  17521. [`(,ts ... -> ,rt)
  17522. (match v1
  17523. [`(function ,xs ,body ,env)
  17524. (cond [(eq? (length xs) (length ts)) v1]
  17525. [else
  17526. (error 'apply-project "arity mismatch ~a != ~a"
  17527. (length xs) (length ts))])]
  17528. [else (error 'apply-project "expected function not ~a" v1)])]
  17529. [else v1])]
  17530. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17531. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17532. \end{lstlisting}
  17533. \fi}
  17534. {\if\edition\pythonEd\pythonColor
  17535. \begin{lstlisting}
  17536. class InterpLany(InterpLlambda):
  17537. def type_to_tag(self, typ):
  17538. match typ:
  17539. case FunctionType(params, rt):
  17540. return 'function'
  17541. case TupleType(fields):
  17542. return 'tuple'
  17543. case t if t == int:
  17544. return 'int'
  17545. case t if t == bool:
  17546. return 'bool'
  17547. case IntType():
  17548. return 'int'
  17549. case BoolType():
  17550. return 'int'
  17551. case _:
  17552. raise Exception('type_to_tag unexpected ' + repr(typ))
  17553. def arity(self, v):
  17554. match v:
  17555. case Function(name, params, body, env):
  17556. return len(params)
  17557. case ClosureTuple(args, arity):
  17558. return arity
  17559. case _:
  17560. raise Exception('Lany arity unexpected ' + repr(v))
  17561. \end{lstlisting}
  17562. \fi}
  17563. \end{tcolorbox}
  17564. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17565. \label{fig:interp-Lany-aux}
  17566. \end{figure}
  17567. \clearpage
  17568. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17569. \label{sec:compile-r7}
  17570. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17571. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17572. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17573. is that given any subexpression $e$ in the \LangDyn{} program, the
  17574. pass will produce an expression $e'$ in \LangAny{} that has type
  17575. \ANYTY{}. For example, the first row in
  17576. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17577. \TRUE{}, which must be injected to produce an expression of type
  17578. \ANYTY{}.
  17579. %
  17580. The compilation of addition is shown in the second row of
  17581. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17582. representative of many primitive operations: the arguments have type
  17583. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17584. be performed.
  17585. The compilation of \key{lambda} (third row of
  17586. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17587. produce type annotations: we simply use \ANYTY{}.
  17588. %
  17589. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17590. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17591. this pass has to account for some differences in behavior between
  17592. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17593. permissive than \LangAny{} regarding what kind of values can be used
  17594. in various places. For example, the condition of an \key{if} does
  17595. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17596. of the same type (in that case the result is \code{\#f}).}
  17597. \begin{figure}[btp]
  17598. \centering
  17599. \begin{tcolorbox}[colback=white]
  17600. {\if\edition\racketEd
  17601. \begin{tabular}{lll}
  17602. \begin{minipage}{0.27\textwidth}
  17603. \begin{lstlisting}
  17604. #t
  17605. \end{lstlisting}
  17606. \end{minipage}
  17607. &
  17608. $\Rightarrow$
  17609. &
  17610. \begin{minipage}{0.65\textwidth}
  17611. \begin{lstlisting}
  17612. (inject #t Boolean)
  17613. \end{lstlisting}
  17614. \end{minipage}
  17615. \\[2ex]\hline
  17616. \begin{minipage}{0.27\textwidth}
  17617. \begin{lstlisting}
  17618. (+ |$e_1$| |$e_2$|)
  17619. \end{lstlisting}
  17620. \end{minipage}
  17621. &
  17622. $\Rightarrow$
  17623. &
  17624. \begin{minipage}{0.65\textwidth}
  17625. \begin{lstlisting}
  17626. (inject
  17627. (+ (project |$e'_1$| Integer)
  17628. (project |$e'_2$| Integer))
  17629. Integer)
  17630. \end{lstlisting}
  17631. \end{minipage}
  17632. \\[2ex]\hline
  17633. \begin{minipage}{0.27\textwidth}
  17634. \begin{lstlisting}
  17635. (lambda (|$x_1 \ldots$|) |$e$|)
  17636. \end{lstlisting}
  17637. \end{minipage}
  17638. &
  17639. $\Rightarrow$
  17640. &
  17641. \begin{minipage}{0.65\textwidth}
  17642. \begin{lstlisting}
  17643. (inject
  17644. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17645. (Any|$\ldots$|Any -> Any))
  17646. \end{lstlisting}
  17647. \end{minipage}
  17648. \\[2ex]\hline
  17649. \begin{minipage}{0.27\textwidth}
  17650. \begin{lstlisting}
  17651. (|$e_0$| |$e_1 \ldots e_n$|)
  17652. \end{lstlisting}
  17653. \end{minipage}
  17654. &
  17655. $\Rightarrow$
  17656. &
  17657. \begin{minipage}{0.65\textwidth}
  17658. \begin{lstlisting}
  17659. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17660. \end{lstlisting}
  17661. \end{minipage}
  17662. \\[2ex]\hline
  17663. \begin{minipage}{0.27\textwidth}
  17664. \begin{lstlisting}
  17665. (vector-ref |$e_1$| |$e_2$|)
  17666. \end{lstlisting}
  17667. \end{minipage}
  17668. &
  17669. $\Rightarrow$
  17670. &
  17671. \begin{minipage}{0.65\textwidth}
  17672. \begin{lstlisting}
  17673. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17674. \end{lstlisting}
  17675. \end{minipage}
  17676. \\[2ex]\hline
  17677. \begin{minipage}{0.27\textwidth}
  17678. \begin{lstlisting}
  17679. (if |$e_1$| |$e_2$| |$e_3$|)
  17680. \end{lstlisting}
  17681. \end{minipage}
  17682. &
  17683. $\Rightarrow$
  17684. &
  17685. \begin{minipage}{0.65\textwidth}
  17686. \begin{lstlisting}
  17687. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17688. \end{lstlisting}
  17689. \end{minipage}
  17690. \\[2ex]\hline
  17691. \begin{minipage}{0.27\textwidth}
  17692. \begin{lstlisting}
  17693. (eq? |$e_1$| |$e_2$|)
  17694. \end{lstlisting}
  17695. \end{minipage}
  17696. &
  17697. $\Rightarrow$
  17698. &
  17699. \begin{minipage}{0.65\textwidth}
  17700. \begin{lstlisting}
  17701. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17702. \end{lstlisting}
  17703. \end{minipage}
  17704. \\[2ex]\hline
  17705. \begin{minipage}{0.27\textwidth}
  17706. \begin{lstlisting}
  17707. (not |$e_1$|)
  17708. \end{lstlisting}
  17709. \end{minipage}
  17710. &
  17711. $\Rightarrow$
  17712. &
  17713. \begin{minipage}{0.65\textwidth}
  17714. \begin{lstlisting}
  17715. (if (eq? |$e'_1$| (inject #f Boolean))
  17716. (inject #t Boolean) (inject #f Boolean))
  17717. \end{lstlisting}
  17718. \end{minipage}
  17719. \end{tabular}
  17720. \fi}
  17721. {\if\edition\pythonEd\pythonColor
  17722. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17723. \begin{minipage}{0.23\textwidth}
  17724. \begin{lstlisting}
  17725. True
  17726. \end{lstlisting}
  17727. \end{minipage}
  17728. &
  17729. $\Rightarrow$
  17730. &
  17731. \begin{minipage}{0.7\textwidth}
  17732. \begin{lstlisting}
  17733. Inject(True, BoolType())
  17734. \end{lstlisting}
  17735. \end{minipage}
  17736. \\[2ex]\hline
  17737. \begin{minipage}{0.23\textwidth}
  17738. \begin{lstlisting}
  17739. |$e_1$| + |$e_2$|
  17740. \end{lstlisting}
  17741. \end{minipage}
  17742. &
  17743. $\Rightarrow$
  17744. &
  17745. \begin{minipage}{0.7\textwidth}
  17746. \begin{lstlisting}
  17747. Inject(Project(|$e'_1$|, IntType())
  17748. + Project(|$e'_2$|, IntType()),
  17749. IntType())
  17750. \end{lstlisting}
  17751. \end{minipage}
  17752. \\[2ex]\hline
  17753. \begin{minipage}{0.23\textwidth}
  17754. \begin{lstlisting}
  17755. lambda |$x_1 \ldots$|: |$e$|
  17756. \end{lstlisting}
  17757. \end{minipage}
  17758. &
  17759. $\Rightarrow$
  17760. &
  17761. \begin{minipage}{0.7\textwidth}
  17762. \begin{lstlisting}
  17763. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17764. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17765. \end{lstlisting}
  17766. \end{minipage}
  17767. \\[2ex]\hline
  17768. \begin{minipage}{0.23\textwidth}
  17769. \begin{lstlisting}
  17770. |$e_0$|(|$e_1 \ldots e_n$|)
  17771. \end{lstlisting}
  17772. \end{minipage}
  17773. &
  17774. $\Rightarrow$
  17775. &
  17776. \begin{minipage}{0.7\textwidth}
  17777. \begin{lstlisting}
  17778. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17779. AnyType())), |$e'_1, \ldots, e'_n$|)
  17780. \end{lstlisting}
  17781. \end{minipage}
  17782. \\[2ex]\hline
  17783. \begin{minipage}{0.23\textwidth}
  17784. \begin{lstlisting}
  17785. |$e_1$|[|$e_2$|]
  17786. \end{lstlisting}
  17787. \end{minipage}
  17788. &
  17789. $\Rightarrow$
  17790. &
  17791. \begin{minipage}{0.7\textwidth}
  17792. \begin{lstlisting}
  17793. Call(Name('any_tuple_load'),
  17794. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  17795. \end{lstlisting}
  17796. \end{minipage}
  17797. %% \begin{minipage}{0.23\textwidth}
  17798. %% \begin{lstlisting}
  17799. %% |$e_2$| if |$e_1$| else |$e_3$|
  17800. %% \end{lstlisting}
  17801. %% \end{minipage}
  17802. %% &
  17803. %% $\Rightarrow$
  17804. %% &
  17805. %% \begin{minipage}{0.7\textwidth}
  17806. %% \begin{lstlisting}
  17807. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17808. %% \end{lstlisting}
  17809. %% \end{minipage}
  17810. %% \\[2ex]\hline
  17811. %% \begin{minipage}{0.23\textwidth}
  17812. %% \begin{lstlisting}
  17813. %% (eq? |$e_1$| |$e_2$|)
  17814. %% \end{lstlisting}
  17815. %% \end{minipage}
  17816. %% &
  17817. %% $\Rightarrow$
  17818. %% &
  17819. %% \begin{minipage}{0.7\textwidth}
  17820. %% \begin{lstlisting}
  17821. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17822. %% \end{lstlisting}
  17823. %% \end{minipage}
  17824. %% \\[2ex]\hline
  17825. %% \begin{minipage}{0.23\textwidth}
  17826. %% \begin{lstlisting}
  17827. %% (not |$e_1$|)
  17828. %% \end{lstlisting}
  17829. %% \end{minipage}
  17830. %% &
  17831. %% $\Rightarrow$
  17832. %% &
  17833. %% \begin{minipage}{0.7\textwidth}
  17834. %% \begin{lstlisting}
  17835. %% (if (eq? |$e'_1$| (inject #f Boolean))
  17836. %% (inject #t Boolean) (inject #f Boolean))
  17837. %% \end{lstlisting}
  17838. %% \end{minipage}
  17839. %% \\[2ex]\hline
  17840. \\\hline
  17841. \end{tabular}
  17842. \fi}
  17843. \end{tcolorbox}
  17844. \caption{Cast insertion.}
  17845. \label{fig:compile-r7-Lany}
  17846. \end{figure}
  17847. \section{Reveal Casts}
  17848. \label{sec:reveal-casts-Lany}
  17849. % TODO: define R'_6
  17850. In the \code{reveal\_casts} pass, we recommend compiling
  17851. \code{Project} into a conditional expression that checks whether the
  17852. value's tag matches the target type; if it does, the value is
  17853. converted to a value of the target type by removing the tag; if it
  17854. does not, the program exits.
  17855. %
  17856. {\if\edition\racketEd
  17857. %
  17858. To perform these actions we need a new primitive operation,
  17859. \code{tag-of-any}, and a new form, \code{ValueOf}.
  17860. The \code{tag-of-any} operation retrieves the type tag from a tagged
  17861. value of type \code{Any}. The \code{ValueOf} form retrieves the
  17862. underlying value from a tagged value. The \code{ValueOf} form
  17863. includes the type for the underlying value that is used by the type
  17864. checker.
  17865. %
  17866. \fi}
  17867. %
  17868. {\if\edition\pythonEd\pythonColor
  17869. %
  17870. To perform these actions we need two new AST classes: \code{TagOf} and
  17871. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  17872. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  17873. the underlying value from a tagged value. The \code{ValueOf}
  17874. operation includes the type for the underlying value which is used by
  17875. the type checker.
  17876. %
  17877. \fi}
  17878. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  17879. \code{Project} can be translated as follows:
  17880. \begin{center}
  17881. \begin{minipage}{1.0\textwidth}
  17882. {\if\edition\racketEd
  17883. \begin{lstlisting}
  17884. (Project |$e$| |$\FType$|)
  17885. |$\Rightarrow$|
  17886. (Let |$\itm{tmp}$| |$e'$|
  17887. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  17888. (Int |$\itm{tagof}(\FType)$|)))
  17889. (ValueOf |$\itm{tmp}$| |$\FType$|)
  17890. (Exit)))
  17891. \end{lstlisting}
  17892. \fi}
  17893. {\if\edition\pythonEd\pythonColor
  17894. \begin{lstlisting}
  17895. Project(|$e$|, |$\FType$|)
  17896. |$\Rightarrow$|
  17897. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  17898. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  17899. [Constant(|$\itm{tagof}(\FType)$|)]),
  17900. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  17901. Call(Name('exit'), [])))
  17902. \end{lstlisting}
  17903. \fi}
  17904. \end{minipage}
  17905. \end{center}
  17906. If the target type of the projection is a tuple or function type, then
  17907. there is a bit more work to do. For tuples, check that the length of
  17908. the tuple type matches the length of the tuple. For functions, check
  17909. that the number of parameters in the function type matches the
  17910. function's arity.
  17911. Regarding \code{Inject}, we recommend compiling it to a slightly
  17912. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  17913. takes a tag instead of a type.
  17914. \begin{center}
  17915. \begin{minipage}{1.0\textwidth}
  17916. {\if\edition\racketEd
  17917. \begin{lstlisting}
  17918. (Inject |$e$| |$\FType$|)
  17919. |$\Rightarrow$|
  17920. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  17921. \end{lstlisting}
  17922. \fi}
  17923. {\if\edition\pythonEd\pythonColor
  17924. \begin{lstlisting}
  17925. Inject(|$e$|, |$\FType$|)
  17926. |$\Rightarrow$|
  17927. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  17928. \end{lstlisting}
  17929. \fi}
  17930. \end{minipage}
  17931. \end{center}
  17932. {\if\edition\pythonEd\pythonColor
  17933. %
  17934. The introduction of \code{make\_any} makes it difficult to use
  17935. bidirectional type checking because we no longer have an expected type
  17936. to use for type checking the expression $e'$. Thus, we run into
  17937. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  17938. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  17939. annotated lambda) whose parameters have type annotations and that
  17940. records the return type.
  17941. %
  17942. \fi}
  17943. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  17944. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  17945. translation of \code{Project}.}
  17946. {\if\edition\racketEd
  17947. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17948. combine the projection action with the vector operation. Also, the
  17949. read and write operations allow arbitrary expressions for the index, so
  17950. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17951. cannot guarantee that the index is within bounds. Thus, we insert code
  17952. to perform bounds checking at runtime. The translation for
  17953. \code{any-vector-ref} is as follows, and the other two operations are
  17954. translated in a similar way:
  17955. \begin{center}
  17956. \begin{minipage}{0.95\textwidth}
  17957. \begin{lstlisting}
  17958. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17959. |$\Rightarrow$|
  17960. (Let |$v$| |$e'_1$|
  17961. (Let |$i$| |$e'_2$|
  17962. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17963. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17964. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17965. (Exit))
  17966. (Exit))))
  17967. \end{lstlisting}
  17968. \end{minipage}
  17969. \end{center}
  17970. \fi}
  17971. %
  17972. {\if\edition\pythonEd\pythonColor
  17973. %
  17974. The \code{any\_tuple\_load} operation combines the projection action
  17975. with the load operation. Also, the load operation allows arbitrary
  17976. expressions for the index so the type checker for \LangAny{}
  17977. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17978. within bounds. Thus, we insert code to perform bounds checking at
  17979. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17980. \begin{lstlisting}
  17981. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17982. |$\Rightarrow$|
  17983. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17984. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17985. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17986. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17987. Call(Name('exit'), [])),
  17988. Call(Name('exit'), [])))
  17989. \end{lstlisting}
  17990. \fi}
  17991. {\if\edition\pythonEd\pythonColor
  17992. \section{Assignment Conversion}
  17993. \label{sec:convert-assignments-Lany}
  17994. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17995. \code{AnnLambda} AST classes.
  17996. \section{Closure Conversion}
  17997. \label{sec:closure-conversion-Lany}
  17998. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17999. \code{AnnLambda} AST classes.
  18000. \fi}
  18001. \section{Remove Complex Operands}
  18002. \label{sec:rco-Lany}
  18003. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18004. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18005. %
  18006. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18007. complex expressions. Their subexpressions must be atomic.}
  18008. \section{Explicate Control and \LangCAny{}}
  18009. \label{sec:explicate-Lany}
  18010. The output of \code{explicate\_control} is the \LangCAny{} language,
  18011. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18012. %
  18013. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18014. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18015. note that the index argument of \code{vector-ref} and
  18016. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18017. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18018. %
  18019. \python{
  18020. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  18021. and \code{explicate\_pred} as appropriately to handle the new expressions
  18022. in \LangCAny{}.
  18023. }
  18024. \newcommand{\CanyASTPython}{
  18025. \begin{array}{lcl}
  18026. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  18027. &\MID& \key{TagOf}\LP \Atm \RP
  18028. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18029. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  18030. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  18031. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  18032. \end{array}
  18033. }
  18034. \newcommand{\CanyASTRacket}{
  18035. \begin{array}{lcl}
  18036. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18037. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18038. &\MID& \VALUEOF{\Atm}{\FType} \\
  18039. \Tail &::= & \LP\key{Exit}\RP
  18040. \end{array}
  18041. }
  18042. \begin{figure}[tp]
  18043. \begin{tcolorbox}[colback=white]
  18044. \small
  18045. {\if\edition\racketEd
  18046. \[
  18047. \begin{array}{l}
  18048. \gray{\CvarASTRacket} \\ \hline
  18049. \gray{\CifASTRacket} \\ \hline
  18050. \gray{\CloopASTRacket} \\ \hline
  18051. \gray{\CtupASTRacket} \\ \hline
  18052. \gray{\CfunASTRacket} \\ \hline
  18053. \gray{\ClambdaASTRacket} \\ \hline
  18054. \CanyASTRacket \\
  18055. \begin{array}{lcl}
  18056. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18057. \end{array}
  18058. \end{array}
  18059. \]
  18060. \fi}
  18061. {\if\edition\pythonEd\pythonColor
  18062. \[
  18063. \begin{array}{l}
  18064. \gray{\CifASTPython} \\ \hline
  18065. \gray{\CtupASTPython} \\ \hline
  18066. \gray{\CfunASTPython} \\ \hline
  18067. \gray{\ClambdaASTPython} \\ \hline
  18068. \CanyASTPython \\
  18069. \begin{array}{lcl}
  18070. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18071. \end{array}
  18072. \end{array}
  18073. \]
  18074. \fi}
  18075. \end{tcolorbox}
  18076. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18077. \label{fig:c5-syntax}
  18078. \end{figure}
  18079. \section{Select Instructions}
  18080. \label{sec:select-Lany}
  18081. \index{subject}{select instructions}
  18082. In the \code{select\_instructions} pass, we translate the primitive
  18083. operations on the \ANYTY{} type to x86 instructions that manipulate
  18084. the three tag bits of the tagged value. In the following descriptions,
  18085. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18086. of translating $e$ into an x86 argument:
  18087. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18088. We recommend compiling the
  18089. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18090. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18091. shifts the destination to the left by the number of bits specified by its
  18092. source argument (in this case three, the length of the tag), and it
  18093. preserves the sign of the integer. We use the \key{orq} instruction to
  18094. combine the tag and the value to form the tagged value.
  18095. {\if\edition\racketEd
  18096. \begin{lstlisting}
  18097. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18098. |$\Rightarrow$|
  18099. movq |$e'$|, |\itm{lhs'}|
  18100. salq $3, |\itm{lhs'}|
  18101. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18102. \end{lstlisting}
  18103. \fi}
  18104. %
  18105. {\if\edition\pythonEd\pythonColor
  18106. \begin{lstlisting}
  18107. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18108. |$\Rightarrow$|
  18109. movq |$e'$|, |\itm{lhs'}|
  18110. salq $3, |\itm{lhs'}|
  18111. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18112. \end{lstlisting}
  18113. \fi}
  18114. %
  18115. The instruction selection\index{subject}{instruction selection} for
  18116. tuples and procedures is different because there is no need to shift
  18117. them to the left. The rightmost 3 bits are already zeros, so we simply
  18118. combine the value and the tag using \key{orq}. \\
  18119. %
  18120. {\if\edition\racketEd
  18121. \begin{center}
  18122. \begin{minipage}{\textwidth}
  18123. \begin{lstlisting}
  18124. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18125. |$\Rightarrow$|
  18126. movq |$e'$|, |\itm{lhs'}|
  18127. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18128. \end{lstlisting}
  18129. \end{minipage}
  18130. \end{center}
  18131. \fi}
  18132. %
  18133. {\if\edition\pythonEd\pythonColor
  18134. \begin{lstlisting}
  18135. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18136. |$\Rightarrow$|
  18137. movq |$e'$|, |\itm{lhs'}|
  18138. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18139. \end{lstlisting}
  18140. \fi}
  18141. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18142. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18143. operation extracts the type tag from a value of type \ANYTY{}. The
  18144. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18145. bitwise-and of the value with $111$ ($7$ decimal).
  18146. %
  18147. {\if\edition\racketEd
  18148. \begin{lstlisting}
  18149. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18150. |$\Rightarrow$|
  18151. movq |$e'$|, |\itm{lhs'}|
  18152. andq $7, |\itm{lhs'}|
  18153. \end{lstlisting}
  18154. \fi}
  18155. %
  18156. {\if\edition\pythonEd\pythonColor
  18157. \begin{lstlisting}
  18158. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18159. |$\Rightarrow$|
  18160. movq |$e'$|, |\itm{lhs'}|
  18161. andq $7, |\itm{lhs'}|
  18162. \end{lstlisting}
  18163. \fi}
  18164. \paragraph{\code{ValueOf}}
  18165. The instructions for \key{ValueOf} also differ, depending on whether
  18166. the type $T$ is a pointer (tuple or function) or not (integer or
  18167. Boolean). The following shows the instruction
  18168. selection for integers and
  18169. Booleans, in which we produce an untagged value by shifting it to the
  18170. right by 3 bits:
  18171. %
  18172. {\if\edition\racketEd
  18173. \begin{lstlisting}
  18174. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18175. |$\Rightarrow$|
  18176. movq |$e'$|, |\itm{lhs'}|
  18177. sarq $3, |\itm{lhs'}|
  18178. \end{lstlisting}
  18179. \fi}
  18180. %
  18181. {\if\edition\pythonEd\pythonColor
  18182. \begin{lstlisting}
  18183. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18184. |$\Rightarrow$|
  18185. movq |$e'$|, |\itm{lhs'}|
  18186. sarq $3, |\itm{lhs'}|
  18187. \end{lstlisting}
  18188. \fi}
  18189. %
  18190. In the case for tuples and procedures, we zero out the rightmost 3
  18191. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18192. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18193. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18194. Finally, we apply \code{andq} with the tagged value to get the desired
  18195. result.
  18196. %
  18197. {\if\edition\racketEd
  18198. \begin{lstlisting}
  18199. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18200. |$\Rightarrow$|
  18201. movq $|$-8$|, |\itm{lhs'}|
  18202. andq |$e'$|, |\itm{lhs'}|
  18203. \end{lstlisting}
  18204. \fi}
  18205. %
  18206. {\if\edition\pythonEd\pythonColor
  18207. \begin{lstlisting}
  18208. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18209. |$\Rightarrow$|
  18210. movq $|$-8$|, |\itm{lhs'}|
  18211. andq |$e'$|, |\itm{lhs'}|
  18212. \end{lstlisting}
  18213. \fi}
  18214. %% \paragraph{Type Predicates} We leave it to the reader to
  18215. %% devise a sequence of instructions to implement the type predicates
  18216. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18217. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18218. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18219. operation combines the effect of \code{ValueOf} with accessing the
  18220. length of a tuple from the tag stored at the zero index of the tuple.
  18221. {\if\edition\racketEd
  18222. \begin{lstlisting}
  18223. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18224. |$\Longrightarrow$|
  18225. movq $|$-8$|, %r11
  18226. andq |$e_1'$|, %r11
  18227. movq 0(%r11), %r11
  18228. andq $126, %r11
  18229. sarq $1, %r11
  18230. movq %r11, |$\itm{lhs'}$|
  18231. \end{lstlisting}
  18232. \fi}
  18233. {\if\edition\pythonEd\pythonColor
  18234. \begin{lstlisting}
  18235. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18236. |$\Longrightarrow$|
  18237. movq $|$-8$|, %r11
  18238. andq |$e_1'$|, %r11
  18239. movq 0(%r11), %r11
  18240. andq $126, %r11
  18241. sarq $1, %r11
  18242. movq %r11, |$\itm{lhs'}$|
  18243. \end{lstlisting}
  18244. \fi}
  18245. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18246. This operation combines the effect of \code{ValueOf} with reading an
  18247. element of the tuple (see
  18248. section~\ref{sec:select-instructions-gc}). However, the index may be
  18249. an arbitrary atom, so instead of computing the offset at compile time,
  18250. we must generate instructions to compute the offset at runtime as
  18251. follows. Note the use of the new instruction \code{imulq}.
  18252. \begin{center}
  18253. \begin{minipage}{0.96\textwidth}
  18254. {\if\edition\racketEd
  18255. \begin{lstlisting}
  18256. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18257. |$\Longrightarrow$|
  18258. movq |$\neg 111$|, %r11
  18259. andq |$e_1'$|, %r11
  18260. movq |$e_2'$|, %rax
  18261. addq $1, %rax
  18262. imulq $8, %rax
  18263. addq %rax, %r11
  18264. movq 0(%r11) |$\itm{lhs'}$|
  18265. \end{lstlisting}
  18266. \fi}
  18267. %
  18268. {\if\edition\pythonEd\pythonColor
  18269. \begin{lstlisting}
  18270. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18271. |$\Longrightarrow$|
  18272. movq $|$-8$|, %r11
  18273. andq |$e_1'$|, %r11
  18274. movq |$e_2'$|, %rax
  18275. addq $1, %rax
  18276. imulq $8, %rax
  18277. addq %rax, %r11
  18278. movq 0(%r11) |$\itm{lhs'}$|
  18279. \end{lstlisting}
  18280. \fi}
  18281. \end{minipage}
  18282. \end{center}
  18283. % $ pacify font lock
  18284. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18285. %% The code generation for
  18286. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18287. %% analogous to the above translation for reading from a tuple.
  18288. \section{Register Allocation for \LangAny{}}
  18289. \label{sec:register-allocation-Lany}
  18290. \index{subject}{register allocation}
  18291. There is an interesting interaction between tagged values and garbage
  18292. collection that has an impact on register allocation. A variable of
  18293. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18294. that needs to be inspected and copied during garbage collection. Thus,
  18295. we need to treat variables of type \ANYTY{} in a similar way to
  18296. variables of tuple type for purposes of register allocation,
  18297. with particular attention to the following:
  18298. \begin{itemize}
  18299. \item If a variable of type \ANYTY{} is live during a function call,
  18300. then it must be spilled. This can be accomplished by changing
  18301. \code{build\_interference} to mark all variables of type \ANYTY{}
  18302. that are live after a \code{callq} to be interfering with all the
  18303. registers.
  18304. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18305. the root stack instead of the normal procedure call stack.
  18306. \end{itemize}
  18307. Another concern regarding the root stack is that the garbage collector
  18308. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18309. tagged value that points to a tuple, and (3) a tagged value that is
  18310. not a tuple. We enable this differentiation by choosing not to use the
  18311. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18312. reserved for identifying plain old pointers to tuples. That way, if
  18313. one of the first three bits is set, then we have a tagged value and
  18314. inspecting the tag can differentiate between tuples ($010$) and the
  18315. other kinds of values.
  18316. %% \begin{exercise}\normalfont
  18317. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18318. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18319. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18320. %% compiler on these new programs and all of your previously created test
  18321. %% programs.
  18322. %% \end{exercise}
  18323. \begin{exercise}\normalfont\normalsize
  18324. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18325. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18326. by removing type annotations. Add five more test programs that
  18327. specifically rely on the language being dynamically typed. That is,
  18328. they should not be legal programs in a statically typed language, but
  18329. nevertheless they should be valid \LangDyn{} programs that run to
  18330. completion without error.
  18331. \end{exercise}
  18332. \begin{figure}[p]
  18333. \begin{tcolorbox}[colback=white]
  18334. {\if\edition\racketEd
  18335. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18336. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18337. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18338. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18339. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18340. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18341. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18342. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18343. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18344. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18345. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18346. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18347. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18348. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18349. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18350. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18351. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18352. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18353. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18354. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18355. \path[->,bend left=15] (Lfun) edge [above] node
  18356. {\ttfamily\footnotesize shrink} (Lfun-2);
  18357. \path[->,bend left=15] (Lfun-2) edge [above] node
  18358. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18359. \path[->,bend left=15] (Lfun-3) edge [above] node
  18360. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18361. \path[->,bend left=15] (Lfun-4) edge [left] node
  18362. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18363. \path[->,bend left=15] (Lfun-5) edge [below] node
  18364. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18365. \path[->,bend left=15] (Lfun-6) edge [below] node
  18366. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18367. \path[->,bend right=15] (Lfun-7) edge [above] node
  18368. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18369. \path[->,bend right=15] (F1-2) edge [right] node
  18370. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18371. \path[->,bend right=15] (F1-3) edge [below] node
  18372. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18373. \path[->,bend right=15] (F1-4) edge [below] node
  18374. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18375. \path[->,bend left=15] (F1-5) edge [above] node
  18376. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18377. \path[->,bend left=10] (F1-6) edge [below] node
  18378. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18379. \path[->,bend left=15] (C3-2) edge [right] node
  18380. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18381. \path[->,bend right=15] (x86-2) edge [right] node
  18382. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18383. \path[->,bend right=15] (x86-2-1) edge [below] node
  18384. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18385. \path[->,bend right=15] (x86-2-2) edge [right] node
  18386. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18387. \path[->,bend left=15] (x86-3) edge [above] node
  18388. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18389. \path[->,bend left=15] (x86-4) edge [right] node
  18390. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18391. \end{tikzpicture}
  18392. \fi}
  18393. {\if\edition\pythonEd\pythonColor
  18394. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18395. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18396. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18397. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18398. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18399. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18400. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18401. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18402. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18403. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18404. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18405. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18406. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18407. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18408. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18409. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18410. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18411. \path[->,bend left=15] (Lfun) edge [above] node
  18412. {\ttfamily\footnotesize shrink} (Lfun-2);
  18413. \path[->,bend left=15] (Lfun-2) edge [above] node
  18414. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18415. \path[->,bend left=15] (Lfun-3) edge [above] node
  18416. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18417. \path[->,bend left=15] (Lfun-4) edge [left] node
  18418. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18419. \path[->,bend left=15] (Lfun-5) edge [below] node
  18420. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18421. \path[->,bend right=15] (Lfun-6) edge [above] node
  18422. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18423. \path[->,bend right=15] (Lfun-7) edge [above] node
  18424. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18425. \path[->,bend right=15] (F1-2) edge [right] node
  18426. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18427. \path[->,bend right=15] (F1-3) edge [below] node
  18428. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18429. \path[->,bend left=15] (F1-5) edge [above] node
  18430. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18431. \path[->,bend left=10] (F1-6) edge [below] node
  18432. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18433. \path[->,bend right=15] (C3-2) edge [right] node
  18434. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18435. \path[->,bend right=15] (x86-2) edge [below] node
  18436. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18437. \path[->,bend right=15] (x86-3) edge [below] node
  18438. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18439. \path[->,bend left=15] (x86-4) edge [above] node
  18440. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18441. \end{tikzpicture}
  18442. \fi}
  18443. \end{tcolorbox}
  18444. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18445. \label{fig:Ldyn-passes}
  18446. \end{figure}
  18447. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18448. for the compilation of \LangDyn{}.
  18449. % Further Reading
  18450. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18451. %% {\if\edition\pythonEd\pythonColor
  18452. %% \chapter{Objects}
  18453. %% \label{ch:Lobject}
  18454. %% \index{subject}{objects}
  18455. %% \index{subject}{classes}
  18456. %% \setcounter{footnote}{0}
  18457. %% \fi}
  18458. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18459. \chapter{Gradual Typing}
  18460. \label{ch:Lgrad}
  18461. \index{subject}{gradual typing}
  18462. \setcounter{footnote}{0}
  18463. This chapter studies the language \LangGrad{}, in which the programmer
  18464. can choose between static and dynamic type checking in different parts
  18465. of a program, thereby mixing the statically typed \LangLam{} language
  18466. with the dynamically typed \LangDyn{}. There are several approaches to
  18467. mixing static and dynamic typing, including multilanguage
  18468. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18469. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18470. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18471. programmer controls the amount of static versus dynamic checking by
  18472. adding or removing type annotations on parameters and
  18473. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18474. The definition of the concrete syntax of \LangGrad{} is shown in
  18475. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18476. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18477. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18478. annotations are optional, which is specified in the grammar using the
  18479. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18480. annotations are not optional, but we use the \CANYTY{} type when a type
  18481. annotation is absent.
  18482. %
  18483. Both the type checker and the interpreter for \LangGrad{} require some
  18484. interesting changes to enable gradual typing, which we discuss in the
  18485. next two sections.
  18486. \newcommand{\LgradGrammarRacket}{
  18487. \begin{array}{lcl}
  18488. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18489. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18490. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18491. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18492. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18493. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18494. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18495. \end{array}
  18496. }
  18497. \newcommand{\LgradASTRacket}{
  18498. \begin{array}{lcl}
  18499. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18500. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18501. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18502. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18503. \itm{op} &::=& \code{procedure-arity} \\
  18504. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18505. \end{array}
  18506. }
  18507. \newcommand{\LgradGrammarPython}{
  18508. \begin{array}{lcl}
  18509. \Type &::=& \key{Any}
  18510. \MID \key{int}
  18511. \MID \key{bool}
  18512. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18513. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18514. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18515. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18516. \MID \CARITY{\Exp} \\
  18517. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18518. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18519. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18520. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18521. \end{array}
  18522. }
  18523. \newcommand{\LgradASTPython}{
  18524. \begin{array}{lcl}
  18525. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18526. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18527. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18528. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18529. &\MID& \ARITY{\Exp} \\
  18530. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18531. \MID \RETURN{\Exp} \\
  18532. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18533. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18534. \end{array}
  18535. }
  18536. \begin{figure}[tp]
  18537. \centering
  18538. \begin{tcolorbox}[colback=white]
  18539. \small
  18540. {\if\edition\racketEd
  18541. \[
  18542. \begin{array}{l}
  18543. \gray{\LintGrammarRacket{}} \\ \hline
  18544. \gray{\LvarGrammarRacket{}} \\ \hline
  18545. \gray{\LifGrammarRacket{}} \\ \hline
  18546. \gray{\LwhileGrammarRacket} \\ \hline
  18547. \gray{\LtupGrammarRacket} \\ \hline
  18548. \LgradGrammarRacket \\
  18549. \begin{array}{lcl}
  18550. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18551. \end{array}
  18552. \end{array}
  18553. \]
  18554. \fi}
  18555. {\if\edition\pythonEd\pythonColor
  18556. \[
  18557. \begin{array}{l}
  18558. \gray{\LintGrammarPython{}} \\ \hline
  18559. \gray{\LvarGrammarPython{}} \\ \hline
  18560. \gray{\LifGrammarPython{}} \\ \hline
  18561. \gray{\LwhileGrammarPython} \\ \hline
  18562. \gray{\LtupGrammarPython} \\ \hline
  18563. \LgradGrammarPython \\
  18564. \begin{array}{lcl}
  18565. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18566. \end{array}
  18567. \end{array}
  18568. \]
  18569. \fi}
  18570. \end{tcolorbox}
  18571. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18572. \label{fig:Lgrad-concrete-syntax}
  18573. \end{figure}
  18574. \begin{figure}[tp]
  18575. \centering
  18576. \begin{tcolorbox}[colback=white]
  18577. \small
  18578. {\if\edition\racketEd
  18579. \[
  18580. \begin{array}{l}
  18581. \gray{\LintOpAST} \\ \hline
  18582. \gray{\LvarASTRacket{}} \\ \hline
  18583. \gray{\LifASTRacket{}} \\ \hline
  18584. \gray{\LwhileASTRacket{}} \\ \hline
  18585. \gray{\LtupASTRacket{}} \\ \hline
  18586. \LgradASTRacket \\
  18587. \begin{array}{lcl}
  18588. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18589. \end{array}
  18590. \end{array}
  18591. \]
  18592. \fi}
  18593. {\if\edition\pythonEd\pythonColor
  18594. \[
  18595. \begin{array}{l}
  18596. \gray{\LintASTPython{}} \\ \hline
  18597. \gray{\LvarASTPython{}} \\ \hline
  18598. \gray{\LifASTPython{}} \\ \hline
  18599. \gray{\LwhileASTPython} \\ \hline
  18600. \gray{\LtupASTPython} \\ \hline
  18601. \LgradASTPython \\
  18602. \begin{array}{lcl}
  18603. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18604. \end{array}
  18605. \end{array}
  18606. \]
  18607. \fi}
  18608. \end{tcolorbox}
  18609. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18610. \label{fig:Lgrad-syntax}
  18611. \end{figure}
  18612. % TODO: more road map -Jeremy
  18613. %\clearpage
  18614. \section{Type Checking \LangGrad{}}
  18615. \label{sec:gradual-type-check}
  18616. We begin by discussing the type checking of a partially typed variant
  18617. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18618. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18619. statically typed, so there is nothing special happening there with
  18620. respect to type checking. On the other hand, the \code{inc} function
  18621. does not have type annotations, so the type checker assigns the type
  18622. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18623. \code{+} operator inside \code{inc}. It expects both arguments to have
  18624. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18625. a gradually typed language, such differences are allowed so long as
  18626. the types are \emph{consistent}; that is, they are equal except in
  18627. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18628. is consistent with every other type. Figure~\ref{fig:consistent}
  18629. shows the definition of the
  18630. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18631. %
  18632. So the type checker allows the \code{+} operator to be applied
  18633. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18634. %
  18635. Next consider the call to the \code{map} function shown in
  18636. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18637. tuple. The \code{inc} function has type
  18638. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18639. but parameter \code{f} of \code{map} has type
  18640. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18641. The type checker for \LangGrad{} accepts this call because the two types are
  18642. consistent.
  18643. \begin{figure}[btp]
  18644. % gradual_test_9.rkt
  18645. \begin{tcolorbox}[colback=white]
  18646. {\if\edition\racketEd
  18647. \begin{lstlisting}
  18648. (define (map [f : (Integer -> Integer)]
  18649. [v : (Vector Integer Integer)])
  18650. : (Vector Integer Integer)
  18651. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18652. (define (inc x) (+ x 1))
  18653. (vector-ref (map inc (vector 0 41)) 1)
  18654. \end{lstlisting}
  18655. \fi}
  18656. {\if\edition\pythonEd\pythonColor
  18657. \begin{lstlisting}
  18658. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18659. return f(v[0]), f(v[1])
  18660. def inc(x):
  18661. return x + 1
  18662. t = map(inc, (0, 41))
  18663. print(t[1])
  18664. \end{lstlisting}
  18665. \fi}
  18666. \end{tcolorbox}
  18667. \caption{A partially typed version of the \code{map} example.}
  18668. \label{fig:gradual-map}
  18669. \end{figure}
  18670. \begin{figure}[tbp]
  18671. \begin{tcolorbox}[colback=white]
  18672. {\if\edition\racketEd
  18673. \begin{lstlisting}
  18674. (define/public (consistent? t1 t2)
  18675. (match* (t1 t2)
  18676. [('Integer 'Integer) #t]
  18677. [('Boolean 'Boolean) #t]
  18678. [('Void 'Void) #t]
  18679. [('Any t2) #t]
  18680. [(t1 'Any) #t]
  18681. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18682. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18683. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18684. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18685. (consistent? rt1 rt2))]
  18686. [(other wise) #f]))
  18687. \end{lstlisting}
  18688. \fi}
  18689. {\if\edition\pythonEd\pythonColor
  18690. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18691. def consistent(self, t1, t2):
  18692. match (t1, t2):
  18693. case (AnyType(), _):
  18694. return True
  18695. case (_, AnyType()):
  18696. return True
  18697. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18698. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18699. case (TupleType(ts1), TupleType(ts2)):
  18700. return all(map(self.consistent, ts1, ts2))
  18701. case (_, _):
  18702. return t1 == t2
  18703. \end{lstlisting}
  18704. \fi}
  18705. \end{tcolorbox}
  18706. \caption{The consistency method on types.}
  18707. \label{fig:consistent}
  18708. \end{figure}
  18709. It is also helpful to consider how gradual typing handles programs with an
  18710. error, such as applying \code{map} to a function that sometimes
  18711. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18712. type checker for \LangGrad{} accepts this program because the type of
  18713. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18714. \code{map}; that is,
  18715. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18716. is consistent with
  18717. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18718. One might say that a gradual type checker is optimistic in that it
  18719. accepts programs that might execute without a runtime type error.
  18720. %
  18721. The definition of the type checker for \LangGrad{} is shown in
  18722. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18723. and \ref{fig:type-check-Lgradual-3}.
  18724. %% \begin{figure}[tp]
  18725. %% \centering
  18726. %% \fbox{
  18727. %% \begin{minipage}{0.96\textwidth}
  18728. %% \small
  18729. %% \[
  18730. %% \begin{array}{lcl}
  18731. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18732. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18733. %% \end{array}
  18734. %% \]
  18735. %% \end{minipage}
  18736. %% }
  18737. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18738. %% \label{fig:Lgrad-prime-syntax}
  18739. %% \end{figure}
  18740. \begin{figure}[tbp]
  18741. \begin{tcolorbox}[colback=white]
  18742. {\if\edition\racketEd
  18743. \begin{lstlisting}
  18744. (define (map [f : (Integer -> Integer)]
  18745. [v : (Vector Integer Integer)])
  18746. : (Vector Integer Integer)
  18747. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18748. (define (inc x) (+ x 1))
  18749. (define (true) #t)
  18750. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18751. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18752. \end{lstlisting}
  18753. \fi}
  18754. {\if\edition\pythonEd\pythonColor
  18755. \begin{lstlisting}
  18756. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18757. return f(v[0]), f(v[1])
  18758. def inc(x):
  18759. return x + 1
  18760. def true():
  18761. return True
  18762. def maybe_inc(x):
  18763. return inc(x) if input_int() == 0 else true()
  18764. t = map(maybe_inc, (0, 41))
  18765. print( t[1] )
  18766. \end{lstlisting}
  18767. \fi}
  18768. \end{tcolorbox}
  18769. \caption{A variant of the \code{map} example with an error.}
  18770. \label{fig:map-maybe_inc}
  18771. \end{figure}
  18772. Running this program with input \code{1} triggers an
  18773. error when the \code{maybe\_inc} function returns
  18774. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18775. performs checking at runtime to ensure the integrity of the static
  18776. types, such as the
  18777. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18778. annotation on
  18779. parameter \code{f} of \code{map}.
  18780. Here we give a preview of how the runtime checking is accomplished;
  18781. the following sections provide the details.
  18782. The runtime checking is carried out by a new \code{Cast} AST node that
  18783. is generated in a new pass named \code{cast\_insert}. The output of
  18784. \code{cast\_insert} is a program in the \LangCast{} language, which
  18785. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18786. %
  18787. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18788. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18789. inserted every time the type checker encounters two types that are
  18790. consistent but not equal. In the \code{inc} function, \code{x} is
  18791. cast to \INTTY{} and the result of the \code{+} is cast to
  18792. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18793. is cast from
  18794. \racket{\code{(Any -> Any)}}
  18795. \python{\code{Callable[[Any], Any]}}
  18796. to
  18797. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18798. %
  18799. In the next section we see how to interpret the \code{Cast} node.
  18800. \begin{figure}[btp]
  18801. \begin{tcolorbox}[colback=white]
  18802. {\if\edition\racketEd
  18803. \begin{lstlisting}
  18804. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  18805. : (Vector Integer Integer)
  18806. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18807. (define (inc [x : Any]) : Any
  18808. (cast (+ (cast x Any Integer) 1) Integer Any))
  18809. (define (true) : Any (cast #t Boolean Any))
  18810. (define (maybe_inc [x : Any]) : Any
  18811. (if (eq? 0 (read)) (inc x) (true)))
  18812. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  18813. (vector 0 41)) 0)
  18814. \end{lstlisting}
  18815. \fi}
  18816. {\if\edition\pythonEd\pythonColor
  18817. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18818. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18819. return f(v[0]), f(v[1])
  18820. def inc(x : Any) -> Any:
  18821. return Cast(Cast(x, Any, int) + 1, int, Any)
  18822. def true() -> Any:
  18823. return Cast(True, bool, Any)
  18824. def maybe_inc(x : Any) -> Any:
  18825. return inc(x) if input_int() == 0 else true()
  18826. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  18827. (0, 41))
  18828. print(t[1])
  18829. \end{lstlisting}
  18830. \fi}
  18831. \end{tcolorbox}
  18832. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  18833. and \code{maybe\_inc} example.}
  18834. \label{fig:map-cast}
  18835. \end{figure}
  18836. {\if\edition\pythonEd\pythonColor
  18837. \begin{figure}[tbp]
  18838. \begin{tcolorbox}[colback=white]
  18839. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18840. class TypeCheckLgrad(TypeCheckLlambda):
  18841. def type_check_exp(self, e, env) -> Type:
  18842. match e:
  18843. case Name(id):
  18844. return env[id]
  18845. case Constant(value) if isinstance(value, bool):
  18846. return BoolType()
  18847. case Constant(value) if isinstance(value, int):
  18848. return IntType()
  18849. case Call(Name('input_int'), []):
  18850. return IntType()
  18851. case BinOp(left, op, right):
  18852. left_type = self.type_check_exp(left, env)
  18853. self.check_consistent(left_type, IntType(), left)
  18854. right_type = self.type_check_exp(right, env)
  18855. self.check_consistent(right_type, IntType(), right)
  18856. return IntType()
  18857. case IfExp(test, body, orelse):
  18858. test_t = self.type_check_exp(test, env)
  18859. self.check_consistent(test_t, BoolType(), test)
  18860. body_t = self.type_check_exp(body, env)
  18861. orelse_t = self.type_check_exp(orelse, env)
  18862. self.check_consistent(body_t, orelse_t, e)
  18863. return self.join_types(body_t, orelse_t)
  18864. case Call(func, args):
  18865. func_t = self.type_check_exp(func, env)
  18866. args_t = [self.type_check_exp(arg, env) for arg in args]
  18867. match func_t:
  18868. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  18869. for (arg_t, param_t) in zip(args_t, params_t):
  18870. self.check_consistent(param_t, arg_t, e)
  18871. return return_t
  18872. case AnyType():
  18873. return AnyType()
  18874. case _:
  18875. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  18876. ...
  18877. case _:
  18878. raise Exception('type_check_exp: unexpected ' + repr(e))
  18879. \end{lstlisting}
  18880. \end{tcolorbox}
  18881. \caption{Type checking expressions in the \LangGrad{} language.}
  18882. \label{fig:type-check-Lgradual-1}
  18883. \end{figure}
  18884. \begin{figure}[tbp]
  18885. \begin{tcolorbox}[colback=white]
  18886. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18887. def check_exp(self, e, expected_ty, env):
  18888. match e:
  18889. case Lambda(params, body):
  18890. match expected_ty:
  18891. case FunctionType(params_t, return_t):
  18892. new_env = env.copy().update(zip(params, params_t))
  18893. e.has_type = expected_ty
  18894. body_ty = self.type_check_exp(body, new_env)
  18895. self.check_consistent(body_ty, return_t)
  18896. case AnyType():
  18897. new_env = env.copy().update((p, AnyType()) for p in params)
  18898. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  18899. body_ty = self.type_check_exp(body, new_env)
  18900. case _:
  18901. raise Exception('lambda does not have type ' + str(expected_ty))
  18902. case _:
  18903. e_ty = self.type_check_exp(e, env)
  18904. self.check_consistent(e_ty, expected_ty, e)
  18905. \end{lstlisting}
  18906. \end{tcolorbox}
  18907. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  18908. \label{fig:type-check-Lgradual-2}
  18909. \end{figure}
  18910. \begin{figure}[tbp]
  18911. \begin{tcolorbox}[colback=white]
  18912. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18913. def type_check_stmt(self, s, env, return_type):
  18914. match s:
  18915. case Assign([Name(id)], value):
  18916. value_ty = self.type_check_exp(value, env)
  18917. if id in env:
  18918. self.check_consistent(env[id], value_ty, value)
  18919. else:
  18920. env[id] = value_ty
  18921. ...
  18922. case _:
  18923. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  18924. def type_check_stmts(self, ss, env, return_type):
  18925. for s in ss:
  18926. self.type_check_stmt(s, env, return_type)
  18927. \end{lstlisting}
  18928. \end{tcolorbox}
  18929. \caption{Type checking statements in the \LangGrad{} language.}
  18930. \label{fig:type-check-Lgradual-3}
  18931. \end{figure}
  18932. \begin{figure}[tbp]
  18933. \begin{tcolorbox}[colback=white]
  18934. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18935. def join_types(self, t1, t2):
  18936. match (t1, t2):
  18937. case (AnyType(), _):
  18938. return t2
  18939. case (_, AnyType()):
  18940. return t1
  18941. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18942. return FunctionType(list(map(self.join_types, ps1, ps2)),
  18943. self.join_types(rt1,rt2))
  18944. case (TupleType(ts1), TupleType(ts2)):
  18945. return TupleType(list(map(self.join_types, ts1, ts2)))
  18946. case (_, _):
  18947. return t1
  18948. def check_consistent(self, t1, t2, e):
  18949. if not self.consistent(t1, t2):
  18950. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  18951. + ' in ' + repr(e))
  18952. \end{lstlisting}
  18953. \end{tcolorbox}
  18954. \caption{Auxiliary methods for type checking \LangGrad{}.}
  18955. \label{fig:type-check-Lgradual-aux}
  18956. \end{figure}
  18957. \fi}
  18958. {\if\edition\racketEd
  18959. \begin{figure}[tbp]
  18960. \begin{tcolorbox}[colback=white]
  18961. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18962. (define/override (type-check-exp env)
  18963. (lambda (e)
  18964. (define recur (type-check-exp env))
  18965. (match e
  18966. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  18967. (define-values (new-es ts)
  18968. (for/lists (exprs types) ([e es])
  18969. (recur e)))
  18970. (define t-ret (type-check-op op ts e))
  18971. (values (Prim op new-es) t-ret)]
  18972. [(Prim 'eq? (list e1 e2))
  18973. (define-values (e1^ t1) (recur e1))
  18974. (define-values (e2^ t2) (recur e2))
  18975. (check-consistent? t1 t2 e)
  18976. (define T (meet t1 t2))
  18977. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  18978. [(Prim 'and (list e1 e2))
  18979. (recur (If e1 e2 (Bool #f)))]
  18980. [(Prim 'or (list e1 e2))
  18981. (define tmp (gensym 'tmp))
  18982. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18983. [(If e1 e2 e3)
  18984. (define-values (e1^ T1) (recur e1))
  18985. (define-values (e2^ T2) (recur e2))
  18986. (define-values (e3^ T3) (recur e3))
  18987. (check-consistent? T1 'Boolean e)
  18988. (check-consistent? T2 T3 e)
  18989. (define Tif (meet T2 T3))
  18990. (values (If e1^ e2^ e3^) Tif)]
  18991. [(SetBang x e1)
  18992. (define-values (e1^ T1) (recur e1))
  18993. (define varT (dict-ref env x))
  18994. (check-consistent? T1 varT e)
  18995. (values (SetBang x e1^) 'Void)]
  18996. [(WhileLoop e1 e2)
  18997. (define-values (e1^ T1) (recur e1))
  18998. (check-consistent? T1 'Boolean e)
  18999. (define-values (e2^ T2) ((type-check-exp env) e2))
  19000. (values (WhileLoop e1^ e2^) 'Void)]
  19001. [(Prim 'vector-length (list e1))
  19002. (define-values (e1^ t) (recur e1))
  19003. (match t
  19004. [`(Vector ,ts ...)
  19005. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19006. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19007. \end{lstlisting}
  19008. \end{tcolorbox}
  19009. \caption{Type checker for the \LangGrad{} language, part 1.}
  19010. \label{fig:type-check-Lgradual-1}
  19011. \end{figure}
  19012. \begin{figure}[tbp]
  19013. \begin{tcolorbox}[colback=white]
  19014. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19015. [(Prim 'vector-ref (list e1 e2))
  19016. (define-values (e1^ t1) (recur e1))
  19017. (define-values (e2^ t2) (recur e2))
  19018. (check-consistent? t2 'Integer e)
  19019. (match t1
  19020. [`(Vector ,ts ...)
  19021. (match e2^
  19022. [(Int i)
  19023. (unless (and (0 . <= . i) (i . < . (length ts)))
  19024. (error 'type-check "invalid index ~a in ~a" i e))
  19025. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19026. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19027. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19028. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19029. [(Prim 'vector-set! (list e1 e2 e3) )
  19030. (define-values (e1^ t1) (recur e1))
  19031. (define-values (e2^ t2) (recur e2))
  19032. (define-values (e3^ t3) (recur e3))
  19033. (check-consistent? t2 'Integer e)
  19034. (match t1
  19035. [`(Vector ,ts ...)
  19036. (match e2^
  19037. [(Int i)
  19038. (unless (and (0 . <= . i) (i . < . (length ts)))
  19039. (error 'type-check "invalid index ~a in ~a" i e))
  19040. (check-consistent? (list-ref ts i) t3 e)
  19041. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19042. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19043. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19044. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19045. [(Apply e1 e2s)
  19046. (define-values (e1^ T1) (recur e1))
  19047. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19048. (match T1
  19049. [`(,T1ps ... -> ,T1rt)
  19050. (for ([T2 T2s] [Tp T1ps])
  19051. (check-consistent? T2 Tp e))
  19052. (values (Apply e1^ e2s^) T1rt)]
  19053. [`Any (values (Apply e1^ e2s^) 'Any)]
  19054. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19055. [(Lambda params Tr e1)
  19056. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19057. (match p
  19058. [`[,x : ,T] (values x T)]
  19059. [(? symbol? x) (values x 'Any)])))
  19060. (define-values (e1^ T1)
  19061. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19062. (check-consistent? Tr T1 e)
  19063. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19064. `(,@Ts -> ,Tr))]
  19065. [else ((super type-check-exp env) e)]
  19066. )))
  19067. \end{lstlisting}
  19068. \end{tcolorbox}
  19069. \caption{Type checker for the \LangGrad{} language, part 2.}
  19070. \label{fig:type-check-Lgradual-2}
  19071. \end{figure}
  19072. \begin{figure}[tbp]
  19073. \begin{tcolorbox}[colback=white]
  19074. \begin{lstlisting}
  19075. (define/override (type-check-def env)
  19076. (lambda (e)
  19077. (match e
  19078. [(Def f params rt info body)
  19079. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19080. (match p
  19081. [`[,x : ,T] (values x T)]
  19082. [(? symbol? x) (values x 'Any)])))
  19083. (define new-env (append (map cons xs ps) env))
  19084. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19085. (check-consistent? ty^ rt e)
  19086. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19087. [else (error 'type-check "ill-formed function definition ~a" e)]
  19088. )))
  19089. (define/override (type-check-program e)
  19090. (match e
  19091. [(Program info body)
  19092. (define-values (body^ ty) ((type-check-exp '()) body))
  19093. (check-consistent? ty 'Integer e)
  19094. (ProgramDefsExp info '() body^)]
  19095. [(ProgramDefsExp info ds body)
  19096. (define new-env (for/list ([d ds])
  19097. (cons (Def-name d) (fun-def-type d))))
  19098. (define ds^ (for/list ([d ds])
  19099. ((type-check-def new-env) d)))
  19100. (define-values (body^ ty) ((type-check-exp new-env) body))
  19101. (check-consistent? ty 'Integer e)
  19102. (ProgramDefsExp info ds^ body^)]
  19103. [else (super type-check-program e)]))
  19104. \end{lstlisting}
  19105. \end{tcolorbox}
  19106. \caption{Type checker for the \LangGrad{} language, part 3.}
  19107. \label{fig:type-check-Lgradual-3}
  19108. \end{figure}
  19109. \begin{figure}[tbp]
  19110. \begin{tcolorbox}[colback=white]
  19111. \begin{lstlisting}
  19112. (define/public (join t1 t2)
  19113. (match* (t1 t2)
  19114. [('Integer 'Integer) 'Integer]
  19115. [('Boolean 'Boolean) 'Boolean]
  19116. [('Void 'Void) 'Void]
  19117. [('Any t2) t2]
  19118. [(t1 'Any) t1]
  19119. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19120. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19121. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19122. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19123. -> ,(join rt1 rt2))]))
  19124. (define/public (meet t1 t2)
  19125. (match* (t1 t2)
  19126. [('Integer 'Integer) 'Integer]
  19127. [('Boolean 'Boolean) 'Boolean]
  19128. [('Void 'Void) 'Void]
  19129. [('Any t2) 'Any]
  19130. [(t1 'Any) 'Any]
  19131. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19132. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19133. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19134. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19135. -> ,(meet rt1 rt2))]))
  19136. (define/public (check-consistent? t1 t2 e)
  19137. (unless (consistent? t1 t2)
  19138. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19139. (define explicit-prim-ops
  19140. (set-union
  19141. (type-predicates)
  19142. (set 'procedure-arity 'eq? 'not 'and 'or
  19143. 'vector 'vector-length 'vector-ref 'vector-set!
  19144. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19145. (define/override (fun-def-type d)
  19146. (match d
  19147. [(Def f params rt info body)
  19148. (define ps
  19149. (for/list ([p params])
  19150. (match p
  19151. [`[,x : ,T] T]
  19152. [(? symbol?) 'Any]
  19153. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19154. `(,@ps -> ,rt)]
  19155. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19156. \end{lstlisting}
  19157. \end{tcolorbox}
  19158. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19159. \label{fig:type-check-Lgradual-aux}
  19160. \end{figure}
  19161. \fi}
  19162. \clearpage
  19163. \section{Interpreting \LangCast{}}
  19164. \label{sec:interp-casts}
  19165. The runtime behavior of casts involving simple types such as
  19166. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19167. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19168. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19169. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19170. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19171. operator, by checking the value's tag and either retrieving
  19172. the underlying integer or signaling an error if the tag is not the
  19173. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19174. %
  19175. Things get more interesting with casts involving
  19176. \racket{function and tuple types}\python{function, tuple, and array types}.
  19177. Consider the cast of the function \code{maybe\_inc} from
  19178. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19179. to
  19180. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19181. shown in figure~\ref{fig:map-maybe_inc}.
  19182. When the \code{maybe\_inc} function flows through
  19183. this cast at runtime, we don't know whether it will return
  19184. an integer, because that depends on the input from the user.
  19185. The \LangCast{} interpreter therefore delays the checking
  19186. of the cast until the function is applied. To do so it
  19187. wraps \code{maybe\_inc} in a new function that casts its parameter
  19188. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19189. casts the return value from \CANYTY{} to \INTTY{}.
  19190. {\if\edition\pythonEd\pythonColor
  19191. %
  19192. There are further complications regarding casts on mutable data
  19193. such as the \code{list} type introduced in
  19194. the challenge assignment of section~\ref{sec:arrays}.
  19195. %
  19196. \fi}
  19197. %
  19198. Consider the example presented in figure~\ref{fig:map-bang} that
  19199. defines a partially typed version of \code{map} whose parameter
  19200. \code{v} has type
  19201. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19202. and that updates \code{v} in place
  19203. instead of returning a new tuple. We name this function
  19204. \code{map\_inplace}. We apply \code{map\_inplace} to
  19205. \racket{a tuple}\python{an array} of integers, so the type checker
  19206. inserts a cast from
  19207. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19208. to
  19209. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19210. A naive way for the \LangCast{} interpreter to cast between
  19211. \racket{tuple}\python{array} types would be to build a new
  19212. \racket{tuple}\python{array} whose elements are the result
  19213. of casting each of the original elements to the appropriate target
  19214. type. However, this approach is not valid for mutable data structures.
  19215. In the example of figure~\ref{fig:map-bang},
  19216. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19217. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19218. the original one.
  19219. \begin{figure}[tbp]
  19220. \begin{tcolorbox}[colback=white]
  19221. % gradual_test_11.rkt
  19222. {\if\edition\racketEd
  19223. \begin{lstlisting}
  19224. (define (map_inplace [f : (Any -> Any)]
  19225. [v : (Vector Any Any)]) : Void
  19226. (begin
  19227. (vector-set! v 0 (f (vector-ref v 0)))
  19228. (vector-set! v 1 (f (vector-ref v 1)))))
  19229. (define (inc x) (+ x 1))
  19230. (let ([v (vector 0 41)])
  19231. (begin (map_inplace inc v) (vector-ref v 1)))
  19232. \end{lstlisting}
  19233. \fi}
  19234. {\if\edition\pythonEd\pythonColor
  19235. \begin{lstlisting}
  19236. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19237. i = 0
  19238. while i != len(v):
  19239. v[i] = f(v[i])
  19240. i = i + 1
  19241. def inc(x : int) -> int:
  19242. return x + 1
  19243. v = [0, 41]
  19244. map_inplace(inc, v)
  19245. print( v[1] )
  19246. \end{lstlisting}
  19247. \fi}
  19248. \end{tcolorbox}
  19249. \caption{An example involving casts on arrays.}
  19250. \label{fig:map-bang}
  19251. \end{figure}
  19252. Instead the interpreter needs to create a new kind of value, a
  19253. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19254. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19255. and then applies a
  19256. cast to the resulting value. On a write, the proxy casts the argument
  19257. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19258. \racket{
  19259. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19260. \code{0} from \INTTY{} to \CANYTY{}.
  19261. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19262. from \CANYTY{} to \INTTY{}.
  19263. }
  19264. \python{
  19265. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19266. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19267. For the subscript on the left of the assignment,
  19268. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19269. }
  19270. Finally we consider casts between the \CANYTY{} type and higher-order types
  19271. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19272. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19273. have a type annotation, so it is given type \CANYTY{}. In the call to
  19274. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19275. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19276. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19277. \code{Inject}, but that doesn't work because
  19278. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19279. a flat type. Instead, we must first cast to
  19280. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19281. and then inject to \CANYTY{}.
  19282. \begin{figure}[tbp]
  19283. \begin{tcolorbox}[colback=white]
  19284. {\if\edition\racketEd
  19285. \begin{lstlisting}
  19286. (define (map_inplace [f : (Any -> Any)] v) : Void
  19287. (begin
  19288. (vector-set! v 0 (f (vector-ref v 0)))
  19289. (vector-set! v 1 (f (vector-ref v 1)))))
  19290. (define (inc x) (+ x 1))
  19291. (let ([v (vector 0 41)])
  19292. (begin (map_inplace inc v) (vector-ref v 1)))
  19293. \end{lstlisting}
  19294. \fi}
  19295. {\if\edition\pythonEd\pythonColor
  19296. \begin{lstlisting}
  19297. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19298. i = 0
  19299. while i != len(v):
  19300. v[i] = f(v[i])
  19301. i = i + 1
  19302. def inc(x):
  19303. return x + 1
  19304. v = [0, 41]
  19305. map_inplace(inc, v)
  19306. print( v[1] )
  19307. \end{lstlisting}
  19308. \fi}
  19309. \end{tcolorbox}
  19310. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19311. \label{fig:map-any}
  19312. \end{figure}
  19313. \begin{figure}[tbp]
  19314. \begin{tcolorbox}[colback=white]
  19315. {\if\edition\racketEd
  19316. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19317. (define/public (apply_cast v s t)
  19318. (match* (s t)
  19319. [(t1 t2) #:when (equal? t1 t2) v]
  19320. [('Any t2)
  19321. (match t2
  19322. [`(,ts ... -> ,rt)
  19323. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19324. (define v^ (apply-project v any->any))
  19325. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19326. [`(Vector ,ts ...)
  19327. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19328. (define v^ (apply-project v vec-any))
  19329. (apply_cast v^ vec-any `(Vector ,@ts))]
  19330. [else (apply-project v t2)])]
  19331. [(t1 'Any)
  19332. (match t1
  19333. [`(,ts ... -> ,rt)
  19334. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19335. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19336. (apply-inject v^ (any-tag any->any))]
  19337. [`(Vector ,ts ...)
  19338. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19339. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19340. (apply-inject v^ (any-tag vec-any))]
  19341. [else (apply-inject v (any-tag t1))])]
  19342. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19343. (define x (gensym 'x))
  19344. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19345. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19346. (define cast-writes
  19347. (for/list ([t1 ts1] [t2 ts2])
  19348. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19349. `(vector-proxy ,(vector v (apply vector cast-reads)
  19350. (apply vector cast-writes)))]
  19351. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19352. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19353. `(function ,xs ,(Cast
  19354. (Apply (Value v)
  19355. (for/list ([x xs][t1 ts1][t2 ts2])
  19356. (Cast (Var x) t2 t1)))
  19357. rt1 rt2) ())]
  19358. ))
  19359. \end{lstlisting}
  19360. \fi}
  19361. {\if\edition\pythonEd\pythonColor
  19362. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19363. def apply_cast(self, value, src, tgt):
  19364. match (src, tgt):
  19365. case (AnyType(), FunctionType(ps2, rt2)):
  19366. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19367. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19368. case (AnyType(), TupleType(ts2)):
  19369. anytup = TupleType([AnyType() for t1 in ts2])
  19370. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19371. case (AnyType(), ListType(t2)):
  19372. anylist = ListType([AnyType() for t1 in ts2])
  19373. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19374. case (AnyType(), AnyType()):
  19375. return value
  19376. case (AnyType(), _):
  19377. return self.apply_project(value, tgt)
  19378. case (FunctionType(ps1,rt1), AnyType()):
  19379. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19380. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19381. case (TupleType(ts1), AnyType()):
  19382. anytup = TupleType([AnyType() for t1 in ts1])
  19383. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19384. case (ListType(t1), AnyType()):
  19385. anylist = ListType(AnyType())
  19386. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19387. case (_, AnyType()):
  19388. return self.apply_inject(value, src)
  19389. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19390. params = [generate_name('x') for p in ps2]
  19391. args = [Cast(Name(x), t2, t1)
  19392. for (x,t1,t2) in zip(params, ps1, ps2)]
  19393. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19394. return Function('cast', params, [Return(body)], {})
  19395. case (TupleType(ts1), TupleType(ts2)):
  19396. x = generate_name('x')
  19397. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19398. for (t1,t2) in zip(ts1,ts2)]
  19399. return ProxiedTuple(value, reads)
  19400. case (ListType(t1), ListType(t2)):
  19401. x = generate_name('x')
  19402. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19403. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19404. return ProxiedList(value, read, write)
  19405. case (t1, t2) if t1 == t2:
  19406. return value
  19407. case (t1, t2):
  19408. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19409. def apply_inject(self, value, src):
  19410. return Tagged(value, self.type_to_tag(src))
  19411. def apply_project(self, value, tgt):
  19412. match value:
  19413. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19414. return val
  19415. case _:
  19416. raise Exception('apply_project, unexpected ' + repr(value))
  19417. \end{lstlisting}
  19418. \fi}
  19419. \end{tcolorbox}
  19420. \caption{The \code{apply\_cast} auxiliary method.}
  19421. \label{fig:apply_cast}
  19422. \end{figure}
  19423. The \LangCast{} interpreter uses an auxiliary function named
  19424. \code{apply\_cast} to cast a value from a source type to a target type,
  19425. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19426. the kinds of casts that we've discussed in this section.
  19427. %
  19428. The definition of the interpreter for \LangCast{} is shown in
  19429. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19430. dispatching to \code{apply\_cast}.
  19431. \racket{To handle the addition of tuple
  19432. proxies, we update the tuple primitives in \code{interp-op} using the
  19433. functions given in figure~\ref{fig:guarded-tuple}.}
  19434. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19435. \begin{figure}[tbp]
  19436. \begin{tcolorbox}[colback=white]
  19437. {\if\edition\racketEd
  19438. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19439. (define interp-Lcast-class
  19440. (class interp-Llambda-class
  19441. (super-new)
  19442. (inherit apply-fun apply-inject apply-project)
  19443. (define/override (interp-op op)
  19444. (match op
  19445. ['vector-length guarded-vector-length]
  19446. ['vector-ref guarded-vector-ref]
  19447. ['vector-set! guarded-vector-set!]
  19448. ['any-vector-ref (lambda (v i)
  19449. (match v [`(tagged ,v^ ,tg)
  19450. (guarded-vector-ref v^ i)]))]
  19451. ['any-vector-set! (lambda (v i a)
  19452. (match v [`(tagged ,v^ ,tg)
  19453. (guarded-vector-set! v^ i a)]))]
  19454. ['any-vector-length (lambda (v)
  19455. (match v [`(tagged ,v^ ,tg)
  19456. (guarded-vector-length v^)]))]
  19457. [else (super interp-op op)]
  19458. ))
  19459. (define/override ((interp-exp env) e)
  19460. (define (recur e) ((interp-exp env) e))
  19461. (match e
  19462. [(Value v) v]
  19463. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19464. [else ((super interp-exp env) e)]))
  19465. ))
  19466. (define (interp-Lcast p)
  19467. (send (new interp-Lcast-class) interp-program p))
  19468. \end{lstlisting}
  19469. \fi}
  19470. {\if\edition\pythonEd\pythonColor
  19471. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19472. class InterpLcast(InterpLany):
  19473. def interp_exp(self, e, env):
  19474. match e:
  19475. case Cast(value, src, tgt):
  19476. v = self.interp_exp(value, env)
  19477. return self.apply_cast(v, src, tgt)
  19478. case ValueExp(value):
  19479. return value
  19480. ...
  19481. case _:
  19482. return super().interp_exp(e, env)
  19483. \end{lstlisting}
  19484. \fi}
  19485. \end{tcolorbox}
  19486. \caption{The interpreter for \LangCast{}.}
  19487. \label{fig:interp-Lcast}
  19488. \end{figure}
  19489. {\if\edition\racketEd
  19490. \begin{figure}[tbp]
  19491. \begin{tcolorbox}[colback=white]
  19492. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19493. (define (guarded-vector-ref vec i)
  19494. (match vec
  19495. [`(vector-proxy ,proxy)
  19496. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19497. (define rd (vector-ref (vector-ref proxy 1) i))
  19498. (apply-fun rd (list val) 'guarded-vector-ref)]
  19499. [else (vector-ref vec i)]))
  19500. (define (guarded-vector-set! vec i arg)
  19501. (match vec
  19502. [`(vector-proxy ,proxy)
  19503. (define wr (vector-ref (vector-ref proxy 2) i))
  19504. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19505. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19506. [else (vector-set! vec i arg)]))
  19507. (define (guarded-vector-length vec)
  19508. (match vec
  19509. [`(vector-proxy ,proxy)
  19510. (guarded-vector-length (vector-ref proxy 0))]
  19511. [else (vector-length vec)]))
  19512. \end{lstlisting}
  19513. %% {\if\edition\pythonEd\pythonColor
  19514. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19515. %% UNDER CONSTRUCTION
  19516. %% \end{lstlisting}
  19517. %% \fi}
  19518. \end{tcolorbox}
  19519. \caption{The \code{guarded-vector} auxiliary functions.}
  19520. \label{fig:guarded-tuple}
  19521. \end{figure}
  19522. \fi}
  19523. {\if\edition\pythonEd\pythonColor
  19524. \section{Overload Resolution}
  19525. \label{sec:gradual-resolution}
  19526. Recall that when we added support for arrays in
  19527. section~\ref{sec:arrays}, the syntax for the array operations were the
  19528. same as for tuple operations (for example, accessing an element, getting the
  19529. length). So we performed overload resolution, with a pass named
  19530. \code{resolve}, to separate the array and tuple operations. In
  19531. particular, we introduced the primitives \code{array\_load},
  19532. \code{array\_store}, and \code{array\_len}.
  19533. For gradual typing, we further overload these operators to work on
  19534. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19535. updated with new cases for the \CANYTY{} type, translating the element
  19536. access and length operations to the primitives \code{any\_load},
  19537. \code{any\_store}, and \code{any\_len}.
  19538. \fi}
  19539. \section{Cast Insertion}
  19540. \label{sec:gradual-insert-casts}
  19541. In our discussion of type checking of \LangGrad{}, we mentioned how
  19542. the runtime aspect of type checking is carried out by the \code{Cast}
  19543. AST node, which is added to the program by a new pass named
  19544. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19545. language. We now discuss the details of this pass.
  19546. The \code{cast\_insert} pass is closely related to the type checker
  19547. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19548. In particular, the type checker allows implicit casts between
  19549. consistent types. The job of the \code{cast\_insert} pass is to make
  19550. those casts explicit. It does so by inserting
  19551. \code{Cast} nodes into the AST.
  19552. %
  19553. For the most part, the implicit casts occur in places where the type
  19554. checker checks two types for consistency. Consider the case for
  19555. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19556. checker requires that the type of the left operand is consistent with
  19557. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19558. \code{Cast} around the left operand, converting from its type to
  19559. \INTTY{}. The story is similar for the right operand. It is not always
  19560. necessary to insert a cast, for example, if the left operand already has type
  19561. \INTTY{} then there is no need for a \code{Cast}.
  19562. Some of the implicit casts are not as straightforward. One such case
  19563. arises with the
  19564. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19565. see that the type checker requires that the two branches have
  19566. consistent types and that type of the conditional expression is the
  19567. meet of the branches' types. In the target language \LangCast{}, both
  19568. branches will need to have the same type, and that type
  19569. will be the type of the conditional expression. Thus, each branch requires
  19570. a \code{Cast} to convert from its type to the meet of the branches' types.
  19571. The case for the function call exhibits another interesting situation. If
  19572. the function expression is of type \CANYTY{}, then it needs to be cast
  19573. to a function type so that it can be used in a function call in
  19574. \LangCast{}. Which function type should it be cast to? The parameter
  19575. and return types are unknown, so we can simply use \CANYTY{} for all
  19576. of them. Furthermore, in \LangCast{} the argument types will need to
  19577. exactly match the parameter types, so we must cast all the arguments
  19578. to type \CANYTY{} (if they are not already of that type).
  19579. {\if\edition\racketEd
  19580. %
  19581. Likewise, the cases for the tuple operators \code{vector-length},
  19582. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19583. where the tuple expression is of type \CANYTY{}. Instead of
  19584. handling these situations with casts, we recommend translating
  19585. the special-purpose variants of the tuple operators that handle
  19586. tuples of type \CANYTY{}: \code{any-vector-length},
  19587. \code{any-vector-ref}, and \code{any-vector-set!}.
  19588. %
  19589. \fi}
  19590. \section{Lower Casts}
  19591. \label{sec:lower_casts}
  19592. The next step in the journey toward x86 is the \code{lower\_casts}
  19593. pass that translates the casts in \LangCast{} to the lower-level
  19594. \code{Inject} and \code{Project} operators and new operators for
  19595. proxies, extending the \LangLam{} language to \LangProxy{}.
  19596. The \LangProxy{} language can also be described as an extension of
  19597. \LangAny{}, with the addition of proxies. We recommend creating an
  19598. auxiliary function named \code{lower\_cast} that takes an expression
  19599. (in \LangCast{}), a source type, and a target type and translates it
  19600. to an expression in \LangProxy{}.
  19601. The \code{lower\_cast} function can follow a code structure similar to
  19602. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19603. the interpreter for \LangCast{}, because it must handle the same cases
  19604. as \code{apply\_cast} and it needs to mimic the behavior of
  19605. \code{apply\_cast}. The most interesting cases concern
  19606. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19607. {\if\edition\racketEd
  19608. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19609. type to another tuple type is accomplished by creating a proxy that
  19610. intercepts the operations on the underlying tuple. Here we make the
  19611. creation of the proxy explicit with the \code{vector-proxy} AST
  19612. node. It takes three arguments: the first is an expression for the
  19613. tuple, the second is a tuple of functions for casting an element that is
  19614. being read from the tuple, and the third is a tuple of functions for
  19615. casting an element that is being written to the array. You can create
  19616. the functions for reading and writing using lambda expressions. Also,
  19617. as we show in the next section, we need to differentiate these tuples
  19618. of functions from the user-created ones, so we recommend using a new
  19619. AST node named \code{raw-vector} instead of \code{vector}.
  19620. %
  19621. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19622. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19623. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19624. \fi}
  19625. {\if\edition\pythonEd\pythonColor
  19626. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19627. type to another array type is accomplished by creating a proxy that
  19628. intercepts the operations on the underlying array. Here we make the
  19629. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19630. takes fives arguments: the first is an expression for the array, the
  19631. second is a function for casting an element that is being read from
  19632. the array, the third is a function for casting an element that is
  19633. being written to the array, the fourth is the type of the underlying
  19634. array, and the fifth is the type of the proxied array. You can create
  19635. the functions for reading and writing using lambda expressions.
  19636. A cast between two tuple types can be handled in a similar manner. We
  19637. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19638. immutable, so there is no need for a function to cast the value during
  19639. a write. Because there is a separate element type for each slot in
  19640. the tuple, we need not just one function for casting during a read,
  19641. but instead a tuple of functions.
  19642. %
  19643. Also, as we show in the next section, we need to differentiate these
  19644. tuples from the user-created ones, so we recommend using a new AST
  19645. node named \code{RawTuple} instead of \code{Tuple} to create the
  19646. tuples of functions.
  19647. %
  19648. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19649. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19650. that involved casting an array of integers to an array of \CANYTY{}.
  19651. \fi}
  19652. \begin{figure}[tbp]
  19653. \begin{tcolorbox}[colback=white]
  19654. {\if\edition\racketEd
  19655. \begin{lstlisting}
  19656. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19657. (begin
  19658. (vector-set! v 0 (f (vector-ref v 0)))
  19659. (vector-set! v 1 (f (vector-ref v 1)))))
  19660. (define (inc [x : Any]) : Any
  19661. (inject (+ (project x Integer) 1) Integer))
  19662. (let ([v (vector 0 41)])
  19663. (begin
  19664. (map_inplace inc (vector-proxy v
  19665. (raw-vector (lambda: ([x9 : Integer]) : Any
  19666. (inject x9 Integer))
  19667. (lambda: ([x9 : Integer]) : Any
  19668. (inject x9 Integer)))
  19669. (raw-vector (lambda: ([x9 : Any]) : Integer
  19670. (project x9 Integer))
  19671. (lambda: ([x9 : Any]) : Integer
  19672. (project x9 Integer)))))
  19673. (vector-ref v 1)))
  19674. \end{lstlisting}
  19675. \fi}
  19676. {\if\edition\pythonEd\pythonColor
  19677. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19678. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19679. i = 0
  19680. while i != array_len(v):
  19681. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19682. i = (i + 1)
  19683. def inc(x : int) -> int:
  19684. return (x + 1)
  19685. def main() -> int:
  19686. v = [0, 41]
  19687. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19688. print(array_load(v, 1))
  19689. return 0
  19690. \end{lstlisting}
  19691. \fi}
  19692. \end{tcolorbox}
  19693. \caption{Output of \code{lower\_casts} on the example shown in
  19694. figure~\ref{fig:map-bang}.}
  19695. \label{fig:map-bang-lower-cast}
  19696. \end{figure}
  19697. A cast from one function type to another function type is accomplished
  19698. by generating a \code{lambda} whose parameter and return types match
  19699. the target function type. The body of the \code{lambda} should cast
  19700. the parameters from the target type to the source type. (Yes,
  19701. backward! Functions are contravariant\index{subject}{contravariant}
  19702. in the parameters.) Afterward, call the underlying function and then
  19703. cast the result from the source return type to the target return type.
  19704. Figure~\ref{fig:map-lower-cast} shows the output of the
  19705. \code{lower\_casts} pass on the \code{map} example give in
  19706. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19707. call to \code{map} is wrapped in a \code{lambda}.
  19708. \begin{figure}[tbp]
  19709. \begin{tcolorbox}[colback=white]
  19710. {\if\edition\racketEd
  19711. \begin{lstlisting}
  19712. (define (map [f : (Integer -> Integer)]
  19713. [v : (Vector Integer Integer)])
  19714. : (Vector Integer Integer)
  19715. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19716. (define (inc [x : Any]) : Any
  19717. (inject (+ (project x Integer) 1) Integer))
  19718. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19719. (project (inc (inject x9 Integer)) Integer))
  19720. (vector 0 41)) 1)
  19721. \end{lstlisting}
  19722. \fi}
  19723. {\if\edition\pythonEd\pythonColor
  19724. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19725. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19726. return (f(v[0]), f(v[1]),)
  19727. def inc(x : any) -> any:
  19728. return inject((project(x, int) + 1), int)
  19729. def main() -> int:
  19730. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19731. print(t[1])
  19732. return 0
  19733. \end{lstlisting}
  19734. \fi}
  19735. \end{tcolorbox}
  19736. \caption{Output of \code{lower\_casts} on the example shown in
  19737. figure~\ref{fig:gradual-map}.}
  19738. \label{fig:map-lower-cast}
  19739. \end{figure}
  19740. \section{Differentiate Proxies}
  19741. \label{sec:differentiate-proxies}
  19742. So far, the responsibility of differentiating tuples and tuple proxies
  19743. has been the job of the interpreter.
  19744. %
  19745. \racket{For example, the interpreter for \LangCast{} implements
  19746. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19747. figure~\ref{fig:guarded-tuple}.}
  19748. %
  19749. In the \code{differentiate\_proxies} pass we shift this responsibility
  19750. to the generated code.
  19751. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19752. we used the type \TUPLETYPENAME{} for both
  19753. real tuples and tuple proxies.
  19754. \python{Similarly, we use the type \code{list} for both arrays and
  19755. array proxies.}
  19756. In \LangPVec{} we return the
  19757. \TUPLETYPENAME{} type to its original
  19758. meaning, as the type of just tuples, and we introduce a new type,
  19759. \PTUPLETYNAME{}, whose values
  19760. can be either real tuples or tuple
  19761. proxies.
  19762. %
  19763. {\if\edition\pythonEd\pythonColor
  19764. Likewise, we return the
  19765. \ARRAYTYPENAME{} type to its original
  19766. meaning, as the type of arrays, and we introduce a new type,
  19767. \PARRAYTYNAME{}, whose values
  19768. can be either arrays or array proxies.
  19769. These new types come with a suite of new primitive operations.
  19770. \fi}
  19771. {\if\edition\racketEd
  19772. A tuple proxy is represented by a tuple containing three things: (1) the
  19773. underlying tuple, (2) a tuple of functions for casting elements that
  19774. are read from the tuple, and (3) a tuple of functions for casting
  19775. values to be written to the tuple. So, we define the following
  19776. abbreviation for the type of a tuple proxy:
  19777. \[
  19778. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19779. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19780. \]
  19781. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19782. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19783. %
  19784. Next we describe each of the new primitive operations.
  19785. \begin{description}
  19786. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19787. (\key{PVector} $T \ldots$)]\ \\
  19788. %
  19789. This operation brands a vector as a value of the \code{PVector} type.
  19790. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19791. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19792. %
  19793. This operation brands a vector proxy as value of the \code{PVector} type.
  19794. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19795. \BOOLTY{}] \ \\
  19796. %
  19797. This returns true if the value is a tuple proxy and false if it is a
  19798. real tuple.
  19799. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  19800. (\key{Vector} $T \ldots$)]\ \\
  19801. %
  19802. Assuming that the input is a tuple, this operation returns the
  19803. tuple.
  19804. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  19805. $\to$ \BOOLTY{}]\ \\
  19806. %
  19807. Given a tuple proxy, this operation returns the length of the tuple.
  19808. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  19809. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  19810. %
  19811. Given a tuple proxy, this operation returns the $i$th element of the
  19812. tuple.
  19813. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  19814. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  19815. Given a tuple proxy, this operation writes a value to the $i$th element
  19816. of the tuple.
  19817. \end{description}
  19818. \fi}
  19819. {\if\edition\pythonEd\pythonColor
  19820. %
  19821. A tuple proxy is represented by a tuple containing 1) the underlying
  19822. tuple and 2) a tuple of functions for casting elements that are read
  19823. from the tuple. The \LangPVec{} language includes the following AST
  19824. classes and primitive functions.
  19825. \begin{description}
  19826. \item[\code{InjectTuple}] \ \\
  19827. %
  19828. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  19829. \item[\code{InjectTupleProxy}]\ \\
  19830. %
  19831. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  19832. \item[\code{is\_tuple\_proxy}]\ \\
  19833. %
  19834. This primitive returns true if the value is a tuple proxy and false
  19835. if it is a tuple.
  19836. \item[\code{project\_tuple}]\ \\
  19837. %
  19838. Converts a tuple that is branded as \PTUPLETYNAME{}
  19839. back to a tuple.
  19840. \item[\code{proxy\_tuple\_len}]\ \\
  19841. %
  19842. Given a tuple proxy, returns the length of the underlying tuple.
  19843. \item[\code{proxy\_tuple\_load}]\ \\
  19844. %
  19845. Given a tuple proxy, returns the $i$th element of the underlying
  19846. tuple.
  19847. \end{description}
  19848. An array proxy is represented by a tuple containing 1) the underlying
  19849. array, 2) a function for casting elements that are read from the
  19850. array, and 3) a function for casting elements that are written to the
  19851. array. The \LangPVec{} language includes the following AST classes
  19852. and primitive functions.
  19853. \begin{description}
  19854. \item[\code{InjectList}]\ \\
  19855. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  19856. \item[\code{InjectListProxy}]\ \\
  19857. %
  19858. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  19859. \item[\code{is\_array\_proxy}]\ \\
  19860. %
  19861. Returns true if the value is a array proxy and false if it is an
  19862. array.
  19863. \item[\code{project\_array}]\ \\
  19864. %
  19865. Converts an array that is branded as \PARRAYTYNAME{} back to an
  19866. array.
  19867. \item[\code{proxy\_array\_len}]\ \\
  19868. %
  19869. Given a array proxy, returns the length of the underlying array.
  19870. \item[\code{proxy\_array\_load}]\ \\
  19871. %
  19872. Given a array proxy, returns the $i$th element of the underlying
  19873. array.
  19874. \item[\code{proxy\_array\_store}]\ \\
  19875. %
  19876. Given an array proxy, writes a value to the $i$th element of the
  19877. underlying array.
  19878. \end{description}
  19879. \fi}
  19880. Now we discuss the translation that differentiates tuples and arrays
  19881. from proxies. First, every type annotation in the program is
  19882. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  19883. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  19884. places. For example, we wrap every tuple creation with an
  19885. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  19886. %
  19887. {\if\edition\racketEd
  19888. \begin{minipage}{0.96\textwidth}
  19889. \begin{lstlisting}
  19890. (vector |$e_1 \ldots e_n$|)
  19891. |$\Rightarrow$|
  19892. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  19893. \end{lstlisting}
  19894. \end{minipage}
  19895. \fi}
  19896. {\if\edition\pythonEd\pythonColor
  19897. \begin{lstlisting}
  19898. Tuple(|$e_1, \ldots, e_n$|)
  19899. |$\Rightarrow$|
  19900. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  19901. \end{lstlisting}
  19902. \fi}
  19903. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  19904. AST node that we introduced in the previous
  19905. section does not get injected.
  19906. {\if\edition\racketEd
  19907. \begin{lstlisting}
  19908. (raw-vector |$e_1 \ldots e_n$|)
  19909. |$\Rightarrow$|
  19910. (vector |$e'_1 \ldots e'_n$|)
  19911. \end{lstlisting}
  19912. \fi}
  19913. {\if\edition\pythonEd\pythonColor
  19914. \begin{lstlisting}
  19915. RawTuple(|$e_1, \ldots, e_n$|)
  19916. |$\Rightarrow$|
  19917. Tuple(|$e'_1, \ldots, e'_n$|)
  19918. \end{lstlisting}
  19919. \fi}
  19920. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  19921. translates as follows:
  19922. %
  19923. {\if\edition\racketEd
  19924. \begin{lstlisting}
  19925. (vector-proxy |$e_1~e_2~e_3$|)
  19926. |$\Rightarrow$|
  19927. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  19928. \end{lstlisting}
  19929. \fi}
  19930. {\if\edition\pythonEd\pythonColor
  19931. \begin{lstlisting}
  19932. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  19933. |$\Rightarrow$|
  19934. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  19935. \end{lstlisting}
  19936. \fi}
  19937. We translate the element access operations into conditional
  19938. expressions that check whether the value is a proxy and then dispatch
  19939. to either the appropriate proxy tuple operation or the regular tuple
  19940. operation.
  19941. {\if\edition\racketEd
  19942. \begin{lstlisting}
  19943. (vector-ref |$e_1$| |$i$|)
  19944. |$\Rightarrow$|
  19945. (let ([|$v~e_1$|])
  19946. (if (proxy? |$v$|)
  19947. (proxy-vector-ref |$v$| |$i$|)
  19948. (vector-ref (project-vector |$v$|) |$i$|)
  19949. \end{lstlisting}
  19950. \fi}
  19951. %
  19952. Note that in the branch for a tuple, we must apply
  19953. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  19954. from the tuple.
  19955. The translation of array operations is similar to the ones for tuples.
  19956. \section{Reveal Casts}
  19957. \label{sec:reveal-casts-gradual}
  19958. {\if\edition\racketEd
  19959. Recall that the \code{reveal\_casts} pass
  19960. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  19961. \code{Inject} and \code{Project} into lower-level operations.
  19962. %
  19963. In particular, \code{Project} turns into a conditional expression that
  19964. inspects the tag and retrieves the underlying value. Here we need to
  19965. augment the translation of \code{Project} to handle the situation in which
  19966. the target type is \code{PVector}. Instead of using
  19967. \code{vector-length} we need to use \code{proxy-vector-length}.
  19968. \begin{lstlisting}
  19969. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  19970. |$\Rightarrow$|
  19971. (let |$\itm{tmp}$| |$e'$|
  19972. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  19973. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  19974. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  19975. (exit)))
  19976. \end{lstlisting}
  19977. \fi}
  19978. %
  19979. {\if\edition\pythonEd\pythonColor
  19980. Recall that the $\itm{tagof}$ function determines the bits used to
  19981. identify values of different types and it is used in the \code{reveal\_casts}
  19982. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  19983. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  19984. decimal), just like the tuple and array types.
  19985. \fi}
  19986. %
  19987. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  19988. \section{Closure Conversion}
  19989. \label{sec:closure-conversion-gradual}
  19990. The auxiliary function that translates type annotations needs to be
  19991. updated to handle the \PTUPLETYNAME{}
  19992. \racket{type}\python{and \PARRAYTYNAME{} types}.
  19993. %
  19994. Otherwise, the only other changes are adding cases that copy the new
  19995. AST nodes.
  19996. \section{Select Instructions}
  19997. \label{sec:select-instructions-gradual}
  19998. \index{subject}{select instructions}
  19999. Recall that the \code{select\_instructions} pass is responsible for
  20000. lowering the primitive operations into x86 instructions. So, we need
  20001. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20002. to x86. To do so, the first question we need to answer is how to
  20003. differentiate between tuple and tuple proxies\python{, and likewise for
  20004. arrays and array proxies}. We need just one bit to accomplish this;
  20005. we use the bit in position $63$ of the 64-bit tag at the front of
  20006. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20007. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20008. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20009. it that way.
  20010. {\if\edition\racketEd
  20011. \begin{lstlisting}
  20012. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20013. |$\Rightarrow$|
  20014. movq |$e'_1$|, |$\itm{lhs'}$|
  20015. \end{lstlisting}
  20016. \fi}
  20017. {\if\edition\pythonEd\pythonColor
  20018. \begin{lstlisting}
  20019. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20020. |$\Rightarrow$|
  20021. movq |$e'_1$|, |$\itm{lhs'}$|
  20022. \end{lstlisting}
  20023. \fi}
  20024. \python{The translation for \code{InjectList} is also a move instruction.}
  20025. \noindent On the other hand,
  20026. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20027. $63$ to $1$.
  20028. %
  20029. {\if\edition\racketEd
  20030. \begin{lstlisting}
  20031. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20032. |$\Rightarrow$|
  20033. movq |$e'_1$|, %r11
  20034. movq |$(1 << 63)$|, %rax
  20035. orq 0(%r11), %rax
  20036. movq %rax, 0(%r11)
  20037. movq %r11, |$\itm{lhs'}$|
  20038. \end{lstlisting}
  20039. \fi}
  20040. {\if\edition\pythonEd\pythonColor
  20041. \begin{lstlisting}
  20042. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20043. |$\Rightarrow$|
  20044. movq |$e'_1$|, %r11
  20045. movq |$(1 << 63)$|, %rax
  20046. orq 0(%r11), %rax
  20047. movq %rax, 0(%r11)
  20048. movq %r11, |$\itm{lhs'}$|
  20049. \end{lstlisting}
  20050. \fi}
  20051. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20052. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20053. The \racket{\code{proxy?} operation consumes}%
  20054. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20055. consume}
  20056. the information so carefully stashed away by the injections. It
  20057. isolates bit $63$ to tell whether the value is a proxy.
  20058. %
  20059. {\if\edition\racketEd
  20060. \begin{lstlisting}
  20061. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20062. |$\Rightarrow$|
  20063. movq |$e_1'$|, %r11
  20064. movq 0(%r11), %rax
  20065. sarq $63, %rax
  20066. andq $1, %rax
  20067. movq %rax, |$\itm{lhs'}$|
  20068. \end{lstlisting}
  20069. \fi}%
  20070. %
  20071. {\if\edition\pythonEd\pythonColor
  20072. \begin{lstlisting}
  20073. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20074. |$\Rightarrow$|
  20075. movq |$e_1'$|, %r11
  20076. movq 0(%r11), %rax
  20077. sarq $63, %rax
  20078. andq $1, %rax
  20079. movq %rax, |$\itm{lhs'}$|
  20080. \end{lstlisting}
  20081. \fi}%
  20082. %
  20083. The \racket{\code{project-vector} operation is}
  20084. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20085. straightforward to translate, so we leave that to the reader.
  20086. Regarding the element access operations for tuples\python{ and arrays}, the
  20087. runtime provides procedures that implement them (they are recursive
  20088. functions!), so here we simply need to translate these tuple
  20089. operations into the appropriate function call. For example, here is
  20090. the translation for
  20091. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20092. {\if\edition\racketEd
  20093. \begin{minipage}{0.96\textwidth}
  20094. \begin{lstlisting}
  20095. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20096. |$\Rightarrow$|
  20097. movq |$e_1'$|, %rdi
  20098. movq |$e_2'$|, %rsi
  20099. callq proxy_vector_ref
  20100. movq %rax, |$\itm{lhs'}$|
  20101. \end{lstlisting}
  20102. \end{minipage}
  20103. \fi}
  20104. {\if\edition\pythonEd\pythonColor
  20105. \begin{lstlisting}
  20106. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20107. |$\Rightarrow$|
  20108. movq |$e_1'$|, %rdi
  20109. movq |$e_2'$|, %rsi
  20110. callq proxy_vector_ref
  20111. movq %rax, |$\itm{lhs'}$|
  20112. \end{lstlisting}
  20113. \fi}
  20114. {\if\edition\pythonEd\pythonColor
  20115. % TODO: revisit the names vecof for python -Jeremy
  20116. We translate
  20117. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20118. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20119. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20120. \fi}
  20121. We have another batch of operations to deal with: those for the
  20122. \CANYTY{} type. Recall that we generate an
  20123. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20124. there is a element access on something of type \CANYTY{}, and
  20125. similarly for
  20126. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20127. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20128. section~\ref{sec:select-Lany} we selected instructions for these
  20129. operations on the basis of the idea that the underlying value was a tuple or
  20130. array. But in the current setting, the underlying value is of type
  20131. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20132. functions to deal with this:
  20133. \code{proxy\_vector\_ref},
  20134. \code{proxy\_vector\_set}, and
  20135. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20136. to determine whether the value is a proxy, and then
  20137. dispatches to the the appropriate code.
  20138. %
  20139. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20140. can be translated as follows.
  20141. We begin by projecting the underlying value out of the tagged value and
  20142. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20143. {\if\edition\racketEd
  20144. \begin{lstlisting}
  20145. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  20146. |$\Rightarrow$|
  20147. movq |$\neg 111$|, %rdi
  20148. andq |$e_1'$|, %rdi
  20149. movq |$e_2'$|, %rsi
  20150. callq proxy_vector_ref
  20151. movq %rax, |$\itm{lhs'}$|
  20152. \end{lstlisting}
  20153. \fi}
  20154. {\if\edition\pythonEd\pythonColor
  20155. \begin{lstlisting}
  20156. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20157. |$\Rightarrow$|
  20158. movq |$\neg 111$|, %rdi
  20159. andq |$e_1'$|, %rdi
  20160. movq |$e_2'$|, %rsi
  20161. callq proxy_vector_ref
  20162. movq %rax, |$\itm{lhs'}$|
  20163. \end{lstlisting}
  20164. \fi}
  20165. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20166. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20167. are translated in a similar way. Alternatively, you could generate
  20168. instructions to open-code
  20169. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20170. and \code{proxy\_vector\_length} functions.
  20171. \begin{exercise}\normalfont\normalsize
  20172. Implement a compiler for the gradually typed \LangGrad{} language by
  20173. extending and adapting your compiler for \LangLam{}. Create ten new
  20174. partially typed test programs. In addition to testing with these
  20175. new programs, test your compiler on all the tests for \LangLam{}
  20176. and for \LangDyn{}.
  20177. %
  20178. \racket{Sometimes you may get a type checking error on the
  20179. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20180. the \CANYTY{} type around each subexpression that has caused a type
  20181. error. Although \LangDyn{} does not have explicit casts, you can
  20182. induce one by wrapping the subexpression \code{e} with a call to
  20183. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20184. %
  20185. \python{Sometimes you may get a type checking error on the
  20186. \LangDyn{} programs but you can adapt them by inserting a
  20187. temporary variable of type \CANYTY{} that is initialized with the
  20188. troublesome expression.}
  20189. \end{exercise}
  20190. \begin{figure}[p]
  20191. \begin{tcolorbox}[colback=white]
  20192. {\if\edition\racketEd
  20193. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20194. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20195. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20196. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20197. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20198. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20199. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20200. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20201. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20202. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20203. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20204. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20205. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20206. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20207. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20208. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20209. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20210. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20211. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20212. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20213. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20214. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20215. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20216. \path[->,bend left=15] (Lgradual) edge [above] node
  20217. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20218. \path[->,bend left=15] (Lgradual2) edge [above] node
  20219. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20220. \path[->,bend left=15] (Lgradual3) edge [above] node
  20221. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20222. \path[->,bend left=15] (Lgradual4) edge [left] node
  20223. {\ttfamily\footnotesize shrink} (Lgradualr);
  20224. \path[->,bend left=15] (Lgradualr) edge [above] node
  20225. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20226. \path[->,bend right=15] (Lgradualp) edge [above] node
  20227. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20228. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20229. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20230. \path[->,bend right=15] (Llambdapp) edge [above] node
  20231. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20232. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20233. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20234. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20235. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20236. \path[->,bend left=15] (F1-2) edge [above] node
  20237. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20238. \path[->,bend left=15] (F1-3) edge [left] node
  20239. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20240. \path[->,bend left=15] (F1-4) edge [below] node
  20241. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20242. \path[->,bend right=15] (F1-5) edge [above] node
  20243. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20244. \path[->,bend right=15] (F1-6) edge [above] node
  20245. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20246. \path[->,bend right=15] (C3-2) edge [right] node
  20247. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20248. \path[->,bend right=15] (x86-2) edge [right] node
  20249. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20250. \path[->,bend right=15] (x86-2-1) edge [below] node
  20251. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20252. \path[->,bend right=15] (x86-2-2) edge [right] node
  20253. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20254. \path[->,bend left=15] (x86-3) edge [above] node
  20255. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20256. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20257. \end{tikzpicture}
  20258. \fi}
  20259. {\if\edition\pythonEd\pythonColor
  20260. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20261. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20262. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20263. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20264. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20265. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20266. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20267. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20268. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20269. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20270. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20271. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20272. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20273. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20274. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20275. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20276. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20277. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20278. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20279. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20280. \path[->,bend left=15] (Lgradual) edge [above] node
  20281. {\ttfamily\footnotesize shrink} (Lgradual2);
  20282. \path[->,bend left=15] (Lgradual2) edge [above] node
  20283. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20284. \path[->,bend left=15] (Lgradual3) edge [above] node
  20285. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20286. \path[->,bend left=15] (Lgradual4) edge [left] node
  20287. {\ttfamily\footnotesize resolve} (Lgradualr);
  20288. \path[->,bend left=15] (Lgradualr) edge [below] node
  20289. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20290. \path[->,bend right=15] (Lgradualp) edge [above] node
  20291. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20292. \path[->,bend right=15] (Llambdapp) edge [above] node
  20293. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20294. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20295. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20296. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20297. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20298. \path[->,bend left=15] (F1-1) edge [above] node
  20299. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20300. \path[->,bend left=15] (F1-2) edge [above] node
  20301. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20302. \path[->,bend left=15] (F1-3) edge [right] node
  20303. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20304. \path[->,bend right=15] (F1-5) edge [above] node
  20305. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20306. \path[->,bend right=15] (F1-6) edge [above] node
  20307. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20308. \path[->,bend right=15] (C3-2) edge [right] node
  20309. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20310. \path[->,bend right=15] (x86-2) edge [below] node
  20311. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20312. \path[->,bend right=15] (x86-3) edge [below] node
  20313. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20314. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20315. \end{tikzpicture}
  20316. \fi}
  20317. \end{tcolorbox}
  20318. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20319. \label{fig:Lgradual-passes}
  20320. \end{figure}
  20321. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20322. needed for the compilation of \LangGrad{}.
  20323. \section{Further Reading}
  20324. This chapter just scratches the surface of gradual typing. The basic
  20325. approach described here is missing two key ingredients that one would
  20326. want in a implementation of gradual typing: blame
  20327. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20328. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20329. problem addressed by blame tracking is that when a cast on a
  20330. higher-order value fails, it often does so at a point in the program
  20331. that is far removed from the original cast. Blame tracking is a
  20332. technique for propagating extra information through casts and proxies
  20333. so that when a cast fails, the error message can point back to the
  20334. original location of the cast in the source program.
  20335. The problem addressed by space-efficient casts also relates to
  20336. higher-order casts. It turns out that in partially typed programs, a
  20337. function or tuple can flow through a great many casts at runtime. With
  20338. the approach described in this chapter, each cast adds another
  20339. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20340. considerable space, but it also makes the function calls and tuple
  20341. operations slow. For example, a partially typed version of quicksort
  20342. could, in the worst case, build a chain of proxies of length $O(n)$
  20343. around the tuple, changing the overall time complexity of the
  20344. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20345. solution to this problem by representing casts using the coercion
  20346. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20347. long chains of proxies by compressing them into a concise normal
  20348. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20349. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20350. the Grift compiler:
  20351. \begin{center}
  20352. \url{https://github.com/Gradual-Typing/Grift}
  20353. \end{center}
  20354. There are also interesting interactions between gradual typing and
  20355. other language features, such as generics, information-flow types, and
  20356. type inference, to name a few. We recommend to the reader the
  20357. online gradual typing bibliography for more material:
  20358. \begin{center}
  20359. \url{http://samth.github.io/gradual-typing-bib/}
  20360. \end{center}
  20361. % TODO: challenge problem:
  20362. % type analysis and type specialization?
  20363. % coercions?
  20364. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20365. \chapter{Generics}
  20366. \label{ch:Lpoly}
  20367. \setcounter{footnote}{0}
  20368. This chapter studies the compilation of
  20369. generics\index{subject}{generics} (aka parametric
  20370. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20371. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20372. enable programmers to make code more reusable by parameterizing
  20373. functions and data structures with respect to the types on which they
  20374. operate. For example, figure~\ref{fig:map-poly} revisits the
  20375. \code{map} example and this time gives it a more fitting type. This
  20376. \code{map} function is parameterized with respect to the element type
  20377. of the tuple. The type of \code{map} is the following generic type
  20378. specified by the \code{All} type with parameter \code{T}:
  20379. {\if\edition\racketEd
  20380. \begin{lstlisting}
  20381. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20382. \end{lstlisting}
  20383. \fi}
  20384. {\if\edition\pythonEd\pythonColor
  20385. \begin{lstlisting}
  20386. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20387. \end{lstlisting}
  20388. \fi}
  20389. %
  20390. The idea is that \code{map} can be used at \emph{all} choices of a
  20391. type for parameter \code{T}. In the example shown in
  20392. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20393. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20394. \code{T}, but we could have just as well applied \code{map} to a tuple
  20395. of Booleans.
  20396. %
  20397. A \emph{monomorphic} function is simply one that is not generic.
  20398. %
  20399. We use the term \emph{instantiation} for the process (within the
  20400. language implementation) of turning a generic function into a
  20401. monomorphic one, where the type parameters have been replaced by
  20402. types.
  20403. {\if\edition\pythonEd\pythonColor
  20404. %
  20405. In Python, when writing a generic function such as \code{map}, one
  20406. does not explicitly write down its generic type (using \code{All}).
  20407. Instead, the fact that it is generic is implied by the use of type
  20408. variables (such as \code{T}) in the type annotations of its
  20409. parameters.
  20410. %
  20411. \fi}
  20412. \begin{figure}[tbp]
  20413. % poly_test_2.rkt
  20414. \begin{tcolorbox}[colback=white]
  20415. {\if\edition\racketEd
  20416. \begin{lstlisting}
  20417. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20418. (define (map f v)
  20419. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20420. (define (inc [x : Integer]) : Integer (+ x 1))
  20421. (vector-ref (map inc (vector 0 41)) 1)
  20422. \end{lstlisting}
  20423. \fi}
  20424. {\if\edition\pythonEd\pythonColor
  20425. \begin{lstlisting}
  20426. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20427. return (f(tup[0]), f(tup[1]))
  20428. def add1(x : int) -> int:
  20429. return x + 1
  20430. t = map(add1, (0, 41))
  20431. print(t[1])
  20432. \end{lstlisting}
  20433. \fi}
  20434. \end{tcolorbox}
  20435. \caption{A generic version of the \code{map} function.}
  20436. \label{fig:map-poly}
  20437. \end{figure}
  20438. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20439. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20440. shows the definition of the abstract syntax.
  20441. %
  20442. {\if\edition\racketEd
  20443. We add a second form for function definitions in which a type
  20444. declaration comes before the \code{define}. In the abstract syntax,
  20445. the return type in the \code{Def} is \CANYTY{}, but that should be
  20446. ignored in favor of the return type in the type declaration. (The
  20447. \CANYTY{} comes from using the same parser as discussed in
  20448. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20449. enables the use of an \code{All} type for a function, thereby making
  20450. it generic.
  20451. \fi}
  20452. %
  20453. The grammar for types is extended to include the type of a generic
  20454. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20455. abstract syntax)}.
  20456. \newcommand{\LpolyGrammarRacket}{
  20457. \begin{array}{lcl}
  20458. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20459. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20460. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20461. \end{array}
  20462. }
  20463. \newcommand{\LpolyASTRacket}{
  20464. \begin{array}{lcl}
  20465. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20466. \Def &::=& \DECL{\Var}{\Type} \\
  20467. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20468. \end{array}
  20469. }
  20470. \newcommand{\LpolyGrammarPython}{
  20471. \begin{array}{lcl}
  20472. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20473. \end{array}
  20474. }
  20475. \newcommand{\LpolyASTPython}{
  20476. \begin{array}{lcl}
  20477. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20478. \MID \key{GenericVar}\LP\Var\RP
  20479. \end{array}
  20480. }
  20481. \begin{figure}[tp]
  20482. \centering
  20483. \begin{tcolorbox}[colback=white]
  20484. \footnotesize
  20485. {\if\edition\racketEd
  20486. \[
  20487. \begin{array}{l}
  20488. \gray{\LintGrammarRacket{}} \\ \hline
  20489. \gray{\LvarGrammarRacket{}} \\ \hline
  20490. \gray{\LifGrammarRacket{}} \\ \hline
  20491. \gray{\LwhileGrammarRacket} \\ \hline
  20492. \gray{\LtupGrammarRacket} \\ \hline
  20493. \gray{\LfunGrammarRacket} \\ \hline
  20494. \gray{\LlambdaGrammarRacket} \\ \hline
  20495. \LpolyGrammarRacket \\
  20496. \begin{array}{lcl}
  20497. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20498. \end{array}
  20499. \end{array}
  20500. \]
  20501. \fi}
  20502. {\if\edition\pythonEd\pythonColor
  20503. \[
  20504. \begin{array}{l}
  20505. \gray{\LintGrammarPython{}} \\ \hline
  20506. \gray{\LvarGrammarPython{}} \\ \hline
  20507. \gray{\LifGrammarPython{}} \\ \hline
  20508. \gray{\LwhileGrammarPython} \\ \hline
  20509. \gray{\LtupGrammarPython} \\ \hline
  20510. \gray{\LfunGrammarPython} \\ \hline
  20511. \gray{\LlambdaGrammarPython} \\\hline
  20512. \LpolyGrammarPython \\
  20513. \begin{array}{lcl}
  20514. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20515. \end{array}
  20516. \end{array}
  20517. \]
  20518. \fi}
  20519. \end{tcolorbox}
  20520. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20521. (figure~\ref{fig:Llam-concrete-syntax}).}
  20522. \label{fig:Lpoly-concrete-syntax}
  20523. \end{figure}
  20524. \begin{figure}[tp]
  20525. \centering
  20526. \begin{tcolorbox}[colback=white]
  20527. \footnotesize
  20528. {\if\edition\racketEd
  20529. \[
  20530. \begin{array}{l}
  20531. \gray{\LintOpAST} \\ \hline
  20532. \gray{\LvarASTRacket{}} \\ \hline
  20533. \gray{\LifASTRacket{}} \\ \hline
  20534. \gray{\LwhileASTRacket{}} \\ \hline
  20535. \gray{\LtupASTRacket{}} \\ \hline
  20536. \gray{\LfunASTRacket} \\ \hline
  20537. \gray{\LlambdaASTRacket} \\ \hline
  20538. \LpolyASTRacket \\
  20539. \begin{array}{lcl}
  20540. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20541. \end{array}
  20542. \end{array}
  20543. \]
  20544. \fi}
  20545. {\if\edition\pythonEd\pythonColor
  20546. \[
  20547. \begin{array}{l}
  20548. \gray{\LintASTPython} \\ \hline
  20549. \gray{\LvarASTPython{}} \\ \hline
  20550. \gray{\LifASTPython{}} \\ \hline
  20551. \gray{\LwhileASTPython{}} \\ \hline
  20552. \gray{\LtupASTPython{}} \\ \hline
  20553. \gray{\LfunASTPython} \\ \hline
  20554. \gray{\LlambdaASTPython} \\ \hline
  20555. \LpolyASTPython \\
  20556. \begin{array}{lcl}
  20557. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20558. \end{array}
  20559. \end{array}
  20560. \]
  20561. \fi}
  20562. \end{tcolorbox}
  20563. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20564. (figure~\ref{fig:Llam-syntax}).}
  20565. \label{fig:Lpoly-syntax}
  20566. \end{figure}
  20567. By including the \code{All} type in the $\Type$ nonterminal of the
  20568. grammar we choose to make generics first class, which has interesting
  20569. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20570. not include syntax for the \code{All} type. It is inferred for functions whose
  20571. type annotations contain type variables.} Many languages with generics, such as
  20572. C++~\citep{stroustrup88:_param_types} and Standard
  20573. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20574. may be helpful to see an example of first-class generics in action. In
  20575. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20576. whose parameter is a generic function. Indeed, because the grammar for
  20577. $\Type$ includes the \code{All} type, a generic function may also be
  20578. returned from a function or stored inside a tuple. The body of
  20579. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20580. and also to an integer, which would not be possible if \code{f} were
  20581. not generic.
  20582. \begin{figure}[tbp]
  20583. \begin{tcolorbox}[colback=white]
  20584. {\if\edition\racketEd
  20585. \begin{lstlisting}
  20586. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20587. (define (apply_twice f)
  20588. (if (f #t) (f 42) (f 777)))
  20589. (: id (All (T) (T -> T)))
  20590. (define (id x) x)
  20591. (apply_twice id)
  20592. \end{lstlisting}
  20593. \fi}
  20594. {\if\edition\pythonEd\pythonColor
  20595. \begin{lstlisting}
  20596. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20597. if f(True):
  20598. return f(42)
  20599. else:
  20600. return f(777)
  20601. def id(x: T) -> T:
  20602. return x
  20603. print(apply_twice(id))
  20604. \end{lstlisting}
  20605. \fi}
  20606. \end{tcolorbox}
  20607. \caption{An example illustrating first-class generics.}
  20608. \label{fig:apply-twice}
  20609. \end{figure}
  20610. The type checker for \LangPoly{} shown in
  20611. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20612. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20613. {\if\edition\pythonEd\pythonColor
  20614. %
  20615. Regarding function definitions, if the type annotations on its
  20616. parameters contain generic variables, then the function is generic and
  20617. therefore its type is an \code{All} type wrapped around a function
  20618. type. Otherwise the function is monomorphic and its type is simply
  20619. a function type.
  20620. %
  20621. \fi}
  20622. The type checking of a function application is extended to handle the
  20623. case in which the operator expression is a generic function. In that case
  20624. the type arguments are deduced by matching the types of the parameters
  20625. with the types of the arguments.
  20626. %
  20627. The \code{match\_types} auxiliary function
  20628. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20629. recursively descending through a parameter type \code{param\_ty} and
  20630. the corresponding argument type \code{arg\_ty}, making sure that they
  20631. are equal except when there is a type parameter in the parameter
  20632. type. Upon encountering a type parameter for the first time, the
  20633. algorithm deduces an association of the type parameter to the
  20634. corresponding part of the argument type. If it is not the first time
  20635. that the type parameter has been encountered, the algorithm looks up
  20636. its deduced type and makes sure that it is equal to the corresponding
  20637. part of the argument type. The return type of the application is the
  20638. return type of the generic function with the type parameters
  20639. replaced by the deduced type arguments, using the
  20640. \code{substitute\_type} auxiliary function, which is also listed in
  20641. figure~\ref{fig:type-check-Lpoly-aux}.
  20642. The type checker extends type equality to handle the \code{All} type.
  20643. This is not quite as simple as for other types, such as function and
  20644. tuple types, because two \code{All} types can be syntactically
  20645. different even though they are equivalent. For example,
  20646. \begin{center}
  20647. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20648. \end{center}
  20649. is equivalent to
  20650. \begin{center}
  20651. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20652. \end{center}
  20653. Two generic types are equal if they differ only in
  20654. the choice of the names of the type parameters. The definition of type
  20655. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20656. parameters in one type to match the type parameters of the other type.
  20657. {\if\edition\racketEd
  20658. %
  20659. The type checker also ensures that only defined type variables appear
  20660. in type annotations. The \code{check\_well\_formed} function for which
  20661. the definition is shown in figure~\ref{fig:well-formed-types}
  20662. recursively inspects a type, making sure that each type variable has
  20663. been defined.
  20664. %
  20665. \fi}
  20666. \begin{figure}[tbp]
  20667. \begin{tcolorbox}[colback=white]
  20668. {\if\edition\racketEd
  20669. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20670. (define type-check-poly-class
  20671. (class type-check-Llambda-class
  20672. (super-new)
  20673. (inherit check-type-equal?)
  20674. (define/override (type-check-apply env e1 es)
  20675. (define-values (e^ ty) ((type-check-exp env) e1))
  20676. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20677. ((type-check-exp env) e)))
  20678. (match ty
  20679. [`(,ty^* ... -> ,rt)
  20680. (for ([arg-ty ty*] [param-ty ty^*])
  20681. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20682. (values e^ es^ rt)]
  20683. [`(All ,xs (,tys ... -> ,rt))
  20684. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20685. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20686. (match_types env^^ param-ty arg-ty)))
  20687. (define targs
  20688. (for/list ([x xs])
  20689. (match (dict-ref env^^ x (lambda () #f))
  20690. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20691. x (Apply e1 es))]
  20692. [ty ty])))
  20693. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20694. [else (error 'type-check "expected a function, not ~a" ty)]))
  20695. (define/override ((type-check-exp env) e)
  20696. (match e
  20697. [(Lambda `([,xs : ,Ts] ...) rT body)
  20698. (for ([T Ts]) ((check_well_formed env) T))
  20699. ((check_well_formed env) rT)
  20700. ((super type-check-exp env) e)]
  20701. [(HasType e1 ty)
  20702. ((check_well_formed env) ty)
  20703. ((super type-check-exp env) e)]
  20704. [else ((super type-check-exp env) e)]))
  20705. (define/override ((type-check-def env) d)
  20706. (verbose 'type-check "poly/def" d)
  20707. (match d
  20708. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20709. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20710. (for ([p ps]) ((check_well_formed ts-env) p))
  20711. ((check_well_formed ts-env) rt)
  20712. (define new-env (append ts-env (map cons xs ps) env))
  20713. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20714. (check-type-equal? ty^ rt body)
  20715. (Generic ts (Def f p:t* rt info body^))]
  20716. [else ((super type-check-def env) d)]))
  20717. (define/override (type-check-program p)
  20718. (match p
  20719. [(Program info body)
  20720. (type-check-program (ProgramDefsExp info '() body))]
  20721. [(ProgramDefsExp info ds body)
  20722. (define ds^ (combine-decls-defs ds))
  20723. (define new-env (for/list ([d ds^])
  20724. (cons (def-name d) (fun-def-type d))))
  20725. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20726. (define-values (body^ ty) ((type-check-exp new-env) body))
  20727. (check-type-equal? ty 'Integer body)
  20728. (ProgramDefsExp info ds^^ body^)]))
  20729. ))
  20730. \end{lstlisting}
  20731. \fi}
  20732. {\if\edition\pythonEd\pythonColor
  20733. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20734. def type_check_exp(self, e, env):
  20735. match e:
  20736. case Call(Name(f), args) if f in builtin_functions:
  20737. return super().type_check_exp(e, env)
  20738. case Call(func, args):
  20739. func_t = self.type_check_exp(func, env)
  20740. func.has_type = func_t
  20741. match func_t:
  20742. case AllType(ps, FunctionType(p_tys, rt)):
  20743. for arg in args:
  20744. arg.has_type = self.type_check_exp(arg, env)
  20745. arg_tys = [arg.has_type for arg in args]
  20746. deduced = {}
  20747. for (p, a) in zip(p_tys, arg_tys):
  20748. self.match_types(p, a, deduced, e)
  20749. return self.substitute_type(rt, deduced)
  20750. case _:
  20751. return super().type_check_exp(e, env)
  20752. case _:
  20753. return super().type_check_exp(e, env)
  20754. def type_check(self, p):
  20755. match p:
  20756. case Module(body):
  20757. env = {}
  20758. for s in body:
  20759. match s:
  20760. case FunctionDef(name, params, bod, dl, returns, comment):
  20761. params_t = [t for (x,t) in params]
  20762. ty_params = set()
  20763. for t in params_t:
  20764. ty_params |$\mid$|= self.generic_variables(t)
  20765. ty = FunctionType(params_t, returns)
  20766. if len(ty_params) > 0:
  20767. ty = AllType(list(ty_params), ty)
  20768. env[name] = ty
  20769. self.check_stmts(body, IntType(), env)
  20770. case _:
  20771. raise Exception('type_check: unexpected ' + repr(p))
  20772. \end{lstlisting}
  20773. \fi}
  20774. \end{tcolorbox}
  20775. \caption{Type checker for the \LangPoly{} language.}
  20776. \label{fig:type-check-Lpoly}
  20777. \end{figure}
  20778. \begin{figure}[tbp]
  20779. \begin{tcolorbox}[colback=white]
  20780. {\if\edition\racketEd
  20781. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20782. (define/override (type-equal? t1 t2)
  20783. (match* (t1 t2)
  20784. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20785. (define env (map cons xs ys))
  20786. (type-equal? (substitute_type env T1) T2)]
  20787. [(other wise)
  20788. (super type-equal? t1 t2)]))
  20789. (define/public (match_types env pt at)
  20790. (match* (pt at)
  20791. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20792. [('Void 'Void) env] [('Any 'Any) env]
  20793. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20794. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20795. (match_types env^ pt1 at1))]
  20796. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  20797. (define env^ (match_types env prt art))
  20798. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  20799. (match_types env^^ pt1 at1))]
  20800. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  20801. (define env^ (append (map cons pxs axs) env))
  20802. (match_types env^ pt1 at1)]
  20803. [((? symbol? x) at)
  20804. (match (dict-ref env x (lambda () #f))
  20805. [#f (error 'type-check "undefined type variable ~a" x)]
  20806. ['Type (cons (cons x at) env)]
  20807. [t^ (check-type-equal? at t^ 'matching) env])]
  20808. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  20809. (define/public (substitute_type env pt)
  20810. (match pt
  20811. ['Integer 'Integer] ['Boolean 'Boolean]
  20812. ['Void 'Void] ['Any 'Any]
  20813. [`(Vector ,ts ...)
  20814. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  20815. [`(,ts ... -> ,rt)
  20816. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  20817. [`(All ,xs ,t)
  20818. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  20819. [(? symbol? x) (dict-ref env x)]
  20820. [else (error 'type-check "expected a type not ~a" pt)]))
  20821. (define/public (combine-decls-defs ds)
  20822. (match ds
  20823. ['() '()]
  20824. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  20825. (unless (equal? name f)
  20826. (error 'type-check "name mismatch, ~a != ~a" name f))
  20827. (match type
  20828. [`(All ,xs (,ps ... -> ,rt))
  20829. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20830. (cons (Generic xs (Def name params^ rt info body))
  20831. (combine-decls-defs ds^))]
  20832. [`(,ps ... -> ,rt)
  20833. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20834. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  20835. [else (error 'type-check "expected a function type, not ~a" type) ])]
  20836. [`(,(Def f params rt info body) . ,ds^)
  20837. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  20838. \end{lstlisting}
  20839. \fi}
  20840. {\if\edition\pythonEd\pythonColor
  20841. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20842. def match_types(self, param_ty, arg_ty, deduced, e):
  20843. match (param_ty, arg_ty):
  20844. case (GenericVar(id), _):
  20845. if id in deduced:
  20846. self.check_type_equal(arg_ty, deduced[id], e)
  20847. else:
  20848. deduced[id] = arg_ty
  20849. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  20850. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  20851. new_arg_ty = self.substitute_type(arg_ty, rename)
  20852. self.match_types(ty, new_arg_ty, deduced, e)
  20853. case (TupleType(ps), TupleType(ts)):
  20854. for (p, a) in zip(ps, ts):
  20855. self.match_types(p, a, deduced, e)
  20856. case (ListType(p), ListType(a)):
  20857. self.match_types(p, a, deduced, e)
  20858. case (FunctionType(pps, prt), FunctionType(aps, art)):
  20859. for (pp, ap) in zip(pps, aps):
  20860. self.match_types(pp, ap, deduced, e)
  20861. self.match_types(prt, art, deduced, e)
  20862. case (IntType(), IntType()):
  20863. pass
  20864. case (BoolType(), BoolType()):
  20865. pass
  20866. case _:
  20867. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  20868. def substitute_type(self, ty, var_map):
  20869. match ty:
  20870. case GenericVar(id):
  20871. return var_map[id]
  20872. case AllType(ps, ty):
  20873. new_map = copy.deepcopy(var_map)
  20874. for p in ps:
  20875. new_map[p] = GenericVar(p)
  20876. return AllType(ps, self.substitute_type(ty, new_map))
  20877. case TupleType(ts):
  20878. return TupleType([self.substitute_type(t, var_map) for t in ts])
  20879. case ListType(ty):
  20880. return ListType(self.substitute_type(ty, var_map))
  20881. case FunctionType(pts, rt):
  20882. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  20883. self.substitute_type(rt, var_map))
  20884. case IntType():
  20885. return IntType()
  20886. case BoolType():
  20887. return BoolType()
  20888. case _:
  20889. raise Exception('substitute_type: unexpected ' + repr(ty))
  20890. def check_type_equal(self, t1, t2, e):
  20891. match (t1, t2):
  20892. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  20893. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  20894. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  20895. case (_, _):
  20896. return super().check_type_equal(t1, t2, e)
  20897. \end{lstlisting}
  20898. \fi}
  20899. \end{tcolorbox}
  20900. \caption{Auxiliary functions for type checking \LangPoly{}.}
  20901. \label{fig:type-check-Lpoly-aux}
  20902. \end{figure}
  20903. {\if\edition\racketEd
  20904. \begin{figure}[tbp]
  20905. \begin{tcolorbox}[colback=white]
  20906. \begin{lstlisting}
  20907. (define/public ((check_well_formed env) ty)
  20908. (match ty
  20909. ['Integer (void)]
  20910. ['Boolean (void)]
  20911. ['Void (void)]
  20912. [(? symbol? a)
  20913. (match (dict-ref env a (lambda () #f))
  20914. ['Type (void)]
  20915. [else (error 'type-check "undefined type variable ~a" a)])]
  20916. [`(Vector ,ts ...)
  20917. (for ([t ts]) ((check_well_formed env) t))]
  20918. [`(,ts ... -> ,t)
  20919. (for ([t ts]) ((check_well_formed env) t))
  20920. ((check_well_formed env) t)]
  20921. [`(All ,xs ,t)
  20922. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20923. ((check_well_formed env^) t)]
  20924. [else (error 'type-check "unrecognized type ~a" ty)]))
  20925. \end{lstlisting}
  20926. \end{tcolorbox}
  20927. \caption{Well-formed types.}
  20928. \label{fig:well-formed-types}
  20929. \end{figure}
  20930. \fi}
  20931. % TODO: interpreter for R'_10
  20932. \clearpage
  20933. \section{Compiling Generics}
  20934. \label{sec:compiling-poly}
  20935. Broadly speaking, there are four approaches to compiling generics, as
  20936. follows:
  20937. \begin{description}
  20938. \item[Monomorphization] generates a different version of a generic
  20939. function for each set of type arguments with which it is used,
  20940. producing type-specialized code. This approach results in the most
  20941. efficient code but requires whole-program compilation (no separate
  20942. compilation) and may increase code size. Unfortunately,
  20943. monomorphization is incompatible with first-class generics because
  20944. it is not always possible to determine which generic functions are
  20945. used with which type arguments during compilation. (It can be done
  20946. at runtime with just-in-time compilation.) Monomorphization is
  20947. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  20948. generic functions in NESL~\citep{Blelloch:1993aa} and
  20949. ML~\citep{Weeks:2006aa}.
  20950. \item[Uniform representation] generates one version of each generic
  20951. function and requires all values to have a common \emph{boxed} format,
  20952. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  20953. generic and monomorphic code is compiled similarly to code in a
  20954. dynamically typed language (like \LangDyn{}), in which primitive
  20955. operators require their arguments to be projected from \CANYTY{} and
  20956. their results to be injected into \CANYTY{}. (In object-oriented
  20957. languages, the projection is accomplished via virtual method
  20958. dispatch.) The uniform representation approach is compatible with
  20959. separate compilation and with first-class generics. However, it
  20960. produces the least efficient code because it introduces overhead in
  20961. the entire program. This approach is used in
  20962. Java~\citep{Bracha:1998fk},
  20963. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  20964. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  20965. \item[Mixed representation] generates one version of each generic
  20966. function, using a boxed representation for type variables. However,
  20967. monomorphic code is compiled as usual (as in \LangLam{}), and
  20968. conversions are performed at the boundaries between monomorphic code
  20969. and polymorphic code (for example, when a generic function is instantiated
  20970. and called). This approach is compatible with separate compilation
  20971. and first-class generics and maintains efficiency in monomorphic
  20972. code. The trade-off is increased overhead at the boundary between
  20973. monomorphic and generic code. This approach is used in
  20974. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  20975. Java 5 with the addition of autoboxing.
  20976. \item[Type passing] uses the unboxed representation in both
  20977. monomorphic and generic code. Each generic function is compiled to a
  20978. single function with extra parameters that describe the type
  20979. arguments. The type information is used by the generated code to
  20980. determine how to access the unboxed values at runtime. This approach is
  20981. used in implementation of Napier88~\citep{Morrison:1991aa} and
  20982. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  20983. compilation and first-class generics and maintains the
  20984. efficiency for monomorphic code. There is runtime overhead in
  20985. polymorphic code from dispatching on type information.
  20986. \end{description}
  20987. In this chapter we use the mixed representation approach, partly
  20988. because of its favorable attributes and partly because it is
  20989. straightforward to implement using the tools that we have already
  20990. built to support gradual typing. The work of compiling generic
  20991. functions is performed in two passes, \code{resolve} and
  20992. \code{erase\_types}, that we discuss next. The output of
  20993. \code{erase\_types} is \LangCast{}
  20994. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  20995. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  20996. \section{Resolve Instantiation}
  20997. \label{sec:generic-resolve}
  20998. Recall that the type checker for \LangPoly{} deduces the type
  20999. arguments at call sites to a generic function. The purpose of the
  21000. \code{resolve} pass is to turn this implicit instantiation into an
  21001. explicit one, by adding \code{inst} nodes to the syntax of the
  21002. intermediate language. An \code{inst} node records the mapping of
  21003. type parameters to type arguments. The semantics of the \code{inst}
  21004. node is to instantiate the result of its first argument, a generic
  21005. function, to produce a monomorphic function. However, because the
  21006. interpreter never analyzes type annotations, instantiation can be a
  21007. no-op and simply return the generic function.
  21008. %
  21009. The output language of the \code{resolve} pass is \LangInst{},
  21010. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21011. {\if\edition\racketEd
  21012. The \code{resolve} pass combines the type declaration and polymorphic
  21013. function into a single definition, using the \code{Poly} form, to make
  21014. polymorphic functions more convenient to process in the next pass of the
  21015. compiler.
  21016. \fi}
  21017. \newcommand{\LinstASTRacket}{
  21018. \begin{array}{lcl}
  21019. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21020. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21021. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21022. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21023. \end{array}
  21024. }
  21025. \newcommand{\LinstASTPython}{
  21026. \begin{array}{lcl}
  21027. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21028. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21029. \end{array}
  21030. }
  21031. \begin{figure}[tp]
  21032. \centering
  21033. \begin{tcolorbox}[colback=white]
  21034. \small
  21035. {\if\edition\racketEd
  21036. \[
  21037. \begin{array}{l}
  21038. \gray{\LintOpAST} \\ \hline
  21039. \gray{\LvarASTRacket{}} \\ \hline
  21040. \gray{\LifASTRacket{}} \\ \hline
  21041. \gray{\LwhileASTRacket{}} \\ \hline
  21042. \gray{\LtupASTRacket{}} \\ \hline
  21043. \gray{\LfunASTRacket} \\ \hline
  21044. \gray{\LlambdaASTRacket} \\ \hline
  21045. \LinstASTRacket \\
  21046. \begin{array}{lcl}
  21047. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21048. \end{array}
  21049. \end{array}
  21050. \]
  21051. \fi}
  21052. {\if\edition\pythonEd\pythonColor
  21053. \[
  21054. \begin{array}{l}
  21055. \gray{\LintASTPython} \\ \hline
  21056. \gray{\LvarASTPython{}} \\ \hline
  21057. \gray{\LifASTPython{}} \\ \hline
  21058. \gray{\LwhileASTPython{}} \\ \hline
  21059. \gray{\LtupASTPython{}} \\ \hline
  21060. \gray{\LfunASTPython} \\ \hline
  21061. \gray{\LlambdaASTPython} \\ \hline
  21062. \LinstASTPython \\
  21063. \begin{array}{lcl}
  21064. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21065. \end{array}
  21066. \end{array}
  21067. \]
  21068. \fi}
  21069. \end{tcolorbox}
  21070. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21071. (figure~\ref{fig:Llam-syntax}).}
  21072. \label{fig:Lpoly-prime-syntax}
  21073. \end{figure}
  21074. The output of the \code{resolve} pass on the generic \code{map}
  21075. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21076. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21077. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21078. \begin{figure}[tbp]
  21079. % poly_test_2.rkt
  21080. \begin{tcolorbox}[colback=white]
  21081. {\if\edition\racketEd
  21082. \begin{lstlisting}
  21083. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21084. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21085. (define (inc [x : Integer]) : Integer (+ x 1))
  21086. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21087. (Integer))
  21088. inc (vector 0 41)) 1)
  21089. \end{lstlisting}
  21090. \fi}
  21091. {\if\edition\pythonEd\pythonColor
  21092. \begin{lstlisting}
  21093. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21094. return (f(tup[0]), f(tup[1]))
  21095. def add1(x : int) -> int:
  21096. return x + 1
  21097. t = inst(map, {T: int})(add1, (0, 41))
  21098. print(t[1])
  21099. \end{lstlisting}
  21100. \fi}
  21101. \end{tcolorbox}
  21102. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21103. \label{fig:map-resolve}
  21104. \end{figure}
  21105. \section{Erase Generic Types}
  21106. \label{sec:erase_types}
  21107. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21108. represent type variables. For example, figure~\ref{fig:map-erase}
  21109. shows the output of the \code{erase\_types} pass on the generic
  21110. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21111. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  21112. \code{All} types are removed from the type of \code{map}.
  21113. \begin{figure}[tbp]
  21114. \begin{tcolorbox}[colback=white]
  21115. {\if\edition\racketEd
  21116. \begin{lstlisting}
  21117. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21118. : (Vector Any Any)
  21119. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21120. (define (inc [x : Integer]) : Integer (+ x 1))
  21121. (vector-ref ((cast map
  21122. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21123. ((Integer -> Integer) (Vector Integer Integer)
  21124. -> (Vector Integer Integer)))
  21125. inc (vector 0 41)) 1)
  21126. \end{lstlisting}
  21127. \fi}
  21128. {\if\edition\pythonEd\pythonColor
  21129. \begin{lstlisting}
  21130. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21131. return (f(tup[0]), f(tup[1]))
  21132. def add1(x : int) -> int:
  21133. return (x + 1)
  21134. def main() -> int:
  21135. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21136. print(t[1])
  21137. return 0
  21138. \end{lstlisting}
  21139. {\small
  21140. where\\
  21141. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21142. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21143. }
  21144. \fi}
  21145. \end{tcolorbox}
  21146. \caption{The generic \code{map} example after type erasure.}
  21147. \label{fig:map-erase}
  21148. \end{figure}
  21149. This process of type erasure creates a challenge at points of
  21150. instantiation. For example, consider the instantiation of
  21151. \code{map} shown in figure~\ref{fig:map-resolve}.
  21152. The type of \code{map} is
  21153. %
  21154. {\if\edition\racketEd
  21155. \begin{lstlisting}
  21156. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21157. \end{lstlisting}
  21158. \fi}
  21159. {\if\edition\pythonEd\pythonColor
  21160. \begin{lstlisting}
  21161. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21162. \end{lstlisting}
  21163. \fi}
  21164. %
  21165. and it is instantiated to
  21166. %
  21167. {\if\edition\racketEd
  21168. \begin{lstlisting}
  21169. ((Integer -> Integer) (Vector Integer Integer)
  21170. -> (Vector Integer Integer))
  21171. \end{lstlisting}
  21172. \fi}
  21173. {\if\edition\pythonEd\pythonColor
  21174. \begin{lstlisting}
  21175. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21176. \end{lstlisting}
  21177. \fi}
  21178. %
  21179. After erasure, the type of \code{map} is
  21180. %
  21181. {\if\edition\racketEd
  21182. \begin{lstlisting}
  21183. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21184. \end{lstlisting}
  21185. \fi}
  21186. {\if\edition\pythonEd\pythonColor
  21187. \begin{lstlisting}
  21188. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21189. \end{lstlisting}
  21190. \fi}
  21191. %
  21192. but we need to convert it to the instantiated type. This is easy to
  21193. do in the language \LangCast{} with a single \code{cast}. In the
  21194. example shown in figure~\ref{fig:map-erase}, the instantiation of
  21195. \code{map} has been compiled to a \code{cast} from the type of
  21196. \code{map} to the instantiated type. The source and the target type of a
  21197. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  21198. the case because both the source and target are obtained from the same
  21199. generic type of \code{map}, replacing the type parameters with
  21200. \CANYTY{} in the former and with the deduced type arguments in the
  21201. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21202. To implement the \code{erase\_types} pass, we first recommend defining
  21203. a recursive function that translates types, named
  21204. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21205. follows.
  21206. %
  21207. {\if\edition\racketEd
  21208. \begin{lstlisting}
  21209. |$T$|
  21210. |$\Rightarrow$|
  21211. Any
  21212. \end{lstlisting}
  21213. \fi}
  21214. {\if\edition\pythonEd\pythonColor
  21215. \begin{lstlisting}
  21216. GenericVar(|$T$|)
  21217. |$\Rightarrow$|
  21218. Any
  21219. \end{lstlisting}
  21220. \fi}
  21221. %
  21222. \noindent The \code{erase\_type} function also removes the generic
  21223. \code{All} types.
  21224. %
  21225. {\if\edition\racketEd
  21226. \begin{lstlisting}
  21227. (All |$xs$| |$T_1$|)
  21228. |$\Rightarrow$|
  21229. |$T'_1$|
  21230. \end{lstlisting}
  21231. \fi}
  21232. {\if\edition\pythonEd\pythonColor
  21233. \begin{lstlisting}
  21234. AllType(|$xs$|, |$T_1$|)
  21235. |$\Rightarrow$|
  21236. |$T'_1$|
  21237. \end{lstlisting}
  21238. \fi}
  21239. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  21240. %
  21241. In this compiler pass, apply the \code{erase\_type} function to all
  21242. the type annotations in the program.
  21243. Regarding the translation of expressions, the case for \code{Inst} is
  21244. the interesting one. We translate it into a \code{Cast}, as shown
  21245. next.
  21246. The type of the subexpression $e$ is a generic type of the form
  21247. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21248. The source type of the cast is the erasure of $T$, the type $T_s$.
  21249. %
  21250. {\if\edition\racketEd
  21251. %
  21252. The target type $T_t$ is the result of substituting the argument types
  21253. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  21254. erasure.
  21255. %
  21256. \begin{lstlisting}
  21257. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21258. |$\Rightarrow$|
  21259. (Cast |$e'$| |$T_s$| |$T_t$|)
  21260. \end{lstlisting}
  21261. %
  21262. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21263. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21264. \fi}
  21265. {\if\edition\pythonEd\pythonColor
  21266. %
  21267. The target type $T_t$ is the result of substituting the deduced
  21268. argument types $d$ in $T$ followed by doing type erasure.
  21269. %
  21270. \begin{lstlisting}
  21271. Inst(|$e$|, |$d$|)
  21272. |$\Rightarrow$|
  21273. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21274. \end{lstlisting}
  21275. %
  21276. where
  21277. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21278. \fi}
  21279. Finally, each generic function is translated to a regular
  21280. function in which type erasure has been applied to all the type
  21281. annotations and the body.
  21282. %% \begin{lstlisting}
  21283. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21284. %% |$\Rightarrow$|
  21285. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21286. %% \end{lstlisting}
  21287. \begin{exercise}\normalfont\normalsize
  21288. Implement a compiler for the polymorphic language \LangPoly{} by
  21289. extending and adapting your compiler for \LangGrad{}. Create six new
  21290. test programs that use polymorphic functions. Some of them should
  21291. make use of first-class generics.
  21292. \end{exercise}
  21293. \begin{figure}[tbp]
  21294. \begin{tcolorbox}[colback=white]
  21295. {\if\edition\racketEd
  21296. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21297. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21298. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21299. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21300. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21301. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21302. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21303. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21304. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21305. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21306. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21307. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21308. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21309. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21310. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21311. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21312. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21313. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21314. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21315. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21316. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21317. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21318. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21319. \path[->,bend left=15] (Lpoly) edge [above] node
  21320. {\ttfamily\footnotesize resolve} (Lpolyp);
  21321. \path[->,bend left=15] (Lpolyp) edge [above] node
  21322. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21323. \path[->,bend left=15] (Lgradualp) edge [above] node
  21324. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21325. \path[->,bend left=15] (Llambdapp) edge [left] node
  21326. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21327. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21328. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21329. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21330. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21331. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21332. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21333. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21334. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21335. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21336. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21337. \path[->,bend left=15] (F1-1) edge [above] node
  21338. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21339. \path[->,bend left=15] (F1-2) edge [above] node
  21340. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21341. \path[->,bend left=15] (F1-3) edge [left] node
  21342. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21343. \path[->,bend left=15] (F1-4) edge [below] node
  21344. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21345. \path[->,bend right=15] (F1-5) edge [above] node
  21346. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21347. \path[->,bend right=15] (F1-6) edge [above] node
  21348. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21349. \path[->,bend right=15] (C3-2) edge [right] node
  21350. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21351. \path[->,bend right=15] (x86-2) edge [right] node
  21352. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21353. \path[->,bend right=15] (x86-2-1) edge [below] node
  21354. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21355. \path[->,bend right=15] (x86-2-2) edge [right] node
  21356. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21357. \path[->,bend left=15] (x86-3) edge [above] node
  21358. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21359. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21360. \end{tikzpicture}
  21361. \fi}
  21362. {\if\edition\pythonEd\pythonColor
  21363. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21364. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21365. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21366. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21367. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21368. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21369. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21370. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21371. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21372. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21373. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21374. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21375. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21376. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21377. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21378. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21379. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21380. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21381. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21382. \path[->,bend left=15] (Lgradual) edge [above] node
  21383. {\ttfamily\footnotesize shrink} (Lgradual2);
  21384. \path[->,bend left=15] (Lgradual2) edge [above] node
  21385. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21386. \path[->,bend left=15] (Lgradual3) edge [above] node
  21387. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21388. \path[->,bend left=15] (Lgradual4) edge [left] node
  21389. {\ttfamily\footnotesize resolve} (Lgradualr);
  21390. \path[->,bend left=15] (Lgradualr) edge [below] node
  21391. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21392. \path[->,bend right=15] (Llambdapp) edge [above] node
  21393. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21394. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21395. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21396. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21397. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21398. \path[->,bend right=15] (F1-1) edge [below] node
  21399. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21400. \path[->,bend right=15] (F1-2) edge [below] node
  21401. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21402. \path[->,bend left=15] (F1-3) edge [above] node
  21403. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21404. \path[->,bend left=15] (F1-5) edge [left] node
  21405. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21406. \path[->,bend left=5] (F1-6) edge [below] node
  21407. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21408. \path[->,bend right=15] (C3-2) edge [right] node
  21409. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21410. \path[->,bend right=15] (x86-2) edge [below] node
  21411. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21412. \path[->,bend right=15] (x86-3) edge [below] node
  21413. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21414. \path[->,bend left=15] (x86-4) edge [above] node
  21415. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21416. \end{tikzpicture}
  21417. \fi}
  21418. \end{tcolorbox}
  21419. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21420. \label{fig:Lpoly-passes}
  21421. \end{figure}
  21422. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21423. needed to compile \LangPoly{}.
  21424. % TODO: challenge problem: specialization of instantiations
  21425. % Further Reading
  21426. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21427. \clearpage
  21428. \appendix
  21429. \chapter{Appendix}
  21430. \setcounter{footnote}{0}
  21431. {\if\edition\racketEd
  21432. \section{Interpreters}
  21433. \label{appendix:interp}
  21434. \index{subject}{interpreter}
  21435. We provide interpreters for each of the source languages \LangInt{},
  21436. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21437. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21438. intermediate languages \LangCVar{} and \LangCIf{} are in
  21439. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21440. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21441. \key{interp.rkt} file.
  21442. \section{Utility Functions}
  21443. \label{appendix:utilities}
  21444. The utility functions described in this section are in the
  21445. \key{utilities.rkt} file of the support code.
  21446. \paragraph{\code{interp-tests}}
  21447. This function runs the compiler passes and the interpreters on each of
  21448. the specified tests to check whether each pass is correct. The
  21449. \key{interp-tests} function has the following parameters:
  21450. \begin{description}
  21451. \item[name (a string)] A name to identify the compiler.
  21452. \item[typechecker] A function of exactly one argument that either
  21453. raises an error using the \code{error} function when it encounters a
  21454. type error, or returns \code{\#f} when it encounters a type
  21455. error. If there is no type error, the type checker returns the
  21456. program.
  21457. \item[passes] A list with one entry per pass. An entry is a list
  21458. consisting of four things:
  21459. \begin{enumerate}
  21460. \item a string giving the name of the pass;
  21461. \item the function that implements the pass (a translator from AST
  21462. to AST);
  21463. \item a function that implements the interpreter (a function from
  21464. AST to result value) for the output language; and,
  21465. \item a type checker for the output language. Type checkers for
  21466. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21467. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21468. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21469. type checker entry is optional. The support code does not provide
  21470. type checkers for the x86 languages.
  21471. \end{enumerate}
  21472. \item[source-interp] An interpreter for the source language. The
  21473. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21474. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21475. \item[tests] A list of test numbers that specifies which tests to
  21476. run (explained next).
  21477. \end{description}
  21478. %
  21479. The \key{interp-tests} function assumes that the subdirectory
  21480. \key{tests} has a collection of Racket programs whose names all start
  21481. with the family name, followed by an underscore and then the test
  21482. number, and ending with the file extension \key{.rkt}. Also, for each test
  21483. program that calls \code{read} one or more times, there is a file with
  21484. the same name except that the file extension is \key{.in}, which
  21485. provides the input for the Racket program. If the test program is
  21486. expected to fail type checking, then there should be an empty file of
  21487. the same name with extension \key{.tyerr}.
  21488. \paragraph{\code{compiler-tests}}
  21489. This function runs the compiler passes to generate x86 (a \key{.s}
  21490. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21491. It runs the machine code and checks that the output is $42$. The
  21492. parameters to the \code{compiler-tests} function are similar to those
  21493. of the \code{interp-tests} function, and they consist of
  21494. \begin{itemize}
  21495. \item a compiler name (a string),
  21496. \item a type checker,
  21497. \item description of the passes,
  21498. \item name of a test-family, and
  21499. \item a list of test numbers.
  21500. \end{itemize}
  21501. \paragraph{\code{compile-file}}
  21502. This function takes a description of the compiler passes (see the
  21503. comment for \key{interp-tests}) and returns a function that, given a
  21504. program file name (a string ending in \key{.rkt}), applies all the
  21505. passes and writes the output to a file whose name is the same as the
  21506. program file name with extension \key{.rkt} replaced by \key{.s}.
  21507. \paragraph{\code{read-program}}
  21508. This function takes a file path and parses that file (it must be a
  21509. Racket program) into an abstract syntax tree.
  21510. \paragraph{\code{parse-program}}
  21511. This function takes an S-expression representation of an abstract
  21512. syntax tree and converts it into the struct-based representation.
  21513. \paragraph{\code{assert}}
  21514. This function takes two parameters, a string (\code{msg}) and Boolean
  21515. (\code{bool}), and displays the message \key{msg} if the Boolean
  21516. \key{bool} is false.
  21517. \paragraph{\code{lookup}}
  21518. % remove discussion of lookup? -Jeremy
  21519. This function takes a key and an alist and returns the first value that is
  21520. associated with the given key, if there is one. If not, an error is
  21521. triggered. The alist may contain both immutable pairs (built with
  21522. \key{cons}) and mutable pairs (built with \key{mcons}).
  21523. %The \key{map2} function ...
  21524. \fi} %\racketEd
  21525. \section{x86 Instruction Set Quick Reference}
  21526. \label{sec:x86-quick-reference}
  21527. \index{subject}{x86}
  21528. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21529. do. We write $A \to B$ to mean that the value of $A$ is written into
  21530. location $B$. Address offsets are given in bytes. The instruction
  21531. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21532. registers (such as \code{\%rax}), or memory references (such as
  21533. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21534. reference per instruction. Other operands must be immediates or
  21535. registers.
  21536. \begin{table}[tbp]
  21537. \centering
  21538. \begin{tabular}{l|l}
  21539. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21540. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21541. \texttt{negq} $A$ & $- A \to A$ \\
  21542. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21543. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  21544. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  21545. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$ \\
  21546. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  21547. \texttt{retq} & Pops the return address and jumps to it \\
  21548. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  21549. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  21550. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  21551. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21552. be an immediate) \\
  21553. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21554. matches the condition code of the instruction; otherwise go to the
  21555. next instructions. The condition codes are \key{e} for \emph{equal},
  21556. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21557. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21558. \texttt{jl} $L$ & \\
  21559. \texttt{jle} $L$ & \\
  21560. \texttt{jg} $L$ & \\
  21561. \texttt{jge} $L$ & \\
  21562. \texttt{jmp} $L$ & Jump to label $L$ \\
  21563. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21564. \texttt{movzbq} $A$, $B$ &
  21565. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21566. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21567. and the extra bytes of $B$ are set to zero.} \\
  21568. & \\
  21569. & \\
  21570. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  21571. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  21572. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  21573. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21574. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21575. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21576. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21577. description of the condition codes. $A$ must be a single byte register
  21578. (e.g., \texttt{al} or \texttt{cl}).} \\
  21579. \texttt{setl} $A$ & \\
  21580. \texttt{setle} $A$ & \\
  21581. \texttt{setg} $A$ & \\
  21582. \texttt{setge} $A$ &
  21583. \end{tabular}
  21584. \vspace{5pt}
  21585. \caption{Quick reference for the x86 instructions used in this book.}
  21586. \label{tab:x86-instr}
  21587. \end{table}
  21588. \backmatter
  21589. \addtocontents{toc}{\vspace{11pt}}
  21590. \cleardoublepage % needed for right page number in TOC for References
  21591. %% \nocite{*} is a way to get all the entries in the .bib file to
  21592. %% print in the bibliography:
  21593. \nocite{*}\let\bibname\refname
  21594. \addcontentsline{toc}{fmbm}{\refname}
  21595. \printbibliography
  21596. %\printindex{authors}{Author Index}
  21597. \printindex{subject}{Index}
  21598. \end{document}
  21599. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21600. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21601. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21602. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21603. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21604. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21605. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21606. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21607. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21608. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21609. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21610. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21611. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21612. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21613. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21614. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21615. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21616. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21617. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21618. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21619. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21620. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  21621. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21622. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21623. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21624. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21625. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21626. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21627. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21628. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21629. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21630. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21631. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21632. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21633. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21634. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21635. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21636. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21637. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21638. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21639. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21640. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21641. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21642. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21643. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21644. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21645. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21646. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21647. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21648. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21649. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21650. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21651. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21652. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21653. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21654. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21655. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21656. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21657. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21658. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21659. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21660. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21661. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21662. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21663. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21664. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21665. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21666. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21667. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21668. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21669. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21670. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21671. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21672. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21673. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21674. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21675. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21676. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21677. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21678. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21679. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21680. % LocalWords: pseudocode underapproximation underapproximations LALR
  21681. % LocalWords: semilattices overapproximate incrementing Earley docs
  21682. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21683. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21684. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21685. % LocalWords: LC partialevaluation pythonEd TOC