book.tex 709 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351
  1. \documentclass[7x10,nocrop]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  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. \definecolor{lightgray}{gray}{1}
  18. \newcommand{\black}[1]{{\color{black} #1}}
  19. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  20. \newcommand{\gray}[1]{{\color{gray} #1}}
  21. \def\racketEd{0}
  22. \def\pythonEd{1}
  23. \def\edition{0}
  24. % material that is specific to the Racket edition of the book
  25. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  26. % would like a command for: \if\edition\racketEd\color{olive}
  27. % and : \fi\color{black}
  28. % material that is specific to the Python edition of the book
  29. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  30. %% For multiple indices:
  31. \usepackage{multind}
  32. \makeindex{subject}
  33. \makeindex{authors}
  34. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  35. \if\edition\racketEd
  36. \lstset{%
  37. language=Lisp,
  38. basicstyle=\ttfamily\small,
  39. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  40. deletekeywords={read,mapping,vector},
  41. escapechar=|,
  42. columns=flexible,
  43. moredelim=[is][\color{red}]{~}{~},
  44. showstringspaces=false
  45. }
  46. \fi
  47. \if\edition\pythonEd
  48. \lstset{%
  49. language=Python,
  50. basicstyle=\ttfamily\small,
  51. morekeywords={match,case,bool,int,let},
  52. deletekeywords={},
  53. escapechar=|,
  54. columns=flexible,
  55. moredelim=[is][\color{red}]{~}{~},
  56. showstringspaces=false
  57. }
  58. \fi
  59. %%% Any shortcut own defined macros place here
  60. %% sample of author macro:
  61. \input{defs}
  62. \newtheorem{exercise}[theorem]{Exercise}
  63. % Adjusted settings
  64. \setlength{\columnsep}{4pt}
  65. %% \begingroup
  66. %% \setlength{\intextsep}{0pt}%
  67. %% \setlength{\columnsep}{0pt}%
  68. %% \begin{wrapfigure}{r}{0.5\textwidth}
  69. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  70. %% \caption{Basic layout}
  71. %% \end{wrapfigure}
  72. %% \lipsum[1]
  73. %% \endgroup
  74. \newbox\oiintbox
  75. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  76. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  77. \def\oiint{\copy\oiintbox}
  78. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  79. %\usepackage{showframe}
  80. \def\ShowFrameLinethickness{0.125pt}
  81. \addbibresource{book.bib}
  82. \begin{document}
  83. \frontmatter
  84. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  85. \halftitlepage
  86. \Title{Essentials of Compilation}
  87. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  88. %\edition{First Edition}
  89. \BookAuthor{Jeremy G. Siek}
  90. \imprint{The MIT Press\\
  91. Cambridge, Massachusetts\\
  92. London, England}
  93. \begin{copyrightpage}
  94. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  95. or personal downloading under the
  96. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  97. license.
  98. Copyright in this monograph has been licensed exclusively to The MIT
  99. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  100. version to the public in 2022. All inquiries regarding rights should
  101. be addressed to The MIT Press, Rights and Permissions Department.
  102. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  103. %% All rights reserved. No part of this book may be reproduced in any
  104. %% form by any electronic or mechanical means (including photocopying,
  105. %% recording, or information storage and retrieval) without permission in
  106. %% writing from the publisher.
  107. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  108. %% United States of America.
  109. %% Library of Congress Cataloging-in-Publication Data is available.
  110. %% ISBN:
  111. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  112. \end{copyrightpage}
  113. \dedication{This book is dedicated to the programming language wonks
  114. at Indiana University.}
  115. %% \begin{epigraphpage}
  116. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  117. %% \textit{Book Name if any}}
  118. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  119. %% \end{epigraphpage}
  120. \tableofcontents
  121. %\listoffigures
  122. %\listoftables
  123. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  124. \chapter*{Preface}
  125. \addcontentsline{toc}{fmbm}{Preface}
  126. There is a magical moment when a programmer presses the ``run'' button
  127. and the software begins to execute. Somehow a program written in a
  128. high-level language is running on a computer that is only capable of
  129. shuffling bits. Here we reveal the wizardry that makes that moment
  130. possible. Beginning with the groundbreaking work of Backus and
  131. colleagues in the 1950s, computer scientists discovered techniques for
  132. constructing programs, called \emph{compilers}, that automatically
  133. translate high-level programs into machine code.
  134. We take you on a journey of constructing your own compiler for a small
  135. but powerful language. Along the way we explain the essential
  136. concepts, algorithms, and data structures that underlie compilers. We
  137. develop your understanding of how programs are mapped onto computer
  138. hardware, which is helpful when reasoning about properties at the
  139. junction between hardware and software such as execution time,
  140. software errors, and security vulnerabilities. For those interested
  141. in pursuing compiler construction as a career, our goal is to provide a
  142. stepping-stone to advanced topics such as just-in-time compilation,
  143. program analysis, and program optimization. For those interested in
  144. designing and implementing programming languages, we connect
  145. language design choices to their impact on the compiler and the generated
  146. code.
  147. A compiler is typically organized as a sequence of stages that
  148. progressively translate a program to the code that runs on
  149. hardware. We take this approach to the extreme by partitioning our
  150. compiler into a large number of \emph{nanopasses}, each of which
  151. performs a single task. This enables the testing of each pass in
  152. isolation and focuses our attention, making the compiler far easier to
  153. understand.
  154. The most familiar approach to describing compilers is with each
  155. chapter dedicated to one pass. The problem with that approach is it
  156. obfuscates how language features motivate design choices in a
  157. compiler. We instead take an \emph{incremental} approach in which we
  158. build a complete compiler in each chapter, starting with a small input
  159. language that includes only arithmetic and variables. We add new
  160. language features in subsequent chapters, extending the compiler as
  161. necessary.
  162. Our choice of language features is designed to elicit fundamental
  163. concepts and algorithms used in compilers.
  164. \begin{itemize}
  165. \item We begin with integer arithmetic and local variables in
  166. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  167. the fundamental tools of compiler construction: \emph{abstract
  168. syntax trees} and \emph{recursive functions}.
  169. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  170. \emph{graph coloring} to assign variables to machine registers.
  171. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  172. motivates an elegant recursive algorithm for translating them into
  173. conditional \code{goto}'s.
  174. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  175. variables}. This elicits the need for \emph{dataflow
  176. analysis} in the register allocator.
  177. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  178. \emph{garbage collection}.
  179. \item Chapter~\ref{ch:Lfun} adds functions as first-class values but
  180. without lexical scoping, similar to functions in the C programming
  181. language~\citep{Kernighan:1988nx}. The reader learns about the
  182. procedure call stack and \emph{calling conventions} and how they interact
  183. with register allocation and garbage collection. The chapter also
  184. describes how to generate efficient tail calls.
  185. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  186. scoping, i.e., \emph{lambda} expressions. The reader learns about
  187. \emph{closure conversion}, in which lambdas are translated into a
  188. combination of functions and tuples.
  189. % Chapter about classes and objects?
  190. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  191. point the input languages are statically typed. The reader extends
  192. the statically typed language with an \code{Any} type which serves
  193. as a target for compiling the dynamically typed language.
  194. {\if\edition\pythonEd
  195. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  196. \emph{classes}.
  197. \fi}
  198. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type of
  199. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  200. in which different regions of a program may be static or dynamically
  201. typed. The reader implements runtime support for \emph{proxies} that
  202. allow values to safely move between regions.
  203. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  204. leveraging the \code{Any} type and type casts developed in Chapters
  205. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  206. \end{itemize}
  207. There are many language features that we do not include. Our choices
  208. balance the incidental complexity of a feature versus the fundamental
  209. concepts that it exposes. For example, we include tuples and not
  210. records because they both elicit the study of heap allocation and
  211. garbage collection but records come with more incidental complexity.
  212. Since 2009 drafts of this book have served as the textbook for 16-week
  213. compiler courses for upper-level undergraduates and first-year
  214. graduate students at the University of Colorado and Indiana
  215. University.
  216. %
  217. Students come into the course having learned the basics of
  218. programming, data structures and algorithms, and discrete
  219. mathematics.
  220. %
  221. At the beginning of the course, students form groups of 2-4 people.
  222. The groups complete one chapter every two weeks, starting with
  223. Chapter~\ref{ch:Lvar} and finishing with
  224. Chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  225. that we assign to the graduate students. The last two weeks of the
  226. course involve a final project in which students design and implement
  227. a compiler extension of their choosing. The later chapters can be
  228. used in support of these projects. For compiler courses at
  229. universities on the quarter system (about 10 weeks in length), we
  230. recommend completing up through Chapter~\ref{ch:Lvec} or
  231. Chapter~\ref{ch:Lfun} and providing some scafolding code to the
  232. students for each compiler pass.
  233. %
  234. The course can be adapted to emphasize functional languages by
  235. skipping Chapter~\ref{ch:Lwhile} (loops) and including
  236. Chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  237. dynamically typed languages by including Chapter~\ref{ch:Ldyn}.
  238. %
  239. \python{A course that emphasizes object-oriented languages would
  240. include Chapter~\ref{ch:Lobject}.}
  241. %
  242. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  243. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  244. Chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  245. tail calls.
  246. This book has been used in compiler courses at California Polytechnic
  247. State University, Portland State University, Rose–Hulman Institute of
  248. Technology, University of Freiburg, University of Massachusetts
  249. Lowell, and the University of Vermont.
  250. \begin{figure}[tp]
  251. {\if\edition\racketEd
  252. \begin{tikzpicture}[baseline=(current bounding box.center)]
  253. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  254. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  255. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  256. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  257. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  258. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  259. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  260. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  261. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  262. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  263. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  264. \path[->] (C1) edge [above] node {} (C2);
  265. \path[->] (C2) edge [above] node {} (C3);
  266. \path[->] (C3) edge [above] node {} (C4);
  267. \path[->] (C4) edge [above] node {} (C5);
  268. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  269. \path[->] (C5) edge [above] node {} (C7);
  270. \path[->] (C6) edge [above] node {} (C7);
  271. \path[->] (C4) edge [above] node {} (C8);
  272. \path[->] (C4) edge [above] node {} (C9);
  273. \path[->] (C7) edge [above] node {} (C10);
  274. \path[->] (C8) edge [above] node {} (C10);
  275. \path[->] (C10) edge [above] node {} (C11);
  276. \end{tikzpicture}
  277. \fi}
  278. {\if\edition\pythonEd
  279. \begin{tikzpicture}[baseline=(current bounding box.center)]
  280. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  281. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  282. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  283. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  284. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  285. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  286. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  287. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  288. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  289. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  290. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  291. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  292. \path[->] (C1) edge [above] node {} (C2);
  293. \path[->] (C2) edge [above] node {} (C3);
  294. \path[->] (C3) edge [above] node {} (C4);
  295. \path[->] (C4) edge [above] node {} (C5);
  296. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  297. \path[->] (C5) edge [above] node {} (C7);
  298. \path[->] (C6) edge [above] node {} (C7);
  299. \path[->] (C4) edge [above] node {} (C8);
  300. \path[->] (C4) edge [above] node {} (C9);
  301. \path[->] (C7) edge [above] node {} (C10);
  302. \path[->] (C8) edge [above] node {} (C10);
  303. \path[->] (C8) edge [above] node {} (CO);
  304. \path[->] (C10) edge [above] node {} (C11);
  305. \end{tikzpicture}
  306. \fi}
  307. \caption{Diagram of chapter dependencies.}
  308. \label{fig:chapter-dependences}
  309. \end{figure}
  310. \racket{
  311. We use the \href{https://racket-lang.org/}{Racket} language both for
  312. the implementation of the compiler and for the input language, so the
  313. reader should be proficient with Racket or Scheme. There are many
  314. excellent resources for learning Scheme and
  315. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  316. }
  317. \python{
  318. This edition of the book uses \href{https://www.python.org/}{Python}
  319. both for the implementation of the compiler and for the input language, so the
  320. reader should be proficient with Python. There are many
  321. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  322. }
  323. The support code for this book is in the github repository at
  324. the following location:
  325. \if\edition\racketEd
  326. \begin{center}\small
  327. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  328. \end{center}
  329. \fi
  330. \if\edition\pythonEd
  331. \begin{center}\small
  332. \url{https://github.com/IUCompilerCourse/}
  333. \end{center}
  334. \fi
  335. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  336. is helpful but not necessary for the reader to have taken a computer
  337. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  338. assembly language that are needed in the compiler.
  339. %
  340. We follow the System V calling
  341. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  342. that we generate works with the runtime system (written in C) when it
  343. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  344. operating systems on Intel hardware.
  345. %
  346. On the Windows operating system, \code{gcc} uses the Microsoft x64
  347. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  348. assembly code that we generate does \emph{not} work with the runtime
  349. system on Windows. One workaround is to use a virtual machine with
  350. Linux as the guest operating system.
  351. \section*{Acknowledgments}
  352. The tradition of compiler construction at Indiana University goes back
  353. to research and courses on programming languages by Daniel Friedman in
  354. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  355. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  356. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  357. the compiler course and continued the development of Chez Scheme.
  358. %
  359. The compiler course evolved to incorporate novel pedagogical ideas
  360. while also including elements of real-world compilers. One of
  361. Friedman's ideas was to split the compiler into many small
  362. passes. Another idea, called ``the game'', was to test the code
  363. generated by each pass using interpreters.
  364. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  365. developed infrastructure to support this approach and evolved the
  366. course to use even smaller
  367. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  368. design decisions in this book are inspired by the assignment
  369. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  370. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  371. organization of the course made it difficult for students to
  372. understand the rationale for the compiler design. Ghuloum proposed the
  373. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  374. on.
  375. We thank the many students who served as teaching assistants for the
  376. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  377. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  378. garbage collector and x86 interpreter, Michael Vollmer for work on
  379. efficient tail calls, and Michael Vitousek for help with the first
  380. offering of the incremental compiler course at IU.
  381. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  382. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  383. Michael Wollowski for teaching courses based on drafts of this book
  384. and for their feedback.
  385. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  386. course in the early 2000's and especially for finding the bug that
  387. sent our garbage collector on a wild goose chase!
  388. \mbox{}\\
  389. \noindent Jeremy G. Siek \\
  390. Bloomington, Indiana
  391. \mainmatter
  392. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  393. \chapter{Preliminaries}
  394. \label{ch:trees-recur}
  395. In this chapter we review the basic tools that are needed to implement
  396. a compiler. Programs are typically input by a programmer as text,
  397. i.e., a sequence of characters. The program-as-text representation is
  398. called \emph{concrete syntax}. We use concrete syntax to concisely
  399. write down and talk about programs. Inside the compiler, we use
  400. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  401. that efficiently supports the operations that the compiler needs to
  402. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  403. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  404. from concrete syntax to abstract syntax is a process called
  405. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  406. implementation of parsing in this book.
  407. %
  408. \racket{A parser is provided in the support code for translating from
  409. concrete to abstract syntax.}
  410. %
  411. \python{We use Python's \code{ast} module to translate from concrete
  412. to abstract syntax.}
  413. ASTs can be represented in many different ways inside the compiler,
  414. depending on the programming language used to write the compiler.
  415. %
  416. \racket{We use Racket's
  417. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  418. feature to represent ASTs (Section~\ref{sec:ast}).}
  419. %
  420. \python{We use Python classes and objects to represent ASTs, especially the
  421. classes defined in the standard \code{ast} module for the Python
  422. source language.}
  423. %
  424. We use grammars to define the abstract syntax of programming languages
  425. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  426. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  427. recursive functions to construct and deconstruct ASTs
  428. (Section~\ref{sec:recursion}). This chapter provides an brief
  429. introduction to these ideas.
  430. \racket{\index{subject}{struct}}
  431. \python{\index{subject}{class}\index{subject}{object}}
  432. \section{Abstract Syntax Trees}
  433. \label{sec:ast}
  434. Compilers use abstract syntax trees to represent programs because they
  435. often need to ask questions like: for a given part of a program, what
  436. kind of language feature is it? What are its sub-parts? Consider the
  437. program on the left and its AST on the right. This program is an
  438. addition operation and it has two sub-parts, a
  439. \racket{read}\python{input} operation and a negation. The negation has
  440. another sub-part, the integer constant \code{8}. By using a tree to
  441. represent the program, we can easily follow the links to go from one
  442. part of a program to its sub-parts.
  443. \begin{center}
  444. \begin{minipage}{0.4\textwidth}
  445. \if\edition\racketEd
  446. \begin{lstlisting}
  447. (+ (read) (- 8))
  448. \end{lstlisting}
  449. \fi
  450. \if\edition\pythonEd
  451. \begin{lstlisting}
  452. input_int() + -8
  453. \end{lstlisting}
  454. \fi
  455. \end{minipage}
  456. \begin{minipage}{0.4\textwidth}
  457. \begin{equation}
  458. \begin{tikzpicture}
  459. \node[draw] (plus) at (0 , 0) {\key{+}};
  460. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  461. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  462. \node[draw] (8) at (1 , -3) {\key{8}};
  463. \draw[->] (plus) to (read);
  464. \draw[->] (plus) to (minus);
  465. \draw[->] (minus) to (8);
  466. \end{tikzpicture}
  467. \label{eq:arith-prog}
  468. \end{equation}
  469. \end{minipage}
  470. \end{center}
  471. We use the standard terminology for trees to describe ASTs: each
  472. rectangle above is called a \emph{node}. The arrows connect a node to its
  473. \emph{children} (which are also nodes). The top-most node is the
  474. \emph{root}. Every node except for the root has a \emph{parent} (the
  475. node it is the child of). If a node has no children, it is a
  476. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  477. \index{subject}{node}
  478. \index{subject}{children}
  479. \index{subject}{root}
  480. \index{subject}{parent}
  481. \index{subject}{leaf}
  482. \index{subject}{internal node}
  483. %% Recall that an \emph{symbolic expression} (S-expression) is either
  484. %% \begin{enumerate}
  485. %% \item an atom, or
  486. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  487. %% where $e_1$ and $e_2$ are each an S-expression.
  488. %% \end{enumerate}
  489. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  490. %% null value \code{'()}, etc. We can create an S-expression in Racket
  491. %% simply by writing a backquote (called a quasi-quote in Racket)
  492. %% followed by the textual representation of the S-expression. It is
  493. %% quite common to use S-expressions to represent a list, such as $a, b
  494. %% ,c$ in the following way:
  495. %% \begin{lstlisting}
  496. %% `(a . (b . (c . ())))
  497. %% \end{lstlisting}
  498. %% Each element of the list is in the first slot of a pair, and the
  499. %% second slot is either the rest of the list or the null value, to mark
  500. %% the end of the list. Such lists are so common that Racket provides
  501. %% special notation for them that removes the need for the periods
  502. %% and so many parenthesis:
  503. %% \begin{lstlisting}
  504. %% `(a b c)
  505. %% \end{lstlisting}
  506. %% The following expression creates an S-expression that represents AST
  507. %% \eqref{eq:arith-prog}.
  508. %% \begin{lstlisting}
  509. %% `(+ (read) (- 8))
  510. %% \end{lstlisting}
  511. %% When using S-expressions to represent ASTs, the convention is to
  512. %% represent each AST node as a list and to put the operation symbol at
  513. %% the front of the list. The rest of the list contains the children. So
  514. %% in the above case, the root AST node has operation \code{`+} and its
  515. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  516. %% diagram \eqref{eq:arith-prog}.
  517. %% To build larger S-expressions one often needs to splice together
  518. %% several smaller S-expressions. Racket provides the comma operator to
  519. %% splice an S-expression into a larger one. For example, instead of
  520. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  521. %% we could have first created an S-expression for AST
  522. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  523. %% S-expression.
  524. %% \begin{lstlisting}
  525. %% (define ast1.4 `(- 8))
  526. %% (define ast1_1 `(+ (read) ,ast1.4))
  527. %% \end{lstlisting}
  528. %% In general, the Racket expression that follows the comma (splice)
  529. %% can be any expression that produces an S-expression.
  530. {\if\edition\racketEd
  531. We define a Racket \code{struct} for each kind of node. For this
  532. chapter we require just two kinds of nodes: one for integer constants
  533. and one for primitive operations. The following is the \code{struct}
  534. definition for integer constants.\footnote{All of the AST structures are
  535. defined in the file \code{utilities.rkt} in the support code.}
  536. \begin{lstlisting}
  537. (struct Int (value))
  538. \end{lstlisting}
  539. An integer node includes just one thing: the integer value.
  540. To create an AST node for the integer $8$, we write \INT{8}.
  541. \begin{lstlisting}
  542. (define eight (Int 8))
  543. \end{lstlisting}
  544. We say that the value created by \INT{8} is an
  545. \emph{instance} of the
  546. \code{Int} structure.
  547. The following is the \code{struct} definition for primitive operations.
  548. \begin{lstlisting}
  549. (struct Prim (op args))
  550. \end{lstlisting}
  551. A primitive operation node includes an operator symbol \code{op} and a
  552. list of child \code{args}. For example, to create an AST that negates
  553. the number $8$, we write the following.
  554. \begin{lstlisting}
  555. (define neg-eight (Prim '- (list eight)))
  556. \end{lstlisting}
  557. Primitive operations may have zero or more children. The \code{read}
  558. operator has zero:
  559. \begin{lstlisting}
  560. (define rd (Prim 'read '()))
  561. \end{lstlisting}
  562. The addition operator has two children:
  563. \begin{lstlisting}
  564. (define ast1_1 (Prim '+ (list rd neg-eight)))
  565. \end{lstlisting}
  566. We have made a design choice regarding the \code{Prim} structure.
  567. Instead of using one structure for many different operations
  568. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  569. structure for each operation, as follows.
  570. \begin{lstlisting}
  571. (struct Read ())
  572. (struct Add (left right))
  573. (struct Neg (value))
  574. \end{lstlisting}
  575. The reason we choose to use just one structure is that in many parts
  576. of the compiler the code for the different primitive operators is the
  577. same, so we might as well just write that code once, which is enabled
  578. by using a single structure.
  579. \fi}
  580. {\if\edition\pythonEd
  581. We use a Python \code{class} for each kind of node.
  582. The following is the class definition for constants.
  583. \begin{lstlisting}
  584. class Constant:
  585. def __init__(self, value):
  586. self.value = value
  587. \end{lstlisting}
  588. An integer constant node includes just one thing: the integer value.
  589. To create an AST node for the integer $8$, we write \INT{8}.
  590. \begin{lstlisting}
  591. eight = Constant(8)
  592. \end{lstlisting}
  593. We say that the value created by \INT{8} is an
  594. \emph{instance} of the \code{Constant} class.
  595. The following is the class definition for unary operators.
  596. \begin{lstlisting}
  597. class UnaryOp:
  598. def __init__(self, op, operand):
  599. self.op = op
  600. self.operand = operand
  601. \end{lstlisting}
  602. The specific operation is specified by the \code{op} parameter. For
  603. example, the class \code{USub} is for unary subtraction. (More unary
  604. operators are introduced in later chapters.) To create an AST that
  605. negates the number $8$, we write the following.
  606. \begin{lstlisting}
  607. neg_eight = UnaryOp(USub(), eight)
  608. \end{lstlisting}
  609. The call to the \code{input\_int} function is represented by the
  610. \code{Call} and \code{Name} classes.
  611. \begin{lstlisting}
  612. class Call:
  613. def __init__(self, func, args):
  614. self.func = func
  615. self.args = args
  616. class Name:
  617. def __init__(self, id):
  618. self.id = id
  619. \end{lstlisting}
  620. To create an AST node that calls \code{input\_int}, we write
  621. \begin{lstlisting}
  622. read = Call(Name('input_int'), [])
  623. \end{lstlisting}
  624. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  625. the \code{BinOp} class for binary operators.
  626. \begin{lstlisting}
  627. class BinOp:
  628. def __init__(self, left, op, right):
  629. self.op = op
  630. self.left = left
  631. self.right = right
  632. \end{lstlisting}
  633. Similar to \code{UnaryOp}, the specific operation is specified by the
  634. \code{op} parameter, which for now is just an instance of the
  635. \code{Add} class. So to create the AST node that adds negative eight
  636. to some user input, we write the following.
  637. \begin{lstlisting}
  638. ast1_1 = BinOp(read, Add(), neg_eight)
  639. \end{lstlisting}
  640. \fi}
  641. When compiling a program such as \eqref{eq:arith-prog}, we need to
  642. know that the operation associated with the root node is addition and
  643. we need to be able to access its two children. \racket{Racket}\python{Python}
  644. provides pattern matching to support these kinds of queries, as we see in
  645. Section~\ref{sec:pattern-matching}.
  646. We often write down the concrete syntax of a program even when we
  647. really have in mind the AST because the concrete syntax is more
  648. concise. We recommend that, in your mind, you always think of
  649. programs as abstract syntax trees.
  650. \section{Grammars}
  651. \label{sec:grammar}
  652. \index{subject}{integer}
  653. \index{subject}{literal}
  654. \index{subject}{constant}
  655. A programming language can be thought of as a \emph{set} of programs.
  656. The set is typically infinite (one can always create larger and larger
  657. programs) so one cannot simply describe a language by listing all of
  658. the programs in the language. Instead we write down a set of rules, a
  659. \emph{grammar}, for building programs. Grammars are often used to
  660. define the concrete syntax of a language but they can also be used to
  661. describe the abstract syntax. We write our rules in a variant of
  662. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  663. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  664. As an example, we describe a small language, named \LangInt{}, that consists of
  665. integers and arithmetic operations.
  666. \index{subject}{grammar}
  667. The first grammar rule for the abstract syntax of \LangInt{} says that an
  668. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  669. \begin{equation}
  670. \Exp ::= \INT{\Int} \label{eq:arith-int}
  671. \end{equation}
  672. %
  673. Each rule has a left-hand-side and a right-hand-side.
  674. If you have an AST node that matches the
  675. right-hand-side, then you can categorize it according to the
  676. left-hand-side.
  677. %
  678. Symbols in typewriter font are \emph{terminal} symbols and must
  679. literally appear in the program for the rule to be applicable.
  680. \index{subject}{terminal}
  681. %
  682. Our grammars do not mention \emph{white-space}, that is, separating characters
  683. like spaces, tabulators, and newlines. White-space may be inserted
  684. between symbols for disambiguation and to improve readability.
  685. \index{subject}{white-space}
  686. %
  687. A name such as $\Exp$ that is defined by the grammar rules is a
  688. \emph{non-terminal}. \index{subject}{non-terminal}
  689. %
  690. The name $\Int$ is also a non-terminal, but instead of defining it
  691. with a grammar rule, we define it with the following explanation. An
  692. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  693. $-$ (for negative integers), such that the sequence of decimals
  694. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  695. the representation of integers using 63 bits, which simplifies several
  696. aspects of compilation. \racket{Thus, these integers correspond to
  697. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  698. \python{In contrast, integers in Python have unlimited precision, but
  699. the techniques needed to handle unlimited precision fall outside the
  700. scope of this book.}
  701. The second grammar rule is the \READOP{} operation that receives an
  702. input integer from the user of the program.
  703. \begin{equation}
  704. \Exp ::= \READ{} \label{eq:arith-read}
  705. \end{equation}
  706. The third rule categorizes the negation of an $\Exp$ node as an
  707. $\Exp$.
  708. \begin{equation}
  709. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  710. \end{equation}
  711. We can apply these rules to categorize the ASTs that are in the
  712. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  713. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  714. following AST is an $\Exp$.
  715. \begin{center}
  716. \begin{minipage}{0.5\textwidth}
  717. \NEG{\INT{\code{8}}}
  718. \end{minipage}
  719. \begin{minipage}{0.25\textwidth}
  720. \begin{equation}
  721. \begin{tikzpicture}
  722. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  723. \node[draw, circle] (8) at (0, -1.2) {$8$};
  724. \draw[->] (minus) to (8);
  725. \end{tikzpicture}
  726. \label{eq:arith-neg8}
  727. \end{equation}
  728. \end{minipage}
  729. \end{center}
  730. The next grammar rules are for addition and subtraction expressions:
  731. \begin{align}
  732. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  733. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  734. \end{align}
  735. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  736. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  737. \eqref{eq:arith-read} and we have already categorized
  738. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  739. to show that
  740. \[
  741. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  742. \]
  743. is an $\Exp$ in the \LangInt{} language.
  744. If you have an AST for which the above rules do not apply, then the
  745. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  746. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  747. because there is no rule for the \key{*} operator. Whenever we
  748. define a language with a grammar, the language only includes those
  749. programs that are justified by the grammar rules.
  750. {\if\edition\pythonEd
  751. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  752. There is a statement for printing the value of an expression
  753. \[
  754. \Stmt{} ::= \PRINT{\Exp}
  755. \]
  756. and a statement that evaluates an expression but ignores the result.
  757. \[
  758. \Stmt{} ::= \EXPR{\Exp}
  759. \]
  760. \fi}
  761. {\if\edition\racketEd
  762. The last grammar rule for \LangInt{} states that there is a
  763. \code{Program} node to mark the top of the whole program:
  764. \[
  765. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  766. \]
  767. The \code{Program} structure is defined as follows
  768. \begin{lstlisting}
  769. (struct Program (info body))
  770. \end{lstlisting}
  771. where \code{body} is an expression. In later chapters, the \code{info}
  772. part will be used to store auxiliary information but for now it is
  773. just the empty list.
  774. \fi}
  775. {\if\edition\pythonEd
  776. The last grammar rule for \LangInt{} states that there is a
  777. \code{Module} node to mark the top of the whole program:
  778. \[
  779. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  780. \]
  781. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  782. this case, a list of statements.
  783. %
  784. The \code{Module} class is defined as follows
  785. \begin{lstlisting}
  786. class Module:
  787. def __init__(self, body):
  788. self.body = body
  789. \end{lstlisting}
  790. where \code{body} is a list of statements.
  791. \fi}
  792. It is common to have many grammar rules with the same left-hand side
  793. but different right-hand sides, such as the rules for $\Exp$ in the
  794. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  795. combine several right-hand-sides into a single rule.
  796. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  797. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  798. defined in Figure~\ref{fig:r0-concrete-syntax}.
  799. \racket{The \code{read-program} function provided in
  800. \code{utilities.rkt} of the support code reads a program in from a
  801. file (the sequence of characters in the concrete syntax of Racket)
  802. and parses it into an abstract syntax tree. See the description of
  803. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  804. details.}
  805. \python{The \code{parse} function in Python's \code{ast} module
  806. converts the concrete syntax (represented as a string) into an
  807. abstract syntax tree.}
  808. \newcommand{\LintGrammarRacket}{
  809. \begin{array}{rcl}
  810. \Type &::=& \key{Integer} \\
  811. \Exp{} &::=& \Int{} \MID \CREAD \RP \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  812. \MID \CSUB{\Exp}{\Exp}
  813. \end{array}
  814. }
  815. \newcommand{\LintASTRacket}{
  816. \begin{array}{rcl}
  817. \Type &::=& \key{Integer} \\
  818. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  819. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  820. \end{array}
  821. }
  822. \newcommand{\LintGrammarPython}{
  823. \begin{array}{rcl}
  824. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  825. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  826. \end{array}
  827. }
  828. \newcommand{\LintASTPython}{
  829. \begin{array}{rcl}
  830. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  831. \itm{unaryop} &::= & \code{USub()} \\
  832. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  833. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  834. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  835. \end{array}
  836. }
  837. \begin{figure}[tp]
  838. \fbox{
  839. \begin{minipage}{0.96\textwidth}
  840. {\if\edition\racketEd
  841. \[
  842. \begin{array}{l}
  843. \LintGrammarRacket \\
  844. \begin{array}{rcl}
  845. \LangInt{} &::=& \Exp
  846. \end{array}
  847. \end{array}
  848. \]
  849. \fi}
  850. {\if\edition\pythonEd
  851. \[
  852. \begin{array}{l}
  853. \LintGrammarPython \\
  854. \begin{array}{rcl}
  855. \LangInt{} &::=& \Stmt^{*}
  856. \end{array}
  857. \end{array}
  858. \]
  859. \fi}
  860. \end{minipage}
  861. }
  862. \caption{The concrete syntax of \LangInt{}.}
  863. \label{fig:r0-concrete-syntax}
  864. \end{figure}
  865. \begin{figure}[tp]
  866. \fbox{
  867. \begin{minipage}{0.96\textwidth}
  868. {\if\edition\racketEd
  869. \[
  870. \begin{array}{l}
  871. \LintASTRacket{} \\
  872. \begin{array}{rcl}
  873. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  874. \end{array}
  875. \end{array}
  876. \]
  877. \fi}
  878. {\if\edition\pythonEd
  879. \[
  880. \begin{array}{l}
  881. \LintASTPython\\
  882. \begin{array}{rcl}
  883. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  884. \end{array}
  885. \end{array}
  886. \]
  887. \fi}
  888. \end{minipage}
  889. }
  890. \caption{The abstract syntax of \LangInt{}.}
  891. \label{fig:r0-syntax}
  892. \end{figure}
  893. \section{Pattern Matching}
  894. \label{sec:pattern-matching}
  895. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  896. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  897. \texttt{match} feature to access the parts of a value.
  898. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  899. \begin{center}
  900. \begin{minipage}{0.5\textwidth}
  901. {\if\edition\racketEd
  902. \begin{lstlisting}
  903. (match ast1_1
  904. [(Prim op (list child1 child2))
  905. (print op)])
  906. \end{lstlisting}
  907. \fi}
  908. {\if\edition\pythonEd
  909. \begin{lstlisting}
  910. match ast1_1:
  911. case BinOp(child1, op, child2):
  912. print(op)
  913. \end{lstlisting}
  914. \fi}
  915. \end{minipage}
  916. \end{center}
  917. {\if\edition\racketEd
  918. %
  919. In the above example, the \texttt{match} form checks whether the AST
  920. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  921. three pattern variables \texttt{op}, \texttt{child1}, and
  922. \texttt{child2}. In general, a match clause consists of a
  923. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  924. recursively defined to be either a pattern variable, a structure name
  925. followed by a pattern for each of the structure's arguments, or an
  926. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  927. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  928. and Chapter 9 of The Racket
  929. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  930. for complete descriptions of \code{match}.)
  931. %
  932. The body of a match clause may contain arbitrary Racket code. The
  933. pattern variables can be used in the scope of the body, such as
  934. \code{op} in \code{(print op)}.
  935. %
  936. \fi}
  937. %
  938. %
  939. {\if\edition\pythonEd
  940. %
  941. In the above example, the \texttt{match} form checks whether the AST
  942. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  943. three pattern variables \texttt{child1}, \texttt{op}, and
  944. \texttt{child2}, and then prints out the operator. In general, each
  945. \code{case} consists of a \emph{pattern} and a
  946. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  947. to be either a pattern variable, a class name followed by a pattern
  948. for each of its constructor's arguments, or other literals such as
  949. strings, lists, etc.
  950. %
  951. The body of each \code{case} may contain arbitrary Python code. The
  952. pattern variables can be used in the body, such as \code{op} in
  953. \code{print(op)}.
  954. %
  955. \fi}
  956. A \code{match} form may contain several clauses, as in the following
  957. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  958. the AST. The \code{match} proceeds through the clauses in order,
  959. checking whether the pattern can match the input AST. The body of the
  960. first clause that matches is executed. The output of \code{leaf} for
  961. several ASTs is shown on the right.
  962. \begin{center}
  963. \begin{minipage}{0.6\textwidth}
  964. {\if\edition\racketEd
  965. \begin{lstlisting}
  966. (define (leaf arith)
  967. (match arith
  968. [(Int n) #t]
  969. [(Prim 'read '()) #t]
  970. [(Prim '- (list e1)) #f]
  971. [(Prim '+ (list e1 e2)) #f]
  972. [(Prim '- (list e1 e2)) #f]))
  973. (leaf (Prim 'read '()))
  974. (leaf (Prim '- (list (Int 8))))
  975. (leaf (Int 8))
  976. \end{lstlisting}
  977. \fi}
  978. {\if\edition\pythonEd
  979. \begin{lstlisting}
  980. def leaf(arith):
  981. match arith:
  982. case Constant(n):
  983. return True
  984. case Call(Name('input_int'), []):
  985. return True
  986. case UnaryOp(USub(), e1):
  987. return False
  988. case BinOp(e1, Add(), e2):
  989. return False
  990. case BinOp(e1, Sub(), e2):
  991. return False
  992. print(leaf(Call(Name('input_int'), [])))
  993. print(leaf(UnaryOp(USub(), eight)))
  994. print(leaf(Constant(8)))
  995. \end{lstlisting}
  996. \fi}
  997. \end{minipage}
  998. \vrule
  999. \begin{minipage}{0.25\textwidth}
  1000. {\if\edition\racketEd
  1001. \begin{lstlisting}
  1002. #t
  1003. #f
  1004. #t
  1005. \end{lstlisting}
  1006. \fi}
  1007. {\if\edition\pythonEd
  1008. \begin{lstlisting}
  1009. True
  1010. False
  1011. True
  1012. \end{lstlisting}
  1013. \fi}
  1014. \end{minipage}
  1015. \end{center}
  1016. When constructing a \code{match} expression, we refer to the grammar
  1017. definition to identify which non-terminal we are expecting to match
  1018. against, then we make sure that 1) we have one
  1019. \racket{clause}\python{case} for each alternative of that non-terminal
  1020. and 2) that the pattern in each \racket{clause}\python{case}
  1021. corresponds to the corresponding right-hand side of a grammar
  1022. rule. For the \code{match} in the \code{leaf} function, we refer to
  1023. the grammar for \LangInt{} in Figure~\ref{fig:r0-syntax}. The $\Exp$
  1024. non-terminal has 4 alternatives, so the \code{match} has 4
  1025. \racket{clauses}\python{cases}. The pattern in each
  1026. \racket{clause}\python{case} corresponds to the right-hand side of a
  1027. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1028. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1029. translating from grammars to patterns, replace non-terminals such as
  1030. $\Exp$ with pattern variables of your choice (e.g. \code{e1} and
  1031. \code{e2}).
  1032. \section{Recursive Functions}
  1033. \label{sec:recursion}
  1034. \index{subject}{recursive function}
  1035. Programs are inherently recursive. For example, an expression is often
  1036. made of smaller expressions. Thus, the natural way to process an
  1037. entire program is with a recursive function. As a first example of
  1038. such a recursive function, we define the function \code{is\_exp} in
  1039. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1040. determines whether or not it is an expression in \LangInt{}.
  1041. %
  1042. We say that a function is defined by \emph{structural recursion} when
  1043. it is defined using a sequence of match \racket{clauses}\python{cases}
  1044. that correspond to a grammar, and the body of each
  1045. \racket{clause}\python{case} makes a recursive call on each child
  1046. node.\footnote{This principle of structuring code according to the
  1047. data definition is advocated in the book \emph{How to Design
  1048. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1049. second function, named \code{stmt}, that recognizes whether a value
  1050. is a \LangInt{} statement.} \python{Finally, }
  1051. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{is\_Lint},
  1052. which determines whether an AST is a program in \LangInt{}. In
  1053. general we can write one recursive function to handle each
  1054. non-terminal in a grammar.\index{subject}{structural recursion} Of the
  1055. two examples at the bottom of the figure, the first is in
  1056. \LangInt{} and the second is not.
  1057. \begin{figure}[tp]
  1058. {\if\edition\racketEd
  1059. \begin{lstlisting}
  1060. (define (is_exp ast)
  1061. (match ast
  1062. [(Int n) #t]
  1063. [(Prim 'read '()) #t]
  1064. [(Prim '- (list e)) (is_exp e)]
  1065. [(Prim '+ (list e1 e2))
  1066. (and (is_exp e1) (is_exp e2))]
  1067. [(Prim '- (list e1 e2))
  1068. (and (is_exp e1) (is_exp e2))]
  1069. [else #f]))
  1070. (define (is_Lint ast)
  1071. (match ast
  1072. [(Program '() e) (is_exp e)]
  1073. [else #f]))
  1074. (is_Lint (Program '() ast1_1)
  1075. (is_Lint (Program '()
  1076. (Prim '* (list (Prim 'read '())
  1077. (Prim '+ (list (Int 8)))))))
  1078. \end{lstlisting}
  1079. \fi}
  1080. {\if\edition\pythonEd
  1081. \begin{lstlisting}
  1082. def is_exp(e):
  1083. match e:
  1084. case Constant(n):
  1085. return True
  1086. case Call(Name('input_int'), []):
  1087. return True
  1088. case UnaryOp(USub(), e1):
  1089. return is_exp(e1)
  1090. case BinOp(e1, Add(), e2):
  1091. return is_exp(e1) and is_exp(e2)
  1092. case BinOp(e1, Sub(), e2):
  1093. return is_exp(e1) and is_exp(e2)
  1094. case _:
  1095. return False
  1096. def stmt(s):
  1097. match s:
  1098. case Expr(Call(Name('print'), [e])):
  1099. return is_exp(e)
  1100. case Expr(e):
  1101. return is_exp(e)
  1102. case _:
  1103. return False
  1104. def is_Lint(p):
  1105. match p:
  1106. case Module(body):
  1107. return all([stmt(s) for s in body])
  1108. case _:
  1109. return False
  1110. print(is_Lint(Module([Expr(ast1_1)])))
  1111. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1112. UnaryOp(Add(), Constant(8))))])))
  1113. \end{lstlisting}
  1114. \fi}
  1115. \caption{Example of recursive functions for \LangInt{}. These functions
  1116. recognize whether an AST is in \LangInt{}.}
  1117. \label{fig:exp-predicate}
  1118. \end{figure}
  1119. %% You may be tempted to merge the two functions into one, like this:
  1120. %% \begin{center}
  1121. %% \begin{minipage}{0.5\textwidth}
  1122. %% \begin{lstlisting}
  1123. %% (define (Lint ast)
  1124. %% (match ast
  1125. %% [(Int n) #t]
  1126. %% [(Prim 'read '()) #t]
  1127. %% [(Prim '- (list e)) (Lint e)]
  1128. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1129. %% [(Program '() e) (Lint e)]
  1130. %% [else #f]))
  1131. %% \end{lstlisting}
  1132. %% \end{minipage}
  1133. %% \end{center}
  1134. %% %
  1135. %% Sometimes such a trick will save a few lines of code, especially when
  1136. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1137. %% \emph{not} recommended because it can get you into trouble.
  1138. %% %
  1139. %% For example, the above function is subtly wrong:
  1140. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1141. %% returns true when it should return false.
  1142. \section{Interpreters}
  1143. \label{sec:interp_Lint}
  1144. \index{subject}{interpreter}
  1145. The behavior of a program is defined by the specification of the
  1146. programming language.
  1147. %
  1148. \racket{For example, the Scheme language is defined in the report by
  1149. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1150. reference manual~\citep{plt-tr}.}
  1151. %
  1152. \python{For example, the Python language is defined in the Python
  1153. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1154. %
  1155. In this book we use interpreters to specify each language that we
  1156. consider. An interpreter that is designated as the definition of a
  1157. language is called a \emph{definitional
  1158. interpreter}~\citep{reynolds72:_def_interp}.
  1159. \index{subject}{definitional interpreter} We warm up by creating a
  1160. definitional interpreter for the \LangInt{} language. This interpreter
  1161. serves as a second example of structural recursion. The
  1162. \code{interp\_Lint} function is defined in
  1163. Figure~\ref{fig:interp_Lint}.
  1164. %
  1165. \racket{The body of the function is a match on the input program
  1166. followed by a call to the \lstinline{interp_exp} helper function,
  1167. which in turn has one match clause per grammar rule for \LangInt{}
  1168. expressions.}
  1169. %
  1170. \python{The body of the function matches on the \code{Module} AST node
  1171. and then invokes \code{interp\_stmt} on each statement in the
  1172. module. The \code{interp\_stmt} function includes a case for each
  1173. grammar rule of the \Stmt{} non-terminal and it calls
  1174. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1175. function includes a case for each grammar rule of the \Exp{}
  1176. non-terminal.}
  1177. \begin{figure}[tp]
  1178. {\if\edition\racketEd
  1179. \begin{lstlisting}
  1180. (define (interp_exp e)
  1181. (match e
  1182. [(Int n) n]
  1183. [(Prim 'read '())
  1184. (define r (read))
  1185. (cond [(fixnum? r) r]
  1186. [else (error 'interp_exp "read expected an integer" r)])]
  1187. [(Prim '- (list e))
  1188. (define v (interp_exp e))
  1189. (fx- 0 v)]
  1190. [(Prim '+ (list e1 e2))
  1191. (define v1 (interp_exp e1))
  1192. (define v2 (interp_exp e2))
  1193. (fx+ v1 v2)]
  1194. [(Prim '- (list e1 e2))
  1195. (define v1 ((interp-exp env) e1))
  1196. (define v2 ((interp-exp env) e2))
  1197. (fx- v1 v2)]))
  1198. (define (interp_Lint p)
  1199. (match p
  1200. [(Program '() e) (interp_exp e)]))
  1201. \end{lstlisting}
  1202. \fi}
  1203. {\if\edition\pythonEd
  1204. \begin{lstlisting}
  1205. def interp_exp(e):
  1206. match e:
  1207. case BinOp(left, Add(), right):
  1208. l = interp_exp(left); r = interp_exp(right)
  1209. return l + r
  1210. case BinOp(left, Sub(), right):
  1211. l = interp_exp(left); r = interp_exp(right)
  1212. return l - r
  1213. case UnaryOp(USub(), v):
  1214. return - interp_exp(v)
  1215. case Constant(value):
  1216. return value
  1217. case Call(Name('input_int'), []):
  1218. return int(input())
  1219. def interp_stmt(s):
  1220. match s:
  1221. case Expr(Call(Name('print'), [arg])):
  1222. print(interp_exp(arg))
  1223. case Expr(value):
  1224. interp_exp(value)
  1225. def interp_Lint(p):
  1226. match p:
  1227. case Module(body):
  1228. for s in body:
  1229. interp_stmt(s)
  1230. \end{lstlisting}
  1231. \fi}
  1232. \caption{Interpreter for the \LangInt{} language.}
  1233. \label{fig:interp_Lint}
  1234. \end{figure}
  1235. Let us consider the result of interpreting a few \LangInt{} programs. The
  1236. following program adds two integers.
  1237. {\if\edition\racketEd
  1238. \begin{lstlisting}
  1239. (+ 10 32)
  1240. \end{lstlisting}
  1241. \fi}
  1242. {\if\edition\pythonEd
  1243. \begin{lstlisting}
  1244. print(10 + 32)
  1245. \end{lstlisting}
  1246. \fi}
  1247. %
  1248. \noindent The result is \key{42}, the answer to life, the universe,
  1249. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1250. the Galaxy} by Douglas Adams.}
  1251. %
  1252. We wrote the above program in concrete syntax whereas the parsed
  1253. abstract syntax is:
  1254. {\if\edition\racketEd
  1255. \begin{lstlisting}
  1256. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1257. \end{lstlisting}
  1258. \fi}
  1259. {\if\edition\pythonEd
  1260. \begin{lstlisting}
  1261. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1262. \end{lstlisting}
  1263. \fi}
  1264. The next example demonstrates that expressions may be nested within
  1265. each other, in this case nesting several additions and negations.
  1266. {\if\edition\racketEd
  1267. \begin{lstlisting}
  1268. (+ 10 (- (+ 12 20)))
  1269. \end{lstlisting}
  1270. \fi}
  1271. {\if\edition\pythonEd
  1272. \begin{lstlisting}
  1273. print(10 + -(12 + 20))
  1274. \end{lstlisting}
  1275. \fi}
  1276. %
  1277. \noindent What is the result of the above program?
  1278. {\if\edition\racketEd
  1279. As mentioned previously, the \LangInt{} language does not support
  1280. arbitrarily-large integers, but only $63$-bit integers, so we
  1281. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1282. in Racket.
  1283. Suppose
  1284. \[
  1285. n = 999999999999999999
  1286. \]
  1287. which indeed fits in $63$-bits. What happens when we run the
  1288. following program in our interpreter?
  1289. \begin{lstlisting}
  1290. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1291. \end{lstlisting}
  1292. It produces an error:
  1293. \begin{lstlisting}
  1294. fx+: result is not a fixnum
  1295. \end{lstlisting}
  1296. We establish the convention that if running the definitional
  1297. interpreter on a program produces an error then the meaning of that
  1298. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1299. error is a \code{trapped-error}. A compiler for the language is under
  1300. no obligations regarding programs with unspecified behavior; it does
  1301. not have to produce an executable, and if it does, that executable can
  1302. do anything. On the other hand, if the error is a
  1303. \code{trapped-error}, then the compiler must produce an executable and
  1304. it is required to report that an error occurred. To signal an error,
  1305. exit with a return code of \code{255}. The interpreters in chapters
  1306. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1307. \code{trapped-error}.
  1308. \fi}
  1309. % TODO: how to deal with too-large integers in the Python interpreter?
  1310. %% This convention applies to the languages defined in this
  1311. %% book, as a way to simplify the student's task of implementing them,
  1312. %% but this convention is not applicable to all programming languages.
  1313. %%
  1314. Moving on to the last feature of the \LangInt{} language, the
  1315. \READOP{} operation prompts the user of the program for an integer.
  1316. Recall that program \eqref{eq:arith-prog} requests an integer input
  1317. and then subtracts \code{8}. So if we run
  1318. {\if\edition\racketEd
  1319. \begin{lstlisting}
  1320. (interp_Lint (Program '() ast1_1))
  1321. \end{lstlisting}
  1322. \fi}
  1323. {\if\edition\pythonEd
  1324. \begin{lstlisting}
  1325. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1326. \end{lstlisting}
  1327. \fi}
  1328. \noindent and if the input is \code{50}, the result is \code{42}.
  1329. We include the \READOP{} operation in \LangInt{} so a clever student
  1330. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1331. during compilation to obtain the output and then generates the trivial
  1332. code to produce the output.\footnote{Yes, a clever student did this in the
  1333. first instance of this course!}
  1334. The job of a compiler is to translate a program in one language into a
  1335. program in another language so that the output program behaves the
  1336. same way as the input program. This idea is depicted in the
  1337. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1338. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1339. Given a compiler that translates from language $\mathcal{L}_1$ to
  1340. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1341. compiler must translate it into some program $P_2$ such that
  1342. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1343. same input $i$ yields the same output $o$.
  1344. \begin{equation} \label{eq:compile-correct}
  1345. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1346. \node (p1) at (0, 0) {$P_1$};
  1347. \node (p2) at (3, 0) {$P_2$};
  1348. \node (o) at (3, -2.5) {$o$};
  1349. \path[->] (p1) edge [above] node {compile} (p2);
  1350. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1351. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1352. \end{tikzpicture}
  1353. \end{equation}
  1354. In the next section we see our first example of a compiler.
  1355. \section{Example Compiler: a Partial Evaluator}
  1356. \label{sec:partial-evaluation}
  1357. In this section we consider a compiler that translates \LangInt{}
  1358. programs into \LangInt{} programs that may be more efficient. The
  1359. compiler eagerly computes the parts of the program that do not depend
  1360. on any inputs, a process known as \emph{partial
  1361. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1362. For example, given the following program
  1363. {\if\edition\racketEd
  1364. \begin{lstlisting}
  1365. (+ (read) (- (+ 5 3)))
  1366. \end{lstlisting}
  1367. \fi}
  1368. {\if\edition\pythonEd
  1369. \begin{lstlisting}
  1370. print(input_int() + -(5 + 3) )
  1371. \end{lstlisting}
  1372. \fi}
  1373. \noindent our compiler translates it into the program
  1374. {\if\edition\racketEd
  1375. \begin{lstlisting}
  1376. (+ (read) -8)
  1377. \end{lstlisting}
  1378. \fi}
  1379. {\if\edition\pythonEd
  1380. \begin{lstlisting}
  1381. print(input_int() + -8)
  1382. \end{lstlisting}
  1383. \fi}
  1384. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1385. evaluator for the \LangInt{} language. The output of the partial evaluator
  1386. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1387. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1388. whereas the code for partially evaluating the negation and addition
  1389. operations is factored into two auxiliary functions:
  1390. \code{pe\_neg} and \code{pe\_add}. The input to these
  1391. functions is the output of partially evaluating the children.
  1392. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1393. arguments are integers and if they are, perform the appropriate
  1394. arithmetic. Otherwise, they create an AST node for the arithmetic
  1395. operation.
  1396. \begin{figure}[tp]
  1397. {\if\edition\racketEd
  1398. \begin{lstlisting}
  1399. (define (pe_neg r)
  1400. (match r
  1401. [(Int n) (Int (fx- 0 n))]
  1402. [else (Prim '- (list r))]))
  1403. (define (pe_add r1 r2)
  1404. (match* (r1 r2)
  1405. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1406. [(_ _) (Prim '+ (list r1 r2))]))
  1407. (define (pe_exp e)
  1408. (match e
  1409. [(Int n) (Int n)]
  1410. [(Prim 'read '()) (Prim 'read '())]
  1411. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1412. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1413. [(Prim '- (list e1 e2)) (pe-add ((pe-exp env) e1)
  1414. (pe-neg ((pe-exp env) e2)))]))
  1415. (define (pe_Lint p)
  1416. (match p
  1417. [(Program '() e) (Program '() (pe_exp e))]))
  1418. \end{lstlisting}
  1419. \fi}
  1420. {\if\edition\pythonEd
  1421. \begin{lstlisting}
  1422. def pe_neg(r):
  1423. match r:
  1424. case Constant(n):
  1425. return Constant(-n)
  1426. case _:
  1427. return UnaryOp(USub(), r)
  1428. def pe_add(r1, r2):
  1429. match (r1, r2):
  1430. case (Constant(n1), Constant(n2)):
  1431. return Constant(n1 + n2)
  1432. case _:
  1433. return BinOp(r1, Add(), r2)
  1434. def pe_sub(r1, r2):
  1435. match (r1, r2):
  1436. case (Constant(n1), Constant(n2)):
  1437. return Constant(n1 - n2)
  1438. case _:
  1439. return BinOp(r1, Sub(), r2)
  1440. def pe_exp(e):
  1441. match e:
  1442. case BinOp(left, Add(), right):
  1443. return pe_add(pe_exp(left), pe_exp(right))
  1444. case BinOp(left, Sub(), right):
  1445. return pe_sub(pe_exp(left), pe_exp(right))
  1446. case UnaryOp(USub(), v):
  1447. return pe_neg(pe_exp(v))
  1448. case Constant(value):
  1449. return e
  1450. case Call(Name('input_int'), []):
  1451. return e
  1452. def pe_stmt(s):
  1453. match s:
  1454. case Expr(Call(Name('print'), [arg])):
  1455. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1456. case Expr(value):
  1457. return Expr(pe_exp(value))
  1458. def pe_P_int(p):
  1459. match p:
  1460. case Module(body):
  1461. new_body = [pe_stmt(s) for s in body]
  1462. return Module(new_body)
  1463. \end{lstlisting}
  1464. \fi}
  1465. \caption{A partial evaluator for \LangInt{}.}
  1466. \label{fig:pe-arith}
  1467. \end{figure}
  1468. To gain some confidence that the partial evaluator is correct, we can
  1469. test whether it produces programs that produce the same result as the
  1470. input programs. That is, we can test whether it satisfies Diagram
  1471. \ref{eq:compile-correct}.
  1472. %
  1473. {\if\edition\racketEd
  1474. The following code runs the partial evaluator on several examples and
  1475. tests the output program. The \texttt{parse-program} and
  1476. \texttt{assert} functions are defined in
  1477. Appendix~\ref{appendix:utilities}.\\
  1478. \begin{minipage}{1.0\textwidth}
  1479. \begin{lstlisting}
  1480. (define (test_pe p)
  1481. (assert "testing pe_Lint"
  1482. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1483. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1484. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1485. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1486. \end{lstlisting}
  1487. \end{minipage}
  1488. \fi}
  1489. % TODO: python version of testing the PE
  1490. \begin{exercise}\normalfont
  1491. Create three programs in the \LangInt{} language and test whether
  1492. partially evaluating them with \code{pe\_Lint} and then
  1493. interpreting them with \code{interp\_Lint} gives the same result
  1494. as directly interpreting them with \code{interp\_Lint}.
  1495. \end{exercise}
  1496. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1497. \chapter{Integers and Variables}
  1498. \label{ch:Lvar}
  1499. This chapter is about compiling a subset of
  1500. \racket{Racket}\python{Python} to x86-64 assembly
  1501. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1502. integer arithmetic and local variables. We often refer to x86-64
  1503. simply as x86. The chapter begins with a description of the
  1504. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1505. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1506. large so we discuss only the instructions needed for compiling
  1507. \LangVar{}. We introduce more x86 instructions in later chapters.
  1508. After introducing \LangVar{} and x86, we reflect on their differences
  1509. and come up with a plan to break down the translation from \LangVar{}
  1510. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1511. rest of the sections in this chapter give detailed hints regarding
  1512. each step. We hope to give enough hints that the well-prepared
  1513. reader, together with a few friends, can implement a compiler from
  1514. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1515. the scale of this first compiler, the instructor solution for the
  1516. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1517. code.
  1518. \section{The \LangVar{} Language}
  1519. \label{sec:s0}
  1520. \index{subject}{variable}
  1521. The \LangVar{} language extends the \LangInt{} language with
  1522. variables. The concrete syntax of the \LangVar{} language is defined
  1523. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1524. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1525. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1526. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1527. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1528. syntax of \LangVar{} includes the \racket{\key{Program}
  1529. struct}\python{\key{Module} instance} to mark the top of the
  1530. program.
  1531. %% The $\itm{info}$
  1532. %% field of the \key{Program} structure contains an \emph{association
  1533. %% list} (a list of key-value pairs) that is used to communicate
  1534. %% auxiliary data from one compiler pass the next.
  1535. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1536. exhibit several compilation techniques.
  1537. \newcommand{\LvarGrammarRacket}{
  1538. \begin{array}{rcl}
  1539. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1540. \end{array}
  1541. }
  1542. \newcommand{\LvarASTRacket}{
  1543. \begin{array}{rcl}
  1544. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1545. \end{array}
  1546. }
  1547. \newcommand{\LvarGrammarPython}{
  1548. \begin{array}{rcl}
  1549. \Exp &::=& \Var{} \\
  1550. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1551. \end{array}
  1552. }
  1553. \newcommand{\LvarASTPython}{
  1554. \begin{array}{rcl}
  1555. \Exp{} &::=& \VAR{\Var{}} \\
  1556. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1557. \end{array}
  1558. }
  1559. \begin{figure}[tp]
  1560. \centering
  1561. \fbox{
  1562. \begin{minipage}{0.96\textwidth}
  1563. {\if\edition\racketEd
  1564. \[
  1565. \begin{array}{l}
  1566. \gray{\LintGrammarRacket{}} \\ \hline
  1567. \LvarGrammarRacket{} \\
  1568. \begin{array}{rcl}
  1569. \LangVarM{} &::=& \Exp
  1570. \end{array}
  1571. \end{array}
  1572. \]
  1573. \fi}
  1574. {\if\edition\pythonEd
  1575. \[
  1576. \begin{array}{l}
  1577. \gray{\LintGrammarPython} \\ \hline
  1578. \LvarGrammarPython \\
  1579. \begin{array}{rcl}
  1580. \LangVarM{} &::=& \Stmt^{*}
  1581. \end{array}
  1582. \end{array}
  1583. \]
  1584. \fi}
  1585. \end{minipage}
  1586. }
  1587. \caption{The concrete syntax of \LangVar{}.}
  1588. \label{fig:Lvar-concrete-syntax}
  1589. \end{figure}
  1590. \begin{figure}[tp]
  1591. \centering
  1592. \fbox{
  1593. \begin{minipage}{0.96\textwidth}
  1594. {\if\edition\racketEd
  1595. \[
  1596. \begin{array}{l}
  1597. \gray{\LintASTRacket{}} \\ \hline
  1598. \LvarASTRacket \\
  1599. \begin{array}{rcl}
  1600. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1601. \end{array}
  1602. \end{array}
  1603. \]
  1604. \fi}
  1605. {\if\edition\pythonEd
  1606. \[
  1607. \begin{array}{l}
  1608. \gray{\LintASTPython}\\ \hline
  1609. \LvarASTPython \\
  1610. \begin{array}{rcl}
  1611. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1612. \end{array}
  1613. \end{array}
  1614. \]
  1615. \fi}
  1616. \end{minipage}
  1617. }
  1618. \caption{The abstract syntax of \LangVar{}.}
  1619. \label{fig:Lvar-syntax}
  1620. \end{figure}
  1621. {\if\edition\racketEd
  1622. Let us dive further into the syntax and semantics of the \LangVar{}
  1623. language. The \key{let} feature defines a variable for use within its
  1624. body and initializes the variable with the value of an expression.
  1625. The abstract syntax for \key{let} is defined in
  1626. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1627. \begin{lstlisting}
  1628. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1629. \end{lstlisting}
  1630. For example, the following program initializes \code{x} to $32$ and then
  1631. evaluates the body \code{(+ 10 x)}, producing $42$.
  1632. \begin{lstlisting}
  1633. (let ([x (+ 12 20)]) (+ 10 x))
  1634. \end{lstlisting}
  1635. \fi}
  1636. %
  1637. {\if\edition\pythonEd
  1638. %
  1639. The \LangVar{} language includes assignment statements, which define a
  1640. variable for use in later statements and initializes the variable with
  1641. the value of an expression. The abstract syntax for assignment is
  1642. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1643. assignment is
  1644. \begin{lstlisting}
  1645. |$\itm{var}$| = |$\itm{exp}$|
  1646. \end{lstlisting}
  1647. For example, the following program initializes the variable \code{x}
  1648. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1649. \begin{lstlisting}
  1650. x = 12 + 20
  1651. print(10 + x)
  1652. \end{lstlisting}
  1653. \fi}
  1654. {\if\edition\racketEd
  1655. %
  1656. When there are multiple \key{let}'s for the same variable, the closest
  1657. enclosing \key{let} is used. That is, variable definitions overshadow
  1658. prior definitions. Consider the following program with two \key{let}'s
  1659. that define two variables named \code{x}. Can you figure out the
  1660. result?
  1661. \begin{lstlisting}
  1662. (let ([x 32]) (+ (let ([x 10]) x) x))
  1663. \end{lstlisting}
  1664. For the purposes of depicting which variable occurences correspond to
  1665. which definitions, the following shows the \code{x}'s annotated with
  1666. subscripts to distinguish them. Double check that your answer for the
  1667. above is the same as your answer for this annotated version of the
  1668. program.
  1669. \begin{lstlisting}
  1670. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1671. \end{lstlisting}
  1672. The initializing expression is always evaluated before the body of the
  1673. \key{let}, so in the following, the \key{read} for \code{x} is
  1674. performed before the \key{read} for \code{y}. Given the input
  1675. $52$ then $10$, the following produces $42$ (not $-42$).
  1676. \begin{lstlisting}
  1677. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1678. \end{lstlisting}
  1679. \fi}
  1680. \subsection{Extensible Interpreters via Method Overriding}
  1681. \label{sec:extensible-interp}
  1682. To prepare for discussing the interpreter of \LangVar{}, we explain
  1683. why we implement it in an object-oriented style. Throughout this book
  1684. we define many interpreters, one for each of language that we
  1685. study. Because each language builds on the prior one, there is a lot
  1686. of commonality between these interpreters. We want to write down the
  1687. common parts just once instead of many times. A naive
  1688. interpreter for \LangVar{} would handle the
  1689. \racket{cases for variables and \code{let}}
  1690. \python{case for variables}
  1691. but dispatch to an interpreter for \LangInt{}
  1692. in the rest of the cases. The following code sketches this idea. (We
  1693. explain the \code{env} parameter soon, in
  1694. Section~\ref{sec:interp-Lvar}.)
  1695. \begin{center}
  1696. {\if\edition\racketEd
  1697. \begin{minipage}{0.45\textwidth}
  1698. \begin{lstlisting}
  1699. (define ((interp_Lint env) e)
  1700. (match e
  1701. [(Prim '- (list e1))
  1702. (fx- 0 ((interp_Lint env) e1))]
  1703. ...))
  1704. \end{lstlisting}
  1705. \end{minipage}
  1706. \begin{minipage}{0.45\textwidth}
  1707. \begin{lstlisting}
  1708. (define ((interp_Lvar env) e)
  1709. (match e
  1710. [(Var x)
  1711. (dict-ref env x)]
  1712. [(Let x e body)
  1713. (define v ((interp_exp env) e))
  1714. (define env^ (dict-set env x v))
  1715. ((interp_exp env^) body)]
  1716. [else ((interp_Lint env) e)]))
  1717. \end{lstlisting}
  1718. \end{minipage}
  1719. \fi}
  1720. {\if\edition\pythonEd
  1721. \begin{minipage}{0.45\textwidth}
  1722. \begin{lstlisting}
  1723. def interp_Lint(e, env):
  1724. match e:
  1725. case UnaryOp(USub(), e1):
  1726. return - interp_Lint(e1, env)
  1727. ...
  1728. \end{lstlisting}
  1729. \end{minipage}
  1730. \begin{minipage}{0.45\textwidth}
  1731. \begin{lstlisting}
  1732. def interp_Lvar(e, env):
  1733. match e:
  1734. case Name(id):
  1735. return env[id]
  1736. case _:
  1737. return interp_Lint(e, env)
  1738. \end{lstlisting}
  1739. \end{minipage}
  1740. \fi}
  1741. \end{center}
  1742. The problem with this naive approach is that it does not handle
  1743. situations in which an \LangVar{} feature, such as a variable, is
  1744. nested inside an \LangInt{} feature, like the \code{-} operator, as in
  1745. the following program.
  1746. %
  1747. {\if\edition\racketEd
  1748. \begin{lstlisting}
  1749. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1750. \end{lstlisting}
  1751. \fi}
  1752. {\if\edition\pythonEd
  1753. \begin{lstlisting}
  1754. y = 10
  1755. print(-y)
  1756. \end{lstlisting}
  1757. \fi}
  1758. %
  1759. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1760. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1761. then it recursively calls \code{interp\_Lint} again on its argument.
  1762. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1763. an error!
  1764. To make our interpreters extensible we need something called
  1765. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1766. recursive knot is delayed to when the functions are
  1767. composed. Object-oriented languages provide open recursion via
  1768. method overriding\index{subject}{method overriding}. The
  1769. following code uses method overriding to interpret \LangInt{} and
  1770. \LangVar{} using
  1771. %
  1772. \racket{the
  1773. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1774. \index{subject}{class} feature of Racket}
  1775. %
  1776. \python{a Python \code{class} definition}.
  1777. %
  1778. We define one class for each language and define a method for
  1779. interpreting expressions inside each class. The class for \LangVar{}
  1780. inherits from the class for \LangInt{} and the method
  1781. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1782. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1783. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1784. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1785. \code{interp\_exp} in \LangInt{}.
  1786. \begin{center}
  1787. \hspace{-20pt}
  1788. {\if\edition\racketEd
  1789. \begin{minipage}{0.45\textwidth}
  1790. \begin{lstlisting}
  1791. (define interp_Lint_class
  1792. (class object%
  1793. (define/public ((interp_exp env) e)
  1794. (match e
  1795. [(Prim '- (list e))
  1796. (fx- 0 ((interp_exp env) e))]
  1797. ...))
  1798. ...))
  1799. \end{lstlisting}
  1800. \end{minipage}
  1801. \begin{minipage}{0.45\textwidth}
  1802. \begin{lstlisting}
  1803. (define interp_Lvar_class
  1804. (class interp_Lint_class
  1805. (define/override ((interp_exp env) e)
  1806. (match e
  1807. [(Var x)
  1808. (dict-ref env x)]
  1809. [(Let x e body)
  1810. (define v ((interp_exp env) e))
  1811. (define env^ (dict-set env x v))
  1812. ((interp_exp env^) body)]
  1813. [else
  1814. (super (interp_exp env) e)]))
  1815. ...
  1816. ))
  1817. \end{lstlisting}
  1818. \end{minipage}
  1819. \fi}
  1820. {\if\edition\pythonEd
  1821. \begin{minipage}{0.45\textwidth}
  1822. \begin{lstlisting}
  1823. class InterpLint:
  1824. def interp_exp(e):
  1825. match e:
  1826. case UnaryOp(USub(), e1):
  1827. return -self.interp_exp(e1)
  1828. ...
  1829. ...
  1830. \end{lstlisting}
  1831. \end{minipage}
  1832. \begin{minipage}{0.45\textwidth}
  1833. \begin{lstlisting}
  1834. def InterpLvar(InterpLint):
  1835. def interp_exp(e):
  1836. match e:
  1837. case Name(id):
  1838. return env[id]
  1839. case _:
  1840. return super().interp_exp(e)
  1841. ...
  1842. \end{lstlisting}
  1843. \end{minipage}
  1844. \fi}
  1845. \end{center}
  1846. Getting back to the troublesome example, repeated here:
  1847. {\if\edition\racketEd
  1848. \begin{lstlisting}
  1849. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1850. \end{lstlisting}
  1851. \fi}
  1852. {\if\edition\pythonEd
  1853. \begin{lstlisting}
  1854. y = 10
  1855. print(-y)
  1856. \end{lstlisting}
  1857. \fi}
  1858. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1859. \racket{on this expression,}
  1860. \python{on the \code{-y} expression,}
  1861. %
  1862. call it \code{e0}, by creating an object of the \LangVar{} class
  1863. and calling the \code{interp\_exp} method.
  1864. {\if\edition\racketEd
  1865. \begin{lstlisting}
  1866. (send (new interp_Lvar_class) interp_exp e0)
  1867. \end{lstlisting}
  1868. \fi}
  1869. {\if\edition\pythonEd
  1870. \begin{lstlisting}
  1871. InterpLvar().interp_exp(e0)
  1872. \end{lstlisting}
  1873. \fi}
  1874. \noindent To process the \code{-} operator, the default case of
  1875. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1876. method in \LangInt{}. But then for the recursive method call, it
  1877. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1878. \code{Var} node is handled correctly. Thus, method overriding gives us
  1879. the open recursion that we need to implement our interpreters in an
  1880. extensible way.
  1881. \subsection{Definitional Interpreter for \LangVar{}}
  1882. \label{sec:interp-Lvar}
  1883. {\if\edition\racketEd
  1884. \begin{figure}[tp]
  1885. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1886. \small
  1887. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1888. An \emph{association list} (alist) is a list of key-value pairs.
  1889. For example, we can map people to their ages with an alist.
  1890. \index{subject}{alist}\index{subject}{association list}
  1891. \begin{lstlisting}[basicstyle=\ttfamily]
  1892. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1893. \end{lstlisting}
  1894. The \emph{dictionary} interface is for mapping keys to values.
  1895. Every alist implements this interface. \index{subject}{dictionary} The package
  1896. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1897. provides many functions for working with dictionaries. Here
  1898. are a few of them:
  1899. \begin{description}
  1900. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1901. returns the value associated with the given $\itm{key}$.
  1902. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1903. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1904. but otherwise is the same as $\itm{dict}$.
  1905. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1906. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1907. of keys and values in $\itm{dict}$. For example, the following
  1908. creates a new alist in which the ages are incremented.
  1909. \end{description}
  1910. \vspace{-10pt}
  1911. \begin{lstlisting}[basicstyle=\ttfamily]
  1912. (for/list ([(k v) (in-dict ages)])
  1913. (cons k (add1 v)))
  1914. \end{lstlisting}
  1915. \end{tcolorbox}
  1916. %\end{wrapfigure}
  1917. \caption{Association lists implement the dictionary interface.}
  1918. \label{fig:alist}
  1919. \end{figure}
  1920. \fi}
  1921. Having justified the use of classes and methods to implement
  1922. interpreters, we revisit the definitional interpreter for \LangInt{}
  1923. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1924. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1925. interpreter for \LangVar{} adds two new \key{match} cases for
  1926. variables and \racket{\key{let}}\python{assignment}. For
  1927. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1928. value bound to a variable to all the uses of the variable. To
  1929. accomplish this, we maintain a mapping from variables to values
  1930. called an \emph{environment}\index{subject}{environment}.
  1931. %
  1932. We use%
  1933. %
  1934. \racket{an association list (alist)}
  1935. %
  1936. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1937. %
  1938. to represent the environment.
  1939. %
  1940. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1941. and the \code{racket/dict} package.}
  1942. %
  1943. The \code{interp\_exp} function takes the current environment,
  1944. \code{env}, as an extra parameter. When the interpreter encounters a
  1945. variable, it looks up the corresponding value in the dictionary.
  1946. %
  1947. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1948. initializing expression, extends the environment with the result
  1949. value bound to the variable, using \code{dict-set}, then evaluates
  1950. the body of the \key{Let}.}
  1951. %
  1952. \python{When the interpreter encounters an assignment, it evaluates
  1953. the initializing expression and then associates the resulting value
  1954. with the variable in the environment.}
  1955. \begin{figure}[tp]
  1956. {\if\edition\racketEd
  1957. \begin{lstlisting}
  1958. (define interp_Lint_class
  1959. (class object%
  1960. (super-new)
  1961. (define/public ((interp_exp env) e)
  1962. (match e
  1963. [(Int n) n]
  1964. [(Prim 'read '())
  1965. (define r (read))
  1966. (cond [(fixnum? r) r]
  1967. [else (error 'interp_exp "expected an integer" r)])]
  1968. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1969. [(Prim '+ (list e1 e2))
  1970. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]))
  1971. (define/public (interp_program p)
  1972. (match p
  1973. [(Program '() e) ((interp_exp '()) e)]))
  1974. ))
  1975. \end{lstlisting}
  1976. \fi}
  1977. {\if\edition\pythonEd
  1978. \begin{lstlisting}
  1979. class InterpLint:
  1980. def interp_exp(self, e, env):
  1981. match e:
  1982. case BinOp(left, Add(), right):
  1983. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1984. case UnaryOp(USub(), v):
  1985. return - self.interp_exp(v, env)
  1986. case Constant(value):
  1987. return value
  1988. case Call(Name('input_int'), []):
  1989. return int(input())
  1990. def interp_stmts(self, ss, env):
  1991. if len(ss) == 0:
  1992. return
  1993. match ss[0]:
  1994. case Expr(Call(Name('print'), [arg])):
  1995. print(self.interp_exp(arg, env), end='')
  1996. return self.interp_stmts(ss[1:], env)
  1997. case Expr(value):
  1998. self.interp_exp(value, env)
  1999. return self.interp_stmts(ss[1:], env)
  2000. def interp(self, p):
  2001. match p:
  2002. case Module(body):
  2003. self.interp_stmts(body, {})
  2004. def interp_Lint(p):
  2005. return InterpLint().interp(p)
  2006. \end{lstlisting}
  2007. \fi}
  2008. \caption{Interpreter for \LangInt{} as a class.}
  2009. \label{fig:interp-Lint-class}
  2010. \end{figure}
  2011. \begin{figure}[tp]
  2012. {\if\edition\racketEd
  2013. \begin{lstlisting}
  2014. (define interp_Lvar_class
  2015. (class interp_Lint_class
  2016. (super-new)
  2017. (define/override ((interp_exp env) e)
  2018. (match e
  2019. [(Var x) (dict-ref env x)]
  2020. [(Let x e body)
  2021. (define new-env (dict-set env x ((interp_exp env) e)))
  2022. ((interp_exp new-env) body)]
  2023. [else ((super interp-exp env) e)]))
  2024. ))
  2025. (define (interp_Lvar p)
  2026. (send (new interp_Lvar_class) interp_program p))
  2027. \end{lstlisting}
  2028. \fi}
  2029. {\if\edition\pythonEd
  2030. \begin{lstlisting}
  2031. class InterpLvar(InterpLint):
  2032. def interp_exp(self, e, env):
  2033. match e:
  2034. case Name(id):
  2035. return env[id]
  2036. case _:
  2037. return super().interp_exp(e, env)
  2038. def interp_stmts(self, ss, env):
  2039. if len(ss) == 0:
  2040. return
  2041. match ss[0]:
  2042. case Assign([lhs], value):
  2043. env[lhs.id] = self.interp_exp(value, env)
  2044. return self.interp_stmts(ss[1:], env)
  2045. case _:
  2046. return super().interp_stmts(ss, env)
  2047. def interp_Lvar(p):
  2048. return InterpLvar().interp(p)
  2049. \end{lstlisting}
  2050. \fi}
  2051. \caption{Interpreter for the \LangVar{} language.}
  2052. \label{fig:interp-Lvar}
  2053. \end{figure}
  2054. The goal for this chapter is to implement a compiler that translates
  2055. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2056. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2057. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2058. That is, they output the same integer $n$. We depict this correctness
  2059. criteria in the following diagram.
  2060. \[
  2061. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2062. \node (p1) at (0, 0) {$P_1$};
  2063. \node (p2) at (4, 0) {$P_2$};
  2064. \node (o) at (4, -2) {$n$};
  2065. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2066. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2067. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2068. \end{tikzpicture}
  2069. \]
  2070. In the next section we introduce the \LangXInt{} subset of x86 that
  2071. suffices for compiling \LangVar{}.
  2072. \section{The \LangXInt{} Assembly Language}
  2073. \label{sec:x86}
  2074. \index{subject}{x86}
  2075. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2076. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2077. assembler.
  2078. %
  2079. A program begins with a \code{main} label followed by a sequence of
  2080. instructions. The \key{globl} directive says that the \key{main}
  2081. procedure is externally visible, which is necessary so that the
  2082. operating system can call it.
  2083. %
  2084. An x86 program is stored in the computer's memory. For our purposes,
  2085. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2086. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2087. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2088. the address of the next instruction to be executed. For most
  2089. instructions, the program counter is incremented after the instruction
  2090. is executed, so it points to the next instruction in memory. Most x86
  2091. instructions take two operands, where each operand is either an
  2092. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2093. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2094. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2095. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2096. && \key{r8} \MID \key{r9} \MID \key{r10}
  2097. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2098. \MID \key{r14} \MID \key{r15}}
  2099. \begin{figure}[tp]
  2100. \fbox{
  2101. \begin{minipage}{0.96\textwidth}
  2102. {\if\edition\racketEd
  2103. \[
  2104. \begin{array}{lcl}
  2105. \Reg &::=& \allregisters{} \\
  2106. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2107. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2108. \key{subq} \; \Arg\key{,} \Arg \MID
  2109. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2110. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2111. \key{callq} \; \mathit{label} \MID
  2112. \key{retq} \MID
  2113. \key{jmp}\,\itm{label} \MID \\
  2114. && \itm{label}\key{:}\; \Instr \\
  2115. \LangXIntM{} &::= & \key{.globl main}\\
  2116. & & \key{main:} \; \Instr\ldots
  2117. \end{array}
  2118. \]
  2119. \fi}
  2120. {\if\edition\pythonEd
  2121. \[
  2122. \begin{array}{lcl}
  2123. \Reg &::=& \allregisters{} \\
  2124. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2125. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2126. \key{subq} \; \Arg\key{,} \Arg \MID
  2127. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2128. && \key{callq} \; \mathit{label} \MID
  2129. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2130. \LangXIntM{} &::= & \key{.globl main}\\
  2131. & & \key{main:} \; \Instr^{*}
  2132. \end{array}
  2133. \]
  2134. \fi}
  2135. \end{minipage}
  2136. }
  2137. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2138. \label{fig:x86-int-concrete}
  2139. \end{figure}
  2140. A register is a special kind of variable that holds a 64-bit
  2141. value. There are 16 general-purpose registers in the computer and
  2142. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2143. is written with a \key{\%} followed by the register name, such as
  2144. \key{\%rax}.
  2145. An immediate value is written using the notation \key{\$}$n$ where $n$
  2146. is an integer.
  2147. %
  2148. %
  2149. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2150. which obtains the address stored in register $r$ and then adds $n$
  2151. bytes to the address. The resulting address is used to load or store
  2152. to memory depending on whether it occurs as a source or destination
  2153. argument of an instruction.
  2154. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2155. source $s$ and destination $d$, applies the arithmetic operation, then
  2156. writes the result back to the destination $d$. \index{subject}{instruction}
  2157. %
  2158. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2159. stores the result in $d$.
  2160. %
  2161. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2162. specified by the label and $\key{retq}$ returns from a procedure to
  2163. its caller.
  2164. %
  2165. We discuss procedure calls in more detail later in this chapter and in
  2166. Chapter~\ref{ch:Lfun}.
  2167. %
  2168. The last letter \key{q} indicates that these instructions operate on
  2169. quadwords, i.e., 64-bit values.
  2170. %
  2171. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2172. counter to the address of the instruction after the specified
  2173. label.}
  2174. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2175. all of the x86 instructions used in this book.
  2176. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2177. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2178. \lstinline{movq $10, %rax}
  2179. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2180. adds $32$ to the $10$ in \key{rax} and
  2181. puts the result, $42$, back into \key{rax}.
  2182. %
  2183. The last instruction, \key{retq}, finishes the \key{main} function by
  2184. returning the integer in \key{rax} to the operating system. The
  2185. operating system interprets this integer as the program's exit
  2186. code. By convention, an exit code of 0 indicates that a program
  2187. completed successfully, and all other exit codes indicate various
  2188. errors.
  2189. %
  2190. \racket{Nevertheless, in this book we return the result of the program
  2191. as the exit code.}
  2192. \begin{figure}[tbp]
  2193. \begin{lstlisting}
  2194. .globl main
  2195. main:
  2196. movq $10, %rax
  2197. addq $32, %rax
  2198. retq
  2199. \end{lstlisting}
  2200. \caption{An x86 program that computes
  2201. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2202. \label{fig:p0-x86}
  2203. \end{figure}
  2204. We exhibit the use of memory for storing intermediate results in the
  2205. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2206. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2207. uses a region of memory called the \emph{procedure call stack} (or
  2208. \emph{stack} for
  2209. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2210. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2211. for each procedure call. The memory layout for an individual frame is
  2212. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2213. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2214. address of the item at the top of the stack. In general, we use the
  2215. term \emph{pointer}\index{subject}{pointer} for something that
  2216. contains an address. The stack grows downward in memory, so we
  2217. increase the size of the stack by subtracting from the stack pointer.
  2218. In the context of a procedure call, the \emph{return
  2219. address}\index{subject}{return address} is the instruction after the
  2220. call instruction on the caller side. The function call instruction,
  2221. \code{callq}, pushes the return address onto the stack prior to
  2222. jumping to the procedure. The register \key{rbp} is the \emph{base
  2223. pointer}\index{subject}{base pointer} and is used to access variables
  2224. that are stored in the frame of the current procedure call. The base
  2225. pointer of the caller is store after the return address. In
  2226. Figure~\ref{fig:frame} we number the variables from $1$ to
  2227. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2228. at $-16\key{(\%rbp)}$, etc.
  2229. \begin{figure}[tbp]
  2230. {\if\edition\racketEd
  2231. \begin{lstlisting}
  2232. start:
  2233. movq $10, -8(%rbp)
  2234. negq -8(%rbp)
  2235. movq -8(%rbp), %rax
  2236. addq $52, %rax
  2237. jmp conclusion
  2238. .globl main
  2239. main:
  2240. pushq %rbp
  2241. movq %rsp, %rbp
  2242. subq $16, %rsp
  2243. jmp start
  2244. conclusion:
  2245. addq $16, %rsp
  2246. popq %rbp
  2247. retq
  2248. \end{lstlisting}
  2249. \fi}
  2250. {\if\edition\pythonEd
  2251. \begin{lstlisting}
  2252. .globl main
  2253. main:
  2254. pushq %rbp
  2255. movq %rsp, %rbp
  2256. subq $16, %rsp
  2257. movq $10, -8(%rbp)
  2258. negq -8(%rbp)
  2259. movq -8(%rbp), %rax
  2260. addq $52, %rax
  2261. addq $16, %rsp
  2262. popq %rbp
  2263. retq
  2264. \end{lstlisting}
  2265. \fi}
  2266. \caption{An x86 program that computes
  2267. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2268. \label{fig:p1-x86}
  2269. \end{figure}
  2270. \begin{figure}[tbp]
  2271. \centering
  2272. \begin{tabular}{|r|l|} \hline
  2273. Position & Contents \\ \hline
  2274. 8(\key{\%rbp}) & return address \\
  2275. 0(\key{\%rbp}) & old \key{rbp} \\
  2276. -8(\key{\%rbp}) & variable $1$ \\
  2277. -16(\key{\%rbp}) & variable $2$ \\
  2278. \ldots & \ldots \\
  2279. 0(\key{\%rsp}) & variable $n$\\ \hline
  2280. \end{tabular}
  2281. \caption{Memory layout of a frame.}
  2282. \label{fig:frame}
  2283. \end{figure}
  2284. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2285. control is transferred from the operating system to the \code{main}
  2286. function. The operating system issues a \code{callq main} instruction
  2287. which pushes its return address on the stack and then jumps to
  2288. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2289. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2290. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2291. alignment (because the \code{callq} pushed the return address). The
  2292. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2293. for a procedure. The instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2294. pointer and then saves the base pointer of the caller at address
  2295. \code{rsp} on the stack. The next instruction \code{movq \%rsp, \%rbp} sets the
  2296. base pointer to the current stack pointer, which is pointing at the location
  2297. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2298. pointer down to make enough room for storing variables. This program
  2299. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2300. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2301. functions.
  2302. \racket{The last instruction of the prelude is \code{jmp start},
  2303. which transfers control to the instructions that were generated from
  2304. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2305. \racket{The first instruction under the \code{start} label is}
  2306. %
  2307. \python{The first instruction after the prelude is}
  2308. %
  2309. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2310. %
  2311. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2312. %
  2313. The next instruction moves the $-10$ from variable $1$ into the
  2314. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2315. the value in \code{rax}, updating its contents to $42$.
  2316. \racket{The three instructions under the label \code{conclusion} are the
  2317. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2318. %
  2319. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2320. \code{main} function consists of the last three instructions.}
  2321. %
  2322. The first two restore the \code{rsp} and \code{rbp} registers to the
  2323. state they were in at the beginning of the procedure. In particular,
  2324. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2325. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2326. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2327. \key{retq}, jumps back to the procedure that called this one and adds
  2328. $8$ to the stack pointer.
  2329. Our compiler needs a convenient representation for manipulating x86
  2330. programs, so we define an abstract syntax for x86 in
  2331. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2332. \LangXInt{}.
  2333. %
  2334. {\if\edition\pythonEd%
  2335. The main difference compared to the concrete syntax of \LangXInt{}
  2336. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2337. names, and register names are explicitly represented by strings.
  2338. \fi} %
  2339. {\if\edition\racketEd
  2340. The main difference compared to the concrete syntax of \LangXInt{}
  2341. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2342. front of every instruction. Instead instructions are grouped into
  2343. \emph{blocks}\index{subject}{block} with a
  2344. label associated with every block, which is why the \key{X86Program}
  2345. struct includes an alist mapping labels to blocks. The reason for this
  2346. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2347. introduce conditional branching. The \code{Block} structure includes
  2348. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2349. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2350. $\itm{info}$ field should contain an empty list.
  2351. \fi}
  2352. %
  2353. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2354. node includes an integer for representing the arity of the function,
  2355. i.e., the number of arguments, which is helpful to know during
  2356. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2357. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2358. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2359. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2360. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2361. \MID \skey{r14} \MID \skey{r15}}
  2362. \begin{figure}[tp]
  2363. \fbox{
  2364. \begin{minipage}{0.98\textwidth}
  2365. \small
  2366. {\if\edition\racketEd
  2367. \[
  2368. \begin{array}{lcl}
  2369. \Reg &::=& \allregisters{} \\
  2370. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2371. \MID \DEREF{\Reg}{\Int} \\
  2372. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2373. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2374. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2375. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2376. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2377. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2378. \MID \RETQ{}
  2379. \MID \JMP{\itm{label}} \\
  2380. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2381. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2382. \end{array}
  2383. \]
  2384. \fi}
  2385. {\if\edition\pythonEd
  2386. \[
  2387. \begin{array}{lcl}
  2388. \Reg &::=& \allastregisters{} \\
  2389. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2390. \MID \DEREF{\Reg}{\Int} \\
  2391. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2392. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2393. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2394. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2395. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2396. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2397. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2398. \end{array}
  2399. \]
  2400. \fi}
  2401. \end{minipage}
  2402. }
  2403. \caption{The abstract syntax of \LangXInt{} assembly.}
  2404. \label{fig:x86-int-ast}
  2405. \end{figure}
  2406. \section{Planning the trip to x86}
  2407. \label{sec:plan-s0-x86}
  2408. To compile one language to another it helps to focus on the
  2409. differences between the two languages because the compiler will need
  2410. to bridge those differences. What are the differences between \LangVar{}
  2411. and x86 assembly? Here are some of the most important ones:
  2412. \begin{enumerate}
  2413. \item x86 arithmetic instructions typically have two arguments and
  2414. update the second argument in place. In contrast, \LangVar{}
  2415. arithmetic operations take two arguments and produce a new value.
  2416. An x86 instruction may have at most one memory-accessing argument.
  2417. Furthermore, some x86 instructions place special restrictions on
  2418. their arguments.
  2419. \item An argument of an \LangVar{} operator can be a deeply-nested
  2420. expression, whereas x86 instructions restrict their arguments to be
  2421. integer constants, registers, and memory locations.
  2422. {\if\edition\racketEd
  2423. \item The order of execution in x86 is explicit in the syntax: a
  2424. sequence of instructions and jumps to labeled positions, whereas in
  2425. \LangVar{} the order of evaluation is a left-to-right depth-first
  2426. traversal of the abstract syntax tree.
  2427. \fi}
  2428. \item A program in \LangVar{} can have any number of variables
  2429. whereas x86 has 16 registers and the procedure call stack.
  2430. {\if\edition\racketEd
  2431. \item Variables in \LangVar{} can shadow other variables with the
  2432. same name. In x86, registers have unique names and memory locations
  2433. have unique addresses.
  2434. \fi}
  2435. \end{enumerate}
  2436. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2437. down the problem into several steps, dealing with the above
  2438. differences one at a time. Each of these steps is called a \emph{pass}
  2439. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2440. %
  2441. This terminology comes from the way each step passes over, that is,
  2442. traverses the AST of the program.
  2443. %
  2444. Furthermore, we follow the nanopass approach, which means we strive
  2445. for each pass to accomplish one clear objective (not two or three at
  2446. the same time).
  2447. %
  2448. We begin by sketching how we might implement each pass, and give them
  2449. names. We then figure out an ordering of the passes and the
  2450. input/output language for each pass. The very first pass has
  2451. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2452. its output language. In between we can choose whichever language is
  2453. most convenient for expressing the output of each pass, whether that
  2454. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2455. our own design. Finally, to implement each pass we write one
  2456. recursive function per non-terminal in the grammar of the input
  2457. language of the pass. \index{subject}{intermediate language}
  2458. Our compiler for \LangVar{} consists of the following passes.
  2459. %
  2460. \begin{description}
  2461. {\if\edition\racketEd
  2462. \item[\key{uniquify}] deals with the shadowing of variables by
  2463. renaming every variable to a unique name.
  2464. \fi}
  2465. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2466. of a primitive operation or function call is a variable or integer,
  2467. that is, an \emph{atomic} expression. We refer to non-atomic
  2468. expressions as \emph{complex}. This pass introduces temporary
  2469. variables to hold the results of complex
  2470. subexpressions.\index{subject}{atomic
  2471. expression}\index{subject}{complex expression}%
  2472. {\if\edition\racketEd
  2473. \item[\key{explicate\_control}] makes the execution order of the
  2474. program explicit. It converts the abstract syntax tree representation
  2475. into a control-flow graph in which each node contains a sequence of
  2476. statements and the edges between nodes say which nodes contain jumps
  2477. to other nodes.
  2478. \fi}
  2479. \item[\key{select\_instructions}] handles the difference between
  2480. \LangVar{} operations and x86 instructions. This pass converts each
  2481. \LangVar{} operation to a short sequence of instructions that
  2482. accomplishes the same task.
  2483. \item[\key{assign\_homes}] replaces variables with registers or stack
  2484. locations.
  2485. \end{description}
  2486. %
  2487. {\if\edition\racketEd
  2488. %
  2489. Our treatment of \code{remove\_complex\_operands} and
  2490. \code{explicate\_control} as separate passes is an example of the
  2491. nanopass approach\footnote{For analogous decompositions of the
  2492. translation into continuation passing style, see the work of
  2493. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2494. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2495. %
  2496. \fi}
  2497. The next question is: in what order should we apply these passes? This
  2498. question can be challenging because it is difficult to know ahead of
  2499. time which orderings will be better (easier to implement, produce more
  2500. efficient code, etc.) so oftentimes trial-and-error is
  2501. involved. Nevertheless, we can try to plan ahead and make educated
  2502. choices regarding the ordering.
  2503. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2504. \key{uniquify}? The \key{uniquify} pass should come first because
  2505. \key{explicate\_control} changes all the \key{let}-bound variables to
  2506. become local variables whose scope is the entire program, which would
  2507. confuse variables with the same name.}
  2508. %
  2509. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2510. because the later removes the \key{let} form, but it is convenient to
  2511. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2512. %
  2513. \racket{The ordering of \key{uniquify} with respect to
  2514. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2515. \key{uniquify} to come first.}
  2516. The \key{select\_instructions} and \key{assign\_homes} passes are
  2517. intertwined.
  2518. %
  2519. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2520. passing arguments to functions and it is preferable to assign
  2521. parameters to their corresponding registers. This suggests that it
  2522. would be better to start with the \key{select\_instructions} pass,
  2523. which generates the instructions for argument passing, before
  2524. performing register allocation.
  2525. %
  2526. On the other hand, by selecting instructions first we may run into a
  2527. dead end in \key{assign\_homes}. Recall that only one argument of an
  2528. x86 instruction may be a memory access but \key{assign\_homes} might
  2529. be forced to assign both arguments to memory locations.
  2530. %
  2531. A sophisticated approach is to iteratively repeat the two passes until
  2532. a solution is found. However, to reduce implementation complexity we
  2533. recommend placing \key{select\_instructions} first, followed by the
  2534. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2535. that uses a reserved register to fix outstanding problems.
  2536. \begin{figure}[tbp]
  2537. {\if\edition\racketEd
  2538. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2539. \node (Lvar) at (0,2) {\large \LangVar{}};
  2540. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2541. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2542. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2543. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2544. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2545. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2546. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2547. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2548. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2549. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2550. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2551. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2552. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2553. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2554. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2555. \end{tikzpicture}
  2556. \fi}
  2557. {\if\edition\pythonEd
  2558. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2559. \node (Lvar) at (0,2) {\large \LangVar{}};
  2560. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2561. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2562. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2563. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2564. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2565. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2566. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2567. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2568. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2569. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2570. \end{tikzpicture}
  2571. \fi}
  2572. \caption{Diagram of the passes for compiling \LangVar{}. }
  2573. \label{fig:Lvar-passes}
  2574. \end{figure}
  2575. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2576. passes and identifies the input and output language of each pass.
  2577. %
  2578. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2579. language, which extends \LangXInt{} with an unbounded number of
  2580. program-scope variables and removes the restrictions regarding
  2581. instruction arguments.
  2582. %
  2583. The last pass, \key{prelude\_and\_conclusion}, places the program
  2584. instructions inside a \code{main} function with instructions for the
  2585. prelude and conclusion.
  2586. %
  2587. \racket{In the following section we discuss the \LangCVar{}
  2588. intermediate language.}
  2589. %
  2590. The remainder of this chapter provides guidance on the implementation
  2591. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2592. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2593. %% are programs that are still in the \LangVar{} language, though the
  2594. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2595. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2596. %% %
  2597. %% The output of \code{explicate\_control} is in an intermediate language
  2598. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2599. %% syntax, which we introduce in the next section. The
  2600. %% \key{select-instruction} pass translates from \LangCVar{} to
  2601. %% \LangXVar{}. The \key{assign-homes} and
  2602. %% \key{patch-instructions}
  2603. %% passes input and output variants of x86 assembly.
  2604. \newcommand{\CvarGrammarRacket}{
  2605. \begin{array}{lcl}
  2606. \Atm &::=& \Int \MID \Var \\
  2607. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2608. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2609. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2610. \end{array}
  2611. }
  2612. \newcommand{\CvarASTRacket}{
  2613. \begin{array}{lcl}
  2614. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2615. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2616. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2617. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2618. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2619. \end{array}
  2620. }
  2621. {\if\edition\racketEd
  2622. \subsection{The \LangCVar{} Intermediate Language}
  2623. The output of \code{explicate\_control} is similar to the $C$
  2624. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2625. categories for expressions and statements, so we name it \LangCVar{}.
  2626. This style of intermediate language is also known as
  2627. \emph{three-address code}, to emphasize that the typical form of a
  2628. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2629. addresses~\citep{Aho:2006wb}.
  2630. The concrete syntax for \LangCVar{} is defined in
  2631. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2632. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2633. %
  2634. The \LangCVar{} language supports the same operators as \LangVar{} but
  2635. the arguments of operators are restricted to atomic
  2636. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2637. assignment statements which can be executed in sequence using the
  2638. \key{Seq} form. A sequence of statements always ends with
  2639. \key{Return}, a guarantee that is baked into the grammar rules for
  2640. \itm{tail}. The naming of this non-terminal comes from the term
  2641. \emph{tail position}\index{subject}{tail position}, which refers to an
  2642. expression that is the last one to execute within a function.
  2643. A \LangCVar{} program consists of an alist mapping labels to
  2644. tails. This is more general than necessary for the present chapter, as
  2645. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2646. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2647. there will be just one label, \key{start}, and the whole program is
  2648. its tail.
  2649. %
  2650. The $\itm{info}$ field of the \key{CProgram} form, after the
  2651. \code{explicate\_control} pass, contains a mapping from the symbol
  2652. \key{locals} to a list of variables, that is, a list of all the
  2653. variables used in the program. At the start of the program, these
  2654. variables are uninitialized; they become initialized on their first
  2655. assignment.
  2656. \begin{figure}[tbp]
  2657. \fbox{
  2658. \begin{minipage}{0.96\textwidth}
  2659. \[
  2660. \begin{array}{l}
  2661. \CvarGrammarRacket \\
  2662. \begin{array}{lcl}
  2663. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2664. \end{array}
  2665. \end{array}
  2666. \]
  2667. \end{minipage}
  2668. }
  2669. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2670. \label{fig:c0-concrete-syntax}
  2671. \end{figure}
  2672. \begin{figure}[tbp]
  2673. \fbox{
  2674. \begin{minipage}{0.96\textwidth}
  2675. \[
  2676. \begin{array}{l}
  2677. \CvarASTRacket \\
  2678. \begin{array}{lcl}
  2679. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2680. \end{array}
  2681. \end{array}
  2682. \]
  2683. \end{minipage}
  2684. }
  2685. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2686. \label{fig:c0-syntax}
  2687. \end{figure}
  2688. The definitional interpreter for \LangCVar{} is in the support code,
  2689. in the file \code{interp-Cvar.rkt}.
  2690. \fi}
  2691. {\if\edition\racketEd
  2692. \section{Uniquify Variables}
  2693. \label{sec:uniquify-Lvar}
  2694. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2695. programs in which every \key{let} binds a unique variable name. For
  2696. example, the \code{uniquify} pass should translate the program on the
  2697. left into the program on the right.
  2698. \begin{transformation}
  2699. \begin{lstlisting}
  2700. (let ([x 32])
  2701. (+ (let ([x 10]) x) x))
  2702. \end{lstlisting}
  2703. \compilesto
  2704. \begin{lstlisting}
  2705. (let ([x.1 32])
  2706. (+ (let ([x.2 10]) x.2) x.1))
  2707. \end{lstlisting}
  2708. \end{transformation}
  2709. The following is another example translation, this time of a program
  2710. with a \key{let} nested inside the initializing expression of another
  2711. \key{let}.
  2712. \begin{transformation}
  2713. \begin{lstlisting}
  2714. (let ([x (let ([x 4])
  2715. (+ x 1))])
  2716. (+ x 2))
  2717. \end{lstlisting}
  2718. \compilesto
  2719. \begin{lstlisting}
  2720. (let ([x.2 (let ([x.1 4])
  2721. (+ x.1 1))])
  2722. (+ x.2 2))
  2723. \end{lstlisting}
  2724. \end{transformation}
  2725. We recommend implementing \code{uniquify} by creating a structurally
  2726. recursive function named \code{uniquify-exp} that mostly just copies
  2727. an expression. However, when encountering a \key{let}, it should
  2728. generate a unique name for the variable and associate the old name
  2729. with the new name in an alist.\footnote{The Racket function
  2730. \code{gensym} is handy for generating unique variable names.} The
  2731. \code{uniquify-exp} function needs to access this alist when it gets
  2732. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2733. for the alist.
  2734. The skeleton of the \code{uniquify-exp} function is shown in
  2735. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2736. convenient to partially apply it to an alist and then apply it to
  2737. different expressions, as in the last case for primitive operations in
  2738. Figure~\ref{fig:uniquify-Lvar}. The
  2739. %
  2740. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2741. %
  2742. form of Racket is useful for transforming each element of a list to
  2743. produce a new list.\index{subject}{for/list}
  2744. \begin{figure}[tbp]
  2745. \begin{lstlisting}
  2746. (define (uniquify-exp env)
  2747. (lambda (e)
  2748. (match e
  2749. [(Var x) ___]
  2750. [(Int n) (Int n)]
  2751. [(Let x e body) ___]
  2752. [(Prim op es)
  2753. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2754. (define (uniquify p)
  2755. (match p
  2756. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2757. \end{lstlisting}
  2758. \caption{Skeleton for the \key{uniquify} pass.}
  2759. \label{fig:uniquify-Lvar}
  2760. \end{figure}
  2761. \begin{exercise}
  2762. \normalfont % I don't like the italics for exercises. -Jeremy
  2763. Complete the \code{uniquify} pass by filling in the blanks in
  2764. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2765. variables and for the \key{let} form in the file \code{compiler.rkt}
  2766. in the support code.
  2767. \end{exercise}
  2768. \begin{exercise}
  2769. \normalfont % I don't like the italics for exercises. -Jeremy
  2770. \label{ex:Lvar}
  2771. Create five \LangVar{} programs that exercise the most interesting
  2772. parts of the \key{uniquify} pass, that is, the programs should include
  2773. \key{let} forms, variables, and variables that shadow each other.
  2774. The five programs should be placed in the subdirectory named
  2775. \key{tests} and the file names should start with \code{var\_test\_}
  2776. followed by a unique integer and end with the file extension
  2777. \key{.rkt}.
  2778. %
  2779. The \key{run-tests.rkt} script in the support code checks whether the
  2780. output programs produce the same result as the input programs. The
  2781. script uses the \key{interp-tests} function
  2782. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2783. your \key{uniquify} pass on the example programs. The \code{passes}
  2784. parameter of \key{interp-tests} is a list that should have one entry
  2785. for each pass in your compiler. For now, define \code{passes} to
  2786. contain just one entry for \code{uniquify} as shown below.
  2787. \begin{lstlisting}
  2788. (define passes
  2789. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2790. \end{lstlisting}
  2791. Run the \key{run-tests.rkt} script in the support code to check
  2792. whether the output programs produce the same result as the input
  2793. programs.
  2794. \end{exercise}
  2795. \fi}
  2796. \section{Remove Complex Operands}
  2797. \label{sec:remove-complex-opera-Lvar}
  2798. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2799. into a restricted form in which the arguments of operations are atomic
  2800. expressions. Put another way, this pass removes complex
  2801. operands\index{subject}{complex operand}, such as the expression
  2802. \racket{\code{(- 10)}}\python{\code{-10}}
  2803. in the program below. This is accomplished by introducing a new
  2804. temporary variable, assigning the complex operand to the new
  2805. variable, and then using the new variable in place of the complex
  2806. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2807. right.
  2808. {\if\edition\racketEd
  2809. \begin{transformation}
  2810. % var_test_19.rkt
  2811. \begin{lstlisting}
  2812. (let ([x (+ 42 (- 10))])
  2813. (+ x 10))
  2814. \end{lstlisting}
  2815. \compilesto
  2816. \begin{lstlisting}
  2817. (let ([x (let ([tmp.1 (- 10)])
  2818. (+ 42 tmp.1))])
  2819. (+ x 10))
  2820. \end{lstlisting}
  2821. \end{transformation}
  2822. \fi}
  2823. {\if\edition\pythonEd
  2824. \begin{transformation}
  2825. \begin{lstlisting}
  2826. x = 42 + -10
  2827. print(x + 10)
  2828. \end{lstlisting}
  2829. \compilesto
  2830. \begin{lstlisting}
  2831. tmp_0 = -10
  2832. x = 42 + tmp_0
  2833. tmp_1 = x + 10
  2834. print(tmp_1)
  2835. \end{lstlisting}
  2836. \end{transformation}
  2837. \fi}
  2838. \newcommand{\LvarMonadASTPython}{
  2839. \begin{array}{rcl}
  2840. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2841. \Exp{} &::=& \Atm \MID \READ{} \\
  2842. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2843. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2844. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2845. \end{array}
  2846. }
  2847. \begin{figure}[tp]
  2848. \centering
  2849. \fbox{
  2850. \begin{minipage}{0.96\textwidth}
  2851. {\if\edition\racketEd
  2852. \[
  2853. \begin{array}{rcl}
  2854. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2855. \Exp &::=& \Atm \MID \READ{} \\
  2856. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2857. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2858. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2859. \end{array}
  2860. \]
  2861. \fi}
  2862. {\if\edition\pythonEd
  2863. \[
  2864. \begin{array}{l}
  2865. \LvarMonadASTPython \\
  2866. \begin{array}{rcl}
  2867. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2868. \end{array}
  2869. \end{array}
  2870. \]
  2871. \fi}
  2872. \end{minipage}
  2873. }
  2874. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2875. atomic expressions.}
  2876. \label{fig:Lvar-anf-syntax}
  2877. \end{figure}
  2878. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2879. of this pass, the language \LangVarANF{}. The only difference is that
  2880. operator arguments are restricted to be atomic expressions that are
  2881. defined by the \Atm{} non-terminal. In particular, integer constants
  2882. and variables are atomic.
  2883. The atomic expressions are pure (they do not cause side-effects or
  2884. depend on them) whereas complex expressions may have side effects,
  2885. such as \READ{}. A language with this separation between pure versus
  2886. side-effecting expressions is said to be in monadic normal
  2887. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2888. in \LangVarANF{}. An important invariant of the
  2889. \code{remove\_complex\_operands} pass is that the relative ordering
  2890. among complex expressions is not changed, but the relative ordering
  2891. between atomic expressions and complex expressions can change and
  2892. often does. The reason that these changes are behaviour preserving is
  2893. that the atomic expressions are pure.
  2894. Another well-known form for intermediate languages is the
  2895. \emph{administrative normal form}
  2896. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2897. \index{subject}{administrative normal form} \index{subject}{ANF}
  2898. %
  2899. The \LangVarANF{} language is not quite in ANF because we allow the
  2900. right-hand side of a \code{let} to be a complex expression.
  2901. {\if\edition\racketEd
  2902. We recommend implementing this pass with two mutually recursive
  2903. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2904. \code{rco\_atom} to subexpressions that need to become atomic and to
  2905. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2906. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2907. returns an expression. The \code{rco\_atom} function returns two
  2908. things: an atomic expression and an alist mapping temporary variables to
  2909. complex subexpressions. You can return multiple things from a function
  2910. using Racket's \key{values} form and you can receive multiple things
  2911. from a function call using the \key{define-values} form.
  2912. Also, the
  2913. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2914. form is useful for applying a function to each element of a list, in
  2915. the case where the function returns multiple values.
  2916. \index{subject}{for/lists}
  2917. \fi}
  2918. %
  2919. {\if\edition\pythonEd
  2920. %
  2921. We recommend implementing this pass with an auxiliary method named
  2922. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2923. Boolean that specifies whether the expression needs to become atomic
  2924. or not. The \code{rco\_exp} method should return a pair consisting of
  2925. the new expression and a list of pairs, associating new temporary
  2926. variables with their initializing expressions.
  2927. %
  2928. \fi}
  2929. {\if\edition\racketEd
  2930. Returning to the example program with the expression \code{(+ 42 (-
  2931. 10))}, the subexpression \code{(- 10)} should be processed using the
  2932. \code{rco\_atom} function because it is an argument of the \code{+} and
  2933. therefore needs to become atomic. The output of \code{rco\_atom}
  2934. applied to \code{(- 10)} is as follows.
  2935. \begin{transformation}
  2936. \begin{lstlisting}
  2937. (- 10)
  2938. \end{lstlisting}
  2939. \compilesto
  2940. \begin{lstlisting}
  2941. tmp.1
  2942. ((tmp.1 . (- 10)))
  2943. \end{lstlisting}
  2944. \end{transformation}
  2945. \fi}
  2946. %
  2947. {\if\edition\pythonEd
  2948. %
  2949. Returning to the example program with the expression \code{42 + -10},
  2950. the subexpression \code{-10} should be processed using the
  2951. \code{rco\_exp} function with \code{True} as the second argument
  2952. because \code{-10} is an argument of the \code{+} operator and
  2953. therefore needs to become atomic. The output of \code{rco\_exp}
  2954. applied to \code{-10} is as follows.
  2955. \begin{transformation}
  2956. \begin{lstlisting}
  2957. -10
  2958. \end{lstlisting}
  2959. \compilesto
  2960. \begin{lstlisting}
  2961. tmp_1
  2962. [(tmp_1, -10)]
  2963. \end{lstlisting}
  2964. \end{transformation}
  2965. %
  2966. \fi}
  2967. Take special care of programs such as the following that
  2968. %
  2969. \racket{bind a variable to an atomic expression}
  2970. %
  2971. \python{assign an atomic expression to a variable}.
  2972. %
  2973. You should leave such \racket{variable bindings}\python{assignments}
  2974. unchanged, as shown in the program on the right\\
  2975. %
  2976. {\if\edition\racketEd
  2977. \begin{transformation}
  2978. % var_test_20.rkt
  2979. \begin{lstlisting}
  2980. (let ([a 42])
  2981. (let ([b a])
  2982. b))
  2983. \end{lstlisting}
  2984. \compilesto
  2985. \begin{lstlisting}
  2986. (let ([a 42])
  2987. (let ([b a])
  2988. b))
  2989. \end{lstlisting}
  2990. \end{transformation}
  2991. \fi}
  2992. {\if\edition\pythonEd
  2993. \begin{transformation}
  2994. \begin{lstlisting}
  2995. a = 42
  2996. b = a
  2997. print(b)
  2998. \end{lstlisting}
  2999. \compilesto
  3000. \begin{lstlisting}
  3001. a = 42
  3002. b = a
  3003. print(b)
  3004. \end{lstlisting}
  3005. \end{transformation}
  3006. \fi}
  3007. %
  3008. \noindent A careless implementation might produce the following output with
  3009. unnecessary temporary variables.
  3010. \begin{center}
  3011. \begin{minipage}{0.4\textwidth}
  3012. {\if\edition\racketEd
  3013. \begin{lstlisting}
  3014. (let ([tmp.1 42])
  3015. (let ([a tmp.1])
  3016. (let ([tmp.2 a])
  3017. (let ([b tmp.2])
  3018. b))))
  3019. \end{lstlisting}
  3020. \fi}
  3021. {\if\edition\pythonEd
  3022. \begin{lstlisting}
  3023. tmp_1 = 42
  3024. a = tmp_1
  3025. tmp_2 = a
  3026. b = tmp_2
  3027. print(b)
  3028. \end{lstlisting}
  3029. \fi}
  3030. \end{minipage}
  3031. \end{center}
  3032. \begin{exercise}
  3033. \normalfont
  3034. {\if\edition\racketEd
  3035. Implement the \code{remove\_complex\_operands} function in
  3036. \code{compiler.rkt}.
  3037. %
  3038. Create three new \LangVar{} programs that exercise the interesting
  3039. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3040. regarding file names described in Exercise~\ref{ex:Lvar}.
  3041. %
  3042. In the \code{run-tests.rkt} script, add the following entry to the
  3043. list of \code{passes} and then run the script to test your compiler.
  3044. \begin{lstlisting}
  3045. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  3046. \end{lstlisting}
  3047. While debugging your compiler, it is often useful to see the
  3048. intermediate programs that are output from each pass. To print the
  3049. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3050. \code{interp-tests} in \code{run-tests.rkt}.
  3051. \fi}
  3052. %
  3053. {\if\edition\pythonEd
  3054. Implement the \code{remove\_complex\_operands} pass in
  3055. \code{compiler.py}, creating auxiliary functions for each
  3056. non-terminal in the grammar, i.e., \code{rco\_exp}
  3057. and \code{rco\_stmt}. We recommend you use the function
  3058. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3059. \fi}
  3060. \end{exercise}
  3061. {\if\edition\pythonEd
  3062. \begin{exercise}
  3063. \normalfont % I don't like the italics for exercises. -Jeremy
  3064. \label{ex:Lvar}
  3065. Create five \LangVar{} programs that exercise the most interesting
  3066. parts of the \code{remove\_complex\_operands} pass. The five programs
  3067. should be placed in the subdirectory named \key{tests} and the file
  3068. names should start with \code{var\_test\_} followed by a unique
  3069. integer and end with the file extension \key{.py}.
  3070. %% The \key{run-tests.rkt} script in the support code checks whether the
  3071. %% output programs produce the same result as the input programs. The
  3072. %% script uses the \key{interp-tests} function
  3073. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3074. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3075. %% parameter of \key{interp-tests} is a list that should have one entry
  3076. %% for each pass in your compiler. For now, define \code{passes} to
  3077. %% contain just one entry for \code{uniquify} as shown below.
  3078. %% \begin{lstlisting}
  3079. %% (define passes
  3080. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3081. %% \end{lstlisting}
  3082. Run the \key{run-tests.py} script in the support code to check
  3083. whether the output programs produce the same result as the input
  3084. programs.
  3085. \end{exercise}
  3086. \fi}
  3087. {\if\edition\racketEd
  3088. \section{Explicate Control}
  3089. \label{sec:explicate-control-Lvar}
  3090. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3091. programs that make the order of execution explicit in their
  3092. syntax. For now this amounts to flattening \key{let} constructs into a
  3093. sequence of assignment statements. For example, consider the following
  3094. \LangVar{} program.\\
  3095. % var_test_11.rkt
  3096. \begin{minipage}{0.96\textwidth}
  3097. \begin{lstlisting}
  3098. (let ([y (let ([x 20])
  3099. (+ x (let ([x 22]) x)))])
  3100. y)
  3101. \end{lstlisting}
  3102. \end{minipage}\\
  3103. %
  3104. The output of the previous pass and of \code{explicate\_control} is
  3105. shown below. Recall that the right-hand-side of a \key{let} executes
  3106. before its body, so the order of evaluation for this program is to
  3107. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  3108. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  3109. output of \code{explicate\_control} makes this ordering explicit.
  3110. \begin{transformation}
  3111. \begin{lstlisting}
  3112. (let ([y (let ([x.1 20])
  3113. (let ([x.2 22])
  3114. (+ x.1 x.2)))])
  3115. y)
  3116. \end{lstlisting}
  3117. \compilesto
  3118. \begin{lstlisting}[language=C]
  3119. start:
  3120. x.1 = 20;
  3121. x.2 = 22;
  3122. y = (+ x.1 x.2);
  3123. return y;
  3124. \end{lstlisting}
  3125. \end{transformation}
  3126. \begin{figure}[tbp]
  3127. \begin{lstlisting}
  3128. (define (explicate_tail e)
  3129. (match e
  3130. [(Var x) ___]
  3131. [(Int n) (Return (Int n))]
  3132. [(Let x rhs body) ___]
  3133. [(Prim op es) ___]
  3134. [else (error "explicate_tail unhandled case" e)]))
  3135. (define (explicate_assign e x cont)
  3136. (match e
  3137. [(Var x) ___]
  3138. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3139. [(Let y rhs body) ___]
  3140. [(Prim op es) ___]
  3141. [else (error "explicate_assign unhandled case" e)]))
  3142. (define (explicate_control p)
  3143. (match p
  3144. [(Program info body) ___]))
  3145. \end{lstlisting}
  3146. \caption{Skeleton for the \code{explicate\_control} pass.}
  3147. \label{fig:explicate-control-Lvar}
  3148. \end{figure}
  3149. The organization of this pass depends on the notion of tail position
  3150. that we have alluded to earlier.
  3151. \begin{definition}
  3152. The following rules define when an expression is in \textbf{\emph{tail
  3153. position}}\index{subject}{tail position} for the language \LangVar{}.
  3154. \begin{enumerate}
  3155. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3156. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3157. \end{enumerate}
  3158. \end{definition}
  3159. We recommend implementing \code{explicate\_control} using two mutually
  3160. recursive functions, \code{explicate\_tail} and
  3161. \code{explicate\_assign}, as suggested in the skeleton code in
  3162. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3163. function should be applied to expressions in tail position whereas the
  3164. \code{explicate\_assign} should be applied to expressions that occur on
  3165. the right-hand-side of a \key{let}.
  3166. %
  3167. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3168. input and produces a \Tail{} in \LangCVar{} (see
  3169. Figure~\ref{fig:c0-syntax}).
  3170. %
  3171. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3172. the variable that it is to be assigned to, and a \Tail{} in
  3173. \LangCVar{} for the code that comes after the assignment. The
  3174. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3175. The \code{explicate\_assign} function is in accumulator-passing style:
  3176. the \code{cont} parameter is used for accumulating the output. This
  3177. accumulator-passing style plays an important role in how we generate
  3178. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3179. \begin{exercise}\normalfont
  3180. %
  3181. Implement the \code{explicate\_control} function in
  3182. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3183. exercise the code in \code{explicate\_control}.
  3184. %
  3185. In the \code{run-tests.rkt} script, add the following entry to the
  3186. list of \code{passes} and then run the script to test your compiler.
  3187. \begin{lstlisting}
  3188. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3189. \end{lstlisting}
  3190. \end{exercise}
  3191. \fi}
  3192. \section{Select Instructions}
  3193. \label{sec:select-Lvar}
  3194. \index{subject}{instruction selection}
  3195. In the \code{select\_instructions} pass we begin the work of
  3196. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3197. language of this pass is a variant of x86 that still uses variables,
  3198. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3199. non-terminal of the \LangXInt{} abstract syntax
  3200. (Figure~\ref{fig:x86-int-ast}).
  3201. \racket{We recommend implementing the
  3202. \code{select\_instructions} with three auxiliary functions, one for
  3203. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3204. $\Tail$.}
  3205. \python{We recommend implementing an auxiliary function
  3206. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3207. \racket{
  3208. The cases for $\Atm$ are straightforward; variables stay
  3209. the same and integer constants change to immediates:
  3210. $\INT{n}$ changes to $\IMM{n}$.}
  3211. We consider the cases for the $\Stmt$ non-terminal, starting with
  3212. arithmetic operations. For example, consider the addition operation
  3213. below, on the left side. There is an \key{addq} instruction in x86,
  3214. but it performs an in-place update. So we could move $\Arg_1$
  3215. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3216. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3217. $\Atm_1$ and $\Atm_2$ respectively.
  3218. \begin{transformation}
  3219. {\if\edition\racketEd
  3220. \begin{lstlisting}
  3221. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3222. \end{lstlisting}
  3223. \fi}
  3224. {\if\edition\pythonEd
  3225. \begin{lstlisting}
  3226. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3227. \end{lstlisting}
  3228. \fi}
  3229. \compilesto
  3230. \begin{lstlisting}
  3231. movq |$\Arg_1$|, |$\itm{var}$|
  3232. addq |$\Arg_2$|, |$\itm{var}$|
  3233. \end{lstlisting}
  3234. \end{transformation}
  3235. There are also cases that require special care to avoid generating
  3236. needlessly complicated code. For example, if one of the arguments of
  3237. the addition is the same variable as the left-hand side of the
  3238. assignment, as shown below, then there is no need for the extra move
  3239. instruction. The assignment statement can be translated into a single
  3240. \key{addq} instruction as follows.
  3241. \begin{transformation}
  3242. {\if\edition\racketEd
  3243. \begin{lstlisting}
  3244. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3245. \end{lstlisting}
  3246. \fi}
  3247. {\if\edition\pythonEd
  3248. \begin{lstlisting}
  3249. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3250. \end{lstlisting}
  3251. \fi}
  3252. \compilesto
  3253. \begin{lstlisting}
  3254. addq |$\Arg_1$|, |$\itm{var}$|
  3255. \end{lstlisting}
  3256. \end{transformation}
  3257. The \READOP{} operation does not have a direct counterpart in x86
  3258. assembly, so we provide this functionality with the function
  3259. \code{read\_int} in the file \code{runtime.c}, written in
  3260. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3261. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3262. system}, or simply the \emph{runtime} for short. When compiling your
  3263. generated x86 assembly code, you need to compile \code{runtime.c} to
  3264. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3265. \code{-c}) and link it into the executable. For our purposes of code
  3266. generation, all you need to do is translate an assignment of
  3267. \READOP{} into a call to the \code{read\_int} function followed by a
  3268. move from \code{rax} to the left-hand-side variable. (Recall that the
  3269. return value of a function goes into \code{rax}.)
  3270. \begin{transformation}
  3271. {\if\edition\racketEd
  3272. \begin{lstlisting}
  3273. |$\itm{var}$| = (read);
  3274. \end{lstlisting}
  3275. \fi}
  3276. {\if\edition\pythonEd
  3277. \begin{lstlisting}
  3278. |$\itm{var}$| = input_int();
  3279. \end{lstlisting}
  3280. \fi}
  3281. \compilesto
  3282. \begin{lstlisting}
  3283. callq read_int
  3284. movq %rax, |$\itm{var}$|
  3285. \end{lstlisting}
  3286. \end{transformation}
  3287. {\if\edition\pythonEd
  3288. %
  3289. Similarly, we translate the \code{print} operation, shown below, into
  3290. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3291. In x86, the first six arguments to functions are passed in registers,
  3292. with the first argument passed in register \code{rdi}. So we move the
  3293. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3294. \code{callq} instruction.
  3295. \begin{transformation}
  3296. \begin{lstlisting}
  3297. print(|$\Atm$|)
  3298. \end{lstlisting}
  3299. \compilesto
  3300. \begin{lstlisting}
  3301. movq |$\Arg$|, %rdi
  3302. callq print_int
  3303. \end{lstlisting}
  3304. \end{transformation}
  3305. %
  3306. \fi}
  3307. {\if\edition\racketEd
  3308. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3309. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3310. assignment to the \key{rax} register followed by a jump to the
  3311. conclusion of the program (so the conclusion needs to be labeled).
  3312. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3313. recursively and then append the resulting instructions.
  3314. \fi}
  3315. {\if\edition\pythonEd
  3316. We recommend that you use the function \code{utils.label\_name()} to
  3317. transform a string into an label argument suitably suitable for, e.g.,
  3318. the target of the \code{callq} instruction. This practice makes your
  3319. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3320. all labels.
  3321. \fi}
  3322. \begin{exercise}
  3323. \normalfont
  3324. {\if\edition\racketEd
  3325. Implement the \code{select\_instructions} pass in
  3326. \code{compiler.rkt}. Create three new example programs that are
  3327. designed to exercise all of the interesting cases in this pass.
  3328. %
  3329. In the \code{run-tests.rkt} script, add the following entry to the
  3330. list of \code{passes} and then run the script to test your compiler.
  3331. \begin{lstlisting}
  3332. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3333. \end{lstlisting}
  3334. \fi}
  3335. {\if\edition\pythonEd
  3336. Implement the \key{select\_instructions} pass in
  3337. \code{compiler.py}. Create three new example programs that are
  3338. designed to exercise all of the interesting cases in this pass.
  3339. Run the \code{run-tests.py} script to to check
  3340. whether the output programs produce the same result as the input
  3341. programs.
  3342. \fi}
  3343. \end{exercise}
  3344. \section{Assign Homes}
  3345. \label{sec:assign-Lvar}
  3346. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3347. \LangXVar{} programs that no longer use program variables.
  3348. Thus, the \key{assign-homes} pass is responsible for placing all of
  3349. the program variables in registers or on the stack. For runtime
  3350. efficiency, it is better to place variables in registers, but as there
  3351. are only 16 registers, some programs must necessarily resort to
  3352. placing some variables on the stack. In this chapter we focus on the
  3353. mechanics of placing variables on the stack. We study an algorithm for
  3354. placing variables in registers in
  3355. Chapter~\ref{ch:register-allocation-Lvar}.
  3356. Consider again the following \LangVar{} program from
  3357. Section~\ref{sec:remove-complex-opera-Lvar}.
  3358. % var_test_20.rkt
  3359. {\if\edition\racketEd
  3360. \begin{lstlisting}
  3361. (let ([a 42])
  3362. (let ([b a])
  3363. b))
  3364. \end{lstlisting}
  3365. \fi}
  3366. {\if\edition\pythonEd
  3367. \begin{lstlisting}
  3368. a = 42
  3369. b = a
  3370. print(b)
  3371. \end{lstlisting}
  3372. \fi}
  3373. %
  3374. The output of \code{select\_instructions} is shown below, on the left,
  3375. and the output of \code{assign\_homes} is on the right. In this
  3376. example, we assign variable \code{a} to stack location
  3377. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3378. \begin{transformation}
  3379. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3380. movq $42, a
  3381. movq a, b
  3382. movq b, %rax
  3383. \end{lstlisting}
  3384. \compilesto
  3385. %stack-space: 16
  3386. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3387. movq $42, -8(%rbp)
  3388. movq -8(%rbp), -16(%rbp)
  3389. movq -16(%rbp), %rax
  3390. \end{lstlisting}
  3391. \end{transformation}
  3392. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3393. \code{X86Program} node is an alist mapping all the variables in the
  3394. program to their types (for now just \code{Integer}). The
  3395. \code{assign\_homes} pass should replace all uses of those variables
  3396. with stack locations. As an aside, the \code{locals-types} entry is
  3397. computed by \code{type-check-Cvar} in the support code, which
  3398. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3399. which should be propagated to the \code{X86Program} node.}
  3400. %
  3401. \python{The \code{assign\_homes} pass should replace all uses of
  3402. variables with stack locations.}
  3403. %
  3404. In the process of assigning variables to stack locations, it is
  3405. convenient for you to compute and store the size of the frame (in
  3406. bytes) in%
  3407. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3408. %
  3409. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3410. which is needed later to generate the conclusion of the \code{main}
  3411. procedure. The x86-64 standard requires the frame size to be a
  3412. multiple of 16 bytes.\index{subject}{frame}
  3413. % TODO: store the number of variables instead? -Jeremy
  3414. \begin{exercise}\normalfont
  3415. Implement the \key{assign\_homes} pass in
  3416. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3417. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3418. grammar. We recommend that the auxiliary functions take an extra
  3419. parameter that maps variable names to homes (stack locations for now).
  3420. %
  3421. {\if\edition\racketEd
  3422. In the \code{run-tests.rkt} script, add the following entry to the
  3423. list of \code{passes} and then run the script to test your compiler.
  3424. \begin{lstlisting}
  3425. (list "assign homes" assign-homes interp_x86-0)
  3426. \end{lstlisting}
  3427. \fi}
  3428. {\if\edition\pythonEd
  3429. Run the \code{run-tests.py} script to to check
  3430. whether the output programs produce the same result as the input
  3431. programs.
  3432. \fi}
  3433. \end{exercise}
  3434. \section{Patch Instructions}
  3435. \label{sec:patch-s0}
  3436. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3437. \LangXInt{} by making sure that each instruction adheres to the
  3438. restriction that at most one argument of an instruction may be a
  3439. memory reference.
  3440. We return to the following example.\\
  3441. \begin{minipage}{0.5\textwidth}
  3442. % var_test_20.rkt
  3443. {\if\edition\racketEd
  3444. \begin{lstlisting}
  3445. (let ([a 42])
  3446. (let ([b a])
  3447. b))
  3448. \end{lstlisting}
  3449. \fi}
  3450. {\if\edition\pythonEd
  3451. \begin{lstlisting}
  3452. a = 42
  3453. b = a
  3454. print(b)
  3455. \end{lstlisting}
  3456. \fi}
  3457. \end{minipage}\\
  3458. The \key{assign\_homes} pass produces the following translation. \\
  3459. \begin{minipage}{0.5\textwidth}
  3460. {\if\edition\racketEd
  3461. \begin{lstlisting}
  3462. movq $42, -8(%rbp)
  3463. movq -8(%rbp), -16(%rbp)
  3464. movq -16(%rbp), %rax
  3465. \end{lstlisting}
  3466. \fi}
  3467. {\if\edition\pythonEd
  3468. \begin{lstlisting}
  3469. movq 42, -8(%rbp)
  3470. movq -8(%rbp), -16(%rbp)
  3471. movq -16(%rbp), %rdi
  3472. callq print_int
  3473. \end{lstlisting}
  3474. \fi}
  3475. \end{minipage}\\
  3476. The second \key{movq} instruction is problematic because both
  3477. arguments are stack locations. We suggest fixing this problem by
  3478. moving from the source location to the register \key{rax} and then
  3479. from \key{rax} to the destination location, as follows.
  3480. \begin{lstlisting}
  3481. movq -8(%rbp), %rax
  3482. movq %rax, -16(%rbp)
  3483. \end{lstlisting}
  3484. \begin{exercise}
  3485. \normalfont Implement the \key{patch\_instructions} pass in
  3486. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3487. Create three new example programs that are
  3488. designed to exercise all of the interesting cases in this pass.
  3489. %
  3490. {\if\edition\racketEd
  3491. In the \code{run-tests.rkt} script, add the following entry to the
  3492. list of \code{passes} and then run the script to test your compiler.
  3493. \begin{lstlisting}
  3494. (list "patch instructions" patch_instructions interp_x86-0)
  3495. \end{lstlisting}
  3496. \fi}
  3497. {\if\edition\pythonEd
  3498. Run the \code{run-tests.py} script to to check
  3499. whether the output programs produce the same result as the input
  3500. programs.
  3501. \fi}
  3502. \end{exercise}
  3503. \section{Generate Prelude and Conclusion}
  3504. \label{sec:print-x86}
  3505. \index{subject}{prelude}\index{subject}{conclusion}
  3506. The last step of the compiler from \LangVar{} to x86 is to generate
  3507. the \code{main} function with a prelude and conclusion wrapped around
  3508. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3509. discussed in Section~\ref{sec:x86}.
  3510. When running on Mac OS X, your compiler should prefix an underscore to
  3511. all labels, e.g., changing \key{main} to \key{\_main}.
  3512. %
  3513. \racket{The Racket call \code{(system-type 'os)} is useful for
  3514. determining which operating system the compiler is running on. It
  3515. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3516. %
  3517. \python{The Python \code{platform} library includes a \code{system()}
  3518. function that returns \code{'Linux'}, \code{'Windows'}, or
  3519. \code{'Darwin'} (for Mac).}
  3520. \begin{exercise}\normalfont
  3521. %
  3522. Implement the \key{prelude\_and\_conclusion} pass in
  3523. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3524. %
  3525. {\if\edition\racketEd
  3526. In the \code{run-tests.rkt} script, add the following entry to the
  3527. list of \code{passes} and then run the script to test your compiler.
  3528. \begin{lstlisting}
  3529. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3530. \end{lstlisting}
  3531. %
  3532. Uncomment the call to the \key{compiler-tests} function
  3533. (Appendix~\ref{appendix:utilities}), which tests your complete
  3534. compiler by executing the generated x86 code. It translates the x86
  3535. AST that you produce into a string by invoking the \code{print-x86}
  3536. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3537. the provided \key{runtime.c} file to \key{runtime.o} using
  3538. \key{gcc}. Run the script to test your compiler.
  3539. %
  3540. \fi}
  3541. {\if\edition\pythonEd
  3542. %
  3543. Run the \code{run-tests.py} script to to check whether the output
  3544. programs produce the same result as the input programs. That script
  3545. translates the x86 AST that you produce into a string by invoking the
  3546. \code{repr} method that is implemented by the x86 AST classes in
  3547. \code{x86\_ast.py}.
  3548. %
  3549. \fi}
  3550. \end{exercise}
  3551. \section{Challenge: Partial Evaluator for \LangVar{}}
  3552. \label{sec:pe-Lvar}
  3553. \index{subject}{partial evaluation}
  3554. This section describes two optional challenge exercises that involve
  3555. adapting and improving the partial evaluator for \LangInt{} that was
  3556. introduced in Section~\ref{sec:partial-evaluation}.
  3557. \begin{exercise}\label{ex:pe-Lvar}
  3558. \normalfont
  3559. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3560. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3561. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3562. %
  3563. \racket{\key{let} binding}\python{assignment}
  3564. %
  3565. to the \LangInt{} language, so you will need to add cases for them in
  3566. the \code{pe\_exp}
  3567. %
  3568. \racket{function}
  3569. %
  3570. \python{and \code{pe\_stmt} functions}.
  3571. %
  3572. Once complete, add the partial evaluation pass to the front of your
  3573. compiler and make sure that your compiler still passes all of the
  3574. tests.
  3575. \end{exercise}
  3576. \begin{exercise}
  3577. \normalfont
  3578. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3579. \code{pe\_add} auxiliary functions with functions that know more about
  3580. arithmetic. For example, your partial evaluator should translate
  3581. {\if\edition\racketEd
  3582. \[
  3583. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3584. \code{(+ 2 (read))}
  3585. \]
  3586. \fi}
  3587. {\if\edition\pythonEd
  3588. \[
  3589. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3590. \code{2 + input\_int()}
  3591. \]
  3592. \fi}
  3593. To accomplish this, the \code{pe\_exp} function should produce output
  3594. in the form of the $\itm{residual}$ non-terminal of the following
  3595. grammar. The idea is that when processing an addition expression, we
  3596. can always produce either 1) an integer constant, 2) an addition
  3597. expression with an integer constant on the left-hand side but not the
  3598. right-hand side, or 3) or an addition expression in which neither
  3599. subexpression is a constant.
  3600. {\if\edition\racketEd
  3601. \[
  3602. \begin{array}{lcl}
  3603. \itm{inert} &::=& \Var
  3604. \MID \LP\key{read}\RP
  3605. \MID \LP\key{-} ~\Var\RP
  3606. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3607. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3608. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3609. \itm{residual} &::=& \Int
  3610. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3611. \MID \itm{inert}
  3612. \end{array}
  3613. \]
  3614. \fi}
  3615. {\if\edition\pythonEd
  3616. \[
  3617. \begin{array}{lcl}
  3618. \itm{inert} &::=& \Var
  3619. \MID \key{input\_int}\LP\RP
  3620. \MID \key{-} \Var
  3621. \MID \key{-} \key{input\_int}\LP\RP
  3622. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3623. \itm{residual} &::=& \Int
  3624. \MID \Int ~ \key{+} ~ \itm{inert}
  3625. \MID \itm{inert}
  3626. \end{array}
  3627. \]
  3628. \fi}
  3629. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3630. inputs are $\itm{residual}$ expressions and they should return
  3631. $\itm{residual}$ expressions. Once the improvements are complete,
  3632. make sure that your compiler still passes all of the tests. After
  3633. all, fast code is useless if it produces incorrect results!
  3634. \end{exercise}
  3635. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3636. \chapter{Register Allocation}
  3637. \label{ch:register-allocation-Lvar}
  3638. \index{subject}{register allocation}
  3639. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3640. stack. In this chapter we learn how to improve the performance of the
  3641. generated code by assigning some variables to registers. The CPU can
  3642. access a register in a single cycle, whereas accessing the stack can
  3643. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3644. serves as a running example. The source program is on the left and the
  3645. output of instruction selection is on the right. The program is almost
  3646. in the x86 assembly language but it still uses variables.
  3647. \begin{figure}
  3648. \begin{minipage}{0.45\textwidth}
  3649. Example \LangVar{} program:
  3650. % var_test_28.rkt
  3651. {\if\edition\racketEd
  3652. \begin{lstlisting}
  3653. (let ([v 1])
  3654. (let ([w 42])
  3655. (let ([x (+ v 7)])
  3656. (let ([y x])
  3657. (let ([z (+ x w)])
  3658. (+ z (- y)))))))
  3659. \end{lstlisting}
  3660. \fi}
  3661. {\if\edition\pythonEd
  3662. \begin{lstlisting}
  3663. v = 1
  3664. w = 42
  3665. x = v + 7
  3666. y = x
  3667. z = x + w
  3668. print(z + (- y))
  3669. \end{lstlisting}
  3670. \fi}
  3671. \end{minipage}
  3672. \begin{minipage}{0.45\textwidth}
  3673. After instruction selection:
  3674. {\if\edition\racketEd
  3675. \begin{lstlisting}
  3676. locals-types:
  3677. x : Integer, y : Integer,
  3678. z : Integer, t : Integer,
  3679. v : Integer, w : Integer
  3680. start:
  3681. movq $1, v
  3682. movq $42, w
  3683. movq v, x
  3684. addq $7, x
  3685. movq x, y
  3686. movq x, z
  3687. addq w, z
  3688. movq y, t
  3689. negq t
  3690. movq z, %rax
  3691. addq t, %rax
  3692. jmp conclusion
  3693. \end{lstlisting}
  3694. \fi}
  3695. {\if\edition\pythonEd
  3696. \begin{lstlisting}
  3697. movq $1, v
  3698. movq $42, w
  3699. movq v, x
  3700. addq $7, x
  3701. movq x, y
  3702. movq x, z
  3703. addq w, z
  3704. movq y, tmp_0
  3705. negq tmp_0
  3706. movq z, tmp_1
  3707. addq tmp_0, tmp_1
  3708. movq tmp_1, %rdi
  3709. callq print_int
  3710. \end{lstlisting}
  3711. \fi}
  3712. \end{minipage}
  3713. \caption{A running example for register allocation.}
  3714. \label{fig:reg-eg}
  3715. \end{figure}
  3716. The goal of register allocation is to fit as many variables into
  3717. registers as possible. Some programs have more variables than
  3718. registers so we cannot always map each variable to a different
  3719. register. Fortunately, it is common for different variables to be
  3720. needed during different periods of time during program execution, and
  3721. in such cases several variables can be mapped to the same register.
  3722. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3723. After the variable \code{x} is moved to \code{z} it is no longer
  3724. needed. Variable \code{z}, on the other hand, is used only after this
  3725. point, so \code{x} and \code{z} could share the same register. The
  3726. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3727. where a variable is needed. Once we have that information, we compute
  3728. which variables are needed at the same time, i.e., which ones
  3729. \emph{interfere} with each other, and represent this relation as an
  3730. undirected graph whose vertices are variables and edges indicate when
  3731. two variables interfere (Section~\ref{sec:build-interference}). We
  3732. then model register allocation as a graph coloring problem
  3733. (Section~\ref{sec:graph-coloring}).
  3734. If we run out of registers despite these efforts, we place the
  3735. remaining variables on the stack, similar to what we did in
  3736. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3737. assigning a variable to a stack location. The decision to spill a
  3738. variable is handled as part of the graph coloring process.
  3739. We make the simplifying assumption that each variable is assigned to
  3740. one location (a register or stack address). A more sophisticated
  3741. approach is to assign a variable to one or more locations in different
  3742. regions of the program. For example, if a variable is used many times
  3743. in short sequence and then only used again after many other
  3744. instructions, it could be more efficient to assign the variable to a
  3745. register during the initial sequence and then move it to the stack for
  3746. the rest of its lifetime. We refer the interested reader to
  3747. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3748. approach.
  3749. % discuss prioritizing variables based on how much they are used.
  3750. \section{Registers and Calling Conventions}
  3751. \label{sec:calling-conventions}
  3752. \index{subject}{calling conventions}
  3753. As we perform register allocation, we need to be aware of the
  3754. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3755. functions calls are performed in x86.
  3756. %
  3757. Even though \LangVar{} does not include programmer-defined functions,
  3758. our generated code includes a \code{main} function that is called by
  3759. the operating system and our generated code contains calls to the
  3760. \code{read\_int} function.
  3761. Function calls require coordination between two pieces of code that
  3762. may be written by different programmers or generated by different
  3763. compilers. Here we follow the System V calling conventions that are
  3764. used by the GNU C compiler on Linux and
  3765. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3766. %
  3767. The calling conventions include rules about how functions share the
  3768. use of registers. In particular, the caller is responsible for freeing
  3769. up some registers prior to the function call for use by the callee.
  3770. These are called the \emph{caller-saved registers}
  3771. \index{subject}{caller-saved registers}
  3772. and they are
  3773. \begin{lstlisting}
  3774. rax rcx rdx rsi rdi r8 r9 r10 r11
  3775. \end{lstlisting}
  3776. On the other hand, the callee is responsible for preserving the values
  3777. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3778. which are
  3779. \begin{lstlisting}
  3780. rsp rbp rbx r12 r13 r14 r15
  3781. \end{lstlisting}
  3782. We can think about this caller/callee convention from two points of
  3783. view, the caller view and the callee view:
  3784. \begin{itemize}
  3785. \item The caller should assume that all the caller-saved registers get
  3786. overwritten with arbitrary values by the callee. On the other hand,
  3787. the caller can safely assume that all the callee-saved registers
  3788. contain the same values after the call that they did before the
  3789. call.
  3790. \item The callee can freely use any of the caller-saved registers.
  3791. However, if the callee wants to use a callee-saved register, the
  3792. callee must arrange to put the original value back in the register
  3793. prior to returning to the caller. This can be accomplished by saving
  3794. the value to the stack in the prelude of the function and restoring
  3795. the value in the conclusion of the function.
  3796. \end{itemize}
  3797. In x86, registers are also used for passing arguments to a function
  3798. and for the return value. In particular, the first six arguments to a
  3799. function are passed in the following six registers, in this order.
  3800. \begin{lstlisting}
  3801. rdi rsi rdx rcx r8 r9
  3802. \end{lstlisting}
  3803. If there are more than six arguments, then the convention is to use
  3804. space on the frame of the caller for the rest of the
  3805. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3806. need more than six arguments.
  3807. %
  3808. \racket{For now, the only function we care about is \code{read\_int}
  3809. and it takes zero arguments.}
  3810. %
  3811. \python{For now, the only functions we care about are \code{read\_int}
  3812. and \code{print\_int}, which take zero and one argument, respectively.}
  3813. %
  3814. The register \code{rax} is used for the return value of a function.
  3815. The next question is how these calling conventions impact register
  3816. allocation. Consider the \LangVar{} program in
  3817. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3818. example from the caller point of view and then from the callee point
  3819. of view.
  3820. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3821. is in use during the second call to \READOP{}, so we need to make sure
  3822. that the value in \code{x} does not get accidentally wiped out by the
  3823. call to \READOP{}. One obvious approach is to save all the values in
  3824. caller-saved registers to the stack prior to each function call, and
  3825. restore them after each call. That way, if the register allocator
  3826. chooses to assign \code{x} to a caller-saved register, its value will
  3827. be preserved across the call to \READOP{}. However, saving and
  3828. restoring to the stack is relatively slow. If \code{x} is not used
  3829. many times, it may be better to assign \code{x} to a stack location in
  3830. the first place. Or better yet, if we can arrange for \code{x} to be
  3831. placed in a callee-saved register, then it won't need to be saved and
  3832. restored during function calls.
  3833. The approach that we recommend for variables that are in use during a
  3834. function call is to either assign them to callee-saved registers or to
  3835. spill them to the stack. On the other hand, for variables that are not
  3836. in use during a function call, we try the following alternatives in
  3837. order 1) look for an available caller-saved register (to leave room
  3838. for other variables in the callee-saved register), 2) look for a
  3839. callee-saved register, and 3) spill the variable to the stack.
  3840. It is straightforward to implement this approach in a graph coloring
  3841. register allocator. First, we know which variables are in use during
  3842. every function call because we compute that information for every
  3843. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3844. we build the interference graph
  3845. (Section~\ref{sec:build-interference}), we can place an edge between
  3846. each of these call-live variables and the caller-saved registers in
  3847. the interference graph. This will prevent the graph coloring algorithm
  3848. from assigning them to caller-saved registers.
  3849. Returning to the example in
  3850. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3851. generated x86 code on the right-hand side. Notice that variable
  3852. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3853. is already in a safe place during the second call to
  3854. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3855. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3856. live-after set of a \code{callq} instruction.
  3857. Next we analyze the example from the callee point of view, focusing on
  3858. the prelude and conclusion of the \code{main} function. As usual the
  3859. prelude begins with saving the \code{rbp} register to the stack and
  3860. setting the \code{rbp} to the current stack pointer. We now know why
  3861. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3862. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3863. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3864. (\code{x}). The other callee-saved registers are not saved in the
  3865. prelude because they are not used. The prelude subtracts 8 bytes from
  3866. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3867. conclusion, we see that \code{rbx} is restored from the stack with a
  3868. \code{popq} instruction.
  3869. \index{subject}{prelude}\index{subject}{conclusion}
  3870. \begin{figure}[tp]
  3871. \begin{minipage}{0.45\textwidth}
  3872. Example \LangVar{} program:
  3873. %var_test_14.rkt
  3874. {\if\edition\racketEd
  3875. \begin{lstlisting}
  3876. (let ([x (read)])
  3877. (let ([y (read)])
  3878. (+ (+ x y) 42)))
  3879. \end{lstlisting}
  3880. \fi}
  3881. {\if\edition\pythonEd
  3882. \begin{lstlisting}
  3883. x = input_int()
  3884. y = input_int()
  3885. print((x + y) + 42)
  3886. \end{lstlisting}
  3887. \fi}
  3888. \end{minipage}
  3889. \begin{minipage}{0.45\textwidth}
  3890. Generated x86 assembly:
  3891. {\if\edition\racketEd
  3892. \begin{lstlisting}
  3893. start:
  3894. callq read_int
  3895. movq %rax, %rbx
  3896. callq read_int
  3897. movq %rax, %rcx
  3898. addq %rcx, %rbx
  3899. movq %rbx, %rax
  3900. addq $42, %rax
  3901. jmp _conclusion
  3902. .globl main
  3903. main:
  3904. pushq %rbp
  3905. movq %rsp, %rbp
  3906. pushq %rbx
  3907. subq $8, %rsp
  3908. jmp start
  3909. conclusion:
  3910. addq $8, %rsp
  3911. popq %rbx
  3912. popq %rbp
  3913. retq
  3914. \end{lstlisting}
  3915. \fi}
  3916. {\if\edition\pythonEd
  3917. \begin{lstlisting}
  3918. .globl main
  3919. main:
  3920. pushq %rbp
  3921. movq %rsp, %rbp
  3922. pushq %rbx
  3923. subq $8, %rsp
  3924. callq read_int
  3925. movq %rax, %rbx
  3926. callq read_int
  3927. movq %rax, %rcx
  3928. movq %rbx, %rdx
  3929. addq %rcx, %rdx
  3930. movq %rdx, %rcx
  3931. addq $42, %rcx
  3932. movq %rcx, %rdi
  3933. callq print_int
  3934. addq $8, %rsp
  3935. popq %rbx
  3936. popq %rbp
  3937. retq
  3938. \end{lstlisting}
  3939. \fi}
  3940. \end{minipage}
  3941. \caption{An example with function calls.}
  3942. \label{fig:example-calling-conventions}
  3943. \end{figure}
  3944. %\clearpage
  3945. \section{Liveness Analysis}
  3946. \label{sec:liveness-analysis-Lvar}
  3947. \index{subject}{liveness analysis}
  3948. The \code{uncover\_live} \racket{pass}\python{function}
  3949. performs \emph{liveness analysis}, that
  3950. is, it discovers which variables are in-use in different regions of a
  3951. program.
  3952. %
  3953. A variable or register is \emph{live} at a program point if its
  3954. current value is used at some later point in the program. We refer to
  3955. variables, stack locations, and registers collectively as
  3956. \emph{locations}.
  3957. %
  3958. Consider the following code fragment in which there are two writes to
  3959. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3960. \begin{center}
  3961. \begin{minipage}{0.96\textwidth}
  3962. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3963. movq $5, a
  3964. movq $30, b
  3965. movq a, c
  3966. movq $10, b
  3967. addq b, c
  3968. \end{lstlisting}
  3969. \end{minipage}
  3970. \end{center}
  3971. The answer is no because \code{a} is live from line 1 to 3 and
  3972. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3973. line 2 is never used because it is overwritten (line 4) before the
  3974. next read (line 5).
  3975. The live locations can be computed by traversing the instruction
  3976. sequence back to front (i.e., backwards in execution order). Let
  3977. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3978. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3979. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3980. locations before instruction $I_k$.
  3981. \racket{We recommend representing these
  3982. sets with the Racket \code{set} data structure described in
  3983. Figure~\ref{fig:set}.}
  3984. \python{We recommend representing these sets with the Python
  3985. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3986. data structure.}
  3987. {\if\edition\racketEd
  3988. \begin{figure}[tp]
  3989. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3990. \small
  3991. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3992. A \emph{set} is an unordered collection of elements without duplicates.
  3993. Here are some of the operations defined on sets.
  3994. \index{subject}{set}
  3995. \begin{description}
  3996. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3997. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3998. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3999. difference of the two sets.
  4000. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4001. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4002. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4003. \end{description}
  4004. \end{tcolorbox}
  4005. %\end{wrapfigure}
  4006. \caption{The \code{set} data structure.}
  4007. \label{fig:set}
  4008. \end{figure}
  4009. \fi}
  4010. The live locations after an instruction are always the same as the
  4011. live locations before the next instruction.
  4012. \index{subject}{live-after} \index{subject}{live-before}
  4013. \begin{equation} \label{eq:live-after-before-next}
  4014. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4015. \end{equation}
  4016. To start things off, there are no live locations after the last
  4017. instruction, so
  4018. \begin{equation}\label{eq:live-last-empty}
  4019. L_{\mathsf{after}}(n) = \emptyset
  4020. \end{equation}
  4021. We then apply the following rule repeatedly, traversing the
  4022. instruction sequence back to front.
  4023. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4024. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4025. \end{equation}
  4026. where $W(k)$ are the locations written to by instruction $I_k$ and
  4027. $R(k)$ are the locations read by instruction $I_k$.
  4028. {\if\edition\racketEd
  4029. There is a special case for \code{jmp} instructions. The locations
  4030. that are live before a \code{jmp} should be the locations in
  4031. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4032. maintaining an alist named \code{label->live} that maps each label to
  4033. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4034. now the only \code{jmp} in a \LangXVar{} program is the one at the
  4035. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  4036. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  4037. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4038. \fi}
  4039. Let us walk through the above example, applying these formulas
  4040. starting with the instruction on line 5. We collect the answers in
  4041. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4042. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4043. instruction (formula~\ref{eq:live-last-empty}). The
  4044. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4045. because it reads from variables \code{b} and \code{c}
  4046. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4047. \[
  4048. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4049. \]
  4050. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4051. the live-before set from line 5 to be the live-after set for this
  4052. instruction (formula~\ref{eq:live-after-before-next}).
  4053. \[
  4054. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4055. \]
  4056. This move instruction writes to \code{b} and does not read from any
  4057. variables, so we have the following live-before set
  4058. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4059. \[
  4060. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4061. \]
  4062. The live-before for instruction \code{movq a, c}
  4063. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4064. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4065. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4066. variable that is not live and does not read from a variable.
  4067. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4068. because it writes to variable \code{a}.
  4069. \begin{figure}[tbp]
  4070. \begin{minipage}{0.45\textwidth}
  4071. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4072. movq $5, a
  4073. movq $30, b
  4074. movq a, c
  4075. movq $10, b
  4076. addq b, c
  4077. \end{lstlisting}
  4078. \end{minipage}
  4079. \vrule\hspace{10pt}
  4080. \begin{minipage}{0.45\textwidth}
  4081. \begin{align*}
  4082. L_{\mathsf{before}}(1)= \emptyset,
  4083. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4084. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4085. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4086. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4087. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4088. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4089. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4090. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4091. L_{\mathsf{after}}(5)= \emptyset
  4092. \end{align*}
  4093. \end{minipage}
  4094. \caption{Example output of liveness analysis on a short example.}
  4095. \label{fig:liveness-example-0}
  4096. \end{figure}
  4097. \begin{exercise}\normalfont
  4098. Perform liveness analysis on the running example in
  4099. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4100. sets for each instruction. Compare your answers to the solution
  4101. shown in Figure~\ref{fig:live-eg}.
  4102. \end{exercise}
  4103. \begin{figure}[tp]
  4104. \hspace{20pt}
  4105. \begin{minipage}{0.45\textwidth}
  4106. {\if\edition\racketEd
  4107. \begin{lstlisting}
  4108. |$\{\ttm{rsp}\}$|
  4109. movq $1, v
  4110. |$\{\ttm{v},\ttm{rsp}\}$|
  4111. movq $42, w
  4112. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4113. movq v, x
  4114. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4115. addq $7, x
  4116. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4117. movq x, y
  4118. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4119. movq x, z
  4120. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4121. addq w, z
  4122. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4123. movq y, t
  4124. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4125. negq t
  4126. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4127. movq z, %rax
  4128. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4129. addq t, %rax
  4130. |$\{\ttm{rax},\ttm{rsp}\}$|
  4131. jmp conclusion
  4132. \end{lstlisting}
  4133. \fi}
  4134. {\if\edition\pythonEd
  4135. \begin{lstlisting}
  4136. movq $1, v
  4137. |$\{\ttm{v}\}$|
  4138. movq $42, w
  4139. |$\{\ttm{w}, \ttm{v}\}$|
  4140. movq v, x
  4141. |$\{\ttm{w}, \ttm{x}\}$|
  4142. addq $7, x
  4143. |$\{\ttm{w}, \ttm{x}\}$|
  4144. movq x, y
  4145. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4146. movq x, z
  4147. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4148. addq w, z
  4149. |$\{\ttm{y}, \ttm{z}\}$|
  4150. movq y, tmp_0
  4151. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4152. negq tmp_0
  4153. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4154. movq z, tmp_1
  4155. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4156. addq tmp_0, tmp_1
  4157. |$\{\ttm{tmp\_1}\}$|
  4158. movq tmp_1, %rdi
  4159. |$\{\ttm{rdi}\}$|
  4160. callq print_int
  4161. |$\{\}$|
  4162. \end{lstlisting}
  4163. \fi}
  4164. \end{minipage}
  4165. \caption{The running example annotated with live-after sets.}
  4166. \label{fig:live-eg}
  4167. \end{figure}
  4168. \begin{exercise}\normalfont
  4169. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4170. %
  4171. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4172. field of the \code{Block} structure.}
  4173. %
  4174. \python{Return a dictionary that maps each instruction to its
  4175. live-after set.}
  4176. %
  4177. \racket{We recommend creating an auxiliary function that takes a list
  4178. of instructions and an initial live-after set (typically empty) and
  4179. returns the list of live-after sets.}
  4180. %
  4181. We recommend creating auxiliary functions to 1) compute the set
  4182. of locations that appear in an \Arg{}, 2) compute the locations read
  4183. by an instruction (the $R$ function), and 3) the locations written by
  4184. an instruction (the $W$ function). The \code{callq} instruction should
  4185. include all of the caller-saved registers in its write-set $W$ because
  4186. the calling convention says that those registers may be written to
  4187. during the function call. Likewise, the \code{callq} instruction
  4188. should include the appropriate argument-passing registers in its
  4189. read-set $R$, depending on the arity of the function being
  4190. called. (This is why the abstract syntax for \code{callq} includes the
  4191. arity.)
  4192. \end{exercise}
  4193. %\clearpage
  4194. \section{Build the Interference Graph}
  4195. \label{sec:build-interference}
  4196. {\if\edition\racketEd
  4197. \begin{figure}[tp]
  4198. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4199. \small
  4200. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4201. A \emph{graph} is a collection of vertices and edges where each
  4202. edge connects two vertices. A graph is \emph{directed} if each
  4203. edge points from a source to a target. Otherwise the graph is
  4204. \emph{undirected}.
  4205. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4206. \begin{description}
  4207. %% We currently don't use directed graphs. We instead use
  4208. %% directed multi-graphs. -Jeremy
  4209. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4210. directed graph from a list of edges. Each edge is a list
  4211. containing the source and target vertex.
  4212. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4213. undirected graph from a list of edges. Each edge is represented by
  4214. a list containing two vertices.
  4215. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4216. inserts a vertex into the graph.
  4217. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4218. inserts an edge between the two vertices.
  4219. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4220. returns a sequence of vertices adjacent to the vertex.
  4221. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4222. returns a sequence of all vertices in the graph.
  4223. \end{description}
  4224. \end{tcolorbox}
  4225. %\end{wrapfigure}
  4226. \caption{The Racket \code{graph} package.}
  4227. \label{fig:graph}
  4228. \end{figure}
  4229. \fi}
  4230. Based on the liveness analysis, we know where each location is live.
  4231. However, during register allocation, we need to answer questions of
  4232. the specific form: are locations $u$ and $v$ live at the same time?
  4233. (And therefore cannot be assigned to the same register.) To make this
  4234. question more efficient to answer, we create an explicit data
  4235. structure, an \emph{interference graph}\index{subject}{interference
  4236. graph}. An interference graph is an undirected graph that has an
  4237. edge between two locations if they are live at the same time, that is,
  4238. if they interfere with each other.
  4239. %
  4240. \racket{We recommend using the Racket \code{graph} package
  4241. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4242. %
  4243. \python{We provide implementations of directed and undirected graph
  4244. data structures in the file \code{graph.py} of the support code.}
  4245. A straightforward way to compute the interference graph is to look at
  4246. the set of live locations between each instruction and add an edge to
  4247. the graph for every pair of variables in the same set. This approach
  4248. is less than ideal for two reasons. First, it can be expensive because
  4249. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4250. locations. Second, in the special case where two locations hold the
  4251. same value (because one was assigned to the other), they can be live
  4252. at the same time without interfering with each other.
  4253. A better way to compute the interference graph is to focus on
  4254. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4255. must not overwrite something in a live location. So for each
  4256. instruction, we create an edge between the locations being written to
  4257. and the live locations. (Except that one should not create self
  4258. edges.) Note that for the \key{callq} instruction, we consider all of
  4259. the caller-saved registers as being written to, so an edge is added
  4260. between every live variable and every caller-saved register. Also, for
  4261. \key{movq} there is the above-mentioned special case to deal with. If
  4262. a live variable $v$ is the same as the source of the \key{movq}, then
  4263. there is no need to add an edge between $v$ and the destination,
  4264. because they both hold the same value.
  4265. %
  4266. So we have the following two rules.
  4267. \begin{enumerate}
  4268. \item If instruction $I_k$ is a move instruction of the form
  4269. \key{movq} $s$\key{,} $d$, then for every $v \in
  4270. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4271. $(d,v)$.
  4272. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4273. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4274. $(d,v)$.
  4275. \end{enumerate}
  4276. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4277. the above rules to each instruction. We highlight a few of the
  4278. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4279. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4280. so \code{v} interferes with \code{rsp}.}
  4281. %
  4282. \python{The first instruction is \lstinline{movq $1, v} and the
  4283. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4284. no interference because $\ttm{v}$ is the destination of the move.}
  4285. %
  4286. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4287. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4288. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4289. %
  4290. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4291. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4292. $\ttm{x}$ interferes with \ttm{w}.}
  4293. %
  4294. \racket{The next instruction is \lstinline{movq x, y} and the
  4295. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4296. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4297. \ttm{x} because \ttm{x} is the source of the move and therefore
  4298. \ttm{x} and \ttm{y} hold the same value.}
  4299. %
  4300. \python{The next instruction is \lstinline{movq x, y} and the
  4301. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4302. applies, so \ttm{y} interferes with \ttm{w} but not
  4303. \ttm{x} because \ttm{x} is the source of the move and therefore
  4304. \ttm{x} and \ttm{y} hold the same value.}
  4305. %
  4306. Figure~\ref{fig:interference-results} lists the interference results
  4307. for all of the instructions and the resulting interference graph is
  4308. shown in Figure~\ref{fig:interfere}.
  4309. \begin{figure}[tbp]
  4310. \begin{quote}
  4311. {\if\edition\racketEd
  4312. \begin{tabular}{ll}
  4313. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4314. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4315. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4316. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4317. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4318. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4319. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4320. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4321. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4322. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4323. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4324. \lstinline!jmp conclusion!& no interference.
  4325. \end{tabular}
  4326. \fi}
  4327. {\if\edition\pythonEd
  4328. \begin{tabular}{ll}
  4329. \lstinline!movq $1, v!& no interference\\
  4330. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4331. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4332. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4333. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4334. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4335. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4336. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4337. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4338. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4339. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4340. \lstinline!movq tmp_1, %rdi! & no interference \\
  4341. \lstinline!callq print_int!& no interference.
  4342. \end{tabular}
  4343. \fi}
  4344. \end{quote}
  4345. \caption{Interference results for the running example.}
  4346. \label{fig:interference-results}
  4347. \end{figure}
  4348. \begin{figure}[tbp]
  4349. \large
  4350. {\if\edition\racketEd
  4351. \[
  4352. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4353. \node (rax) at (0,0) {$\ttm{rax}$};
  4354. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4355. \node (t1) at (0,2) {$\ttm{t}$};
  4356. \node (z) at (3,2) {$\ttm{z}$};
  4357. \node (x) at (6,2) {$\ttm{x}$};
  4358. \node (y) at (3,0) {$\ttm{y}$};
  4359. \node (w) at (6,0) {$\ttm{w}$};
  4360. \node (v) at (9,0) {$\ttm{v}$};
  4361. \draw (t1) to (rax);
  4362. \draw (t1) to (z);
  4363. \draw (z) to (y);
  4364. \draw (z) to (w);
  4365. \draw (x) to (w);
  4366. \draw (y) to (w);
  4367. \draw (v) to (w);
  4368. \draw (v) to (rsp);
  4369. \draw (w) to (rsp);
  4370. \draw (x) to (rsp);
  4371. \draw (y) to (rsp);
  4372. \path[-.,bend left=15] (z) edge node {} (rsp);
  4373. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4374. \draw (rax) to (rsp);
  4375. \end{tikzpicture}
  4376. \]
  4377. \fi}
  4378. {\if\edition\pythonEd
  4379. \[
  4380. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4381. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4382. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4383. \node (z) at (3,2) {$\ttm{z}$};
  4384. \node (x) at (6,2) {$\ttm{x}$};
  4385. \node (y) at (3,0) {$\ttm{y}$};
  4386. \node (w) at (6,0) {$\ttm{w}$};
  4387. \node (v) at (9,0) {$\ttm{v}$};
  4388. \draw (t0) to (t1);
  4389. \draw (t0) to (z);
  4390. \draw (z) to (y);
  4391. \draw (z) to (w);
  4392. \draw (x) to (w);
  4393. \draw (y) to (w);
  4394. \draw (v) to (w);
  4395. \end{tikzpicture}
  4396. \]
  4397. \fi}
  4398. \caption{The interference graph of the example program.}
  4399. \label{fig:interfere}
  4400. \end{figure}
  4401. %% Our next concern is to choose a data structure for representing the
  4402. %% interference graph. There are many choices for how to represent a
  4403. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4404. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4405. %% data structure is to study the algorithm that uses the data structure,
  4406. %% determine what operations need to be performed, and then choose the
  4407. %% data structure that provide the most efficient implementations of
  4408. %% those operations. Often times the choice of data structure can have an
  4409. %% effect on the time complexity of the algorithm, as it does here. If
  4410. %% you skim the next section, you will see that the register allocation
  4411. %% algorithm needs to ask the graph for all of its vertices and, given a
  4412. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4413. %% correct choice of graph representation is that of an adjacency
  4414. %% list. There are helper functions in \code{utilities.rkt} for
  4415. %% representing graphs using the adjacency list representation:
  4416. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4417. %% (Appendix~\ref{appendix:utilities}).
  4418. %% %
  4419. %% \margincomment{\footnotesize To do: change to use the
  4420. %% Racket graph library. \\ --Jeremy}
  4421. %% %
  4422. %% In particular, those functions use a hash table to map each vertex to
  4423. %% the set of adjacent vertices, and the sets are represented using
  4424. %% Racket's \key{set}, which is also a hash table.
  4425. \begin{exercise}\normalfont
  4426. \racket{Implement the compiler pass named \code{build\_interference} according
  4427. to the algorithm suggested above. We recommend using the Racket
  4428. \code{graph} package to create and inspect the interference graph.
  4429. The output graph of this pass should be stored in the $\itm{info}$ field of
  4430. the program, under the key \code{conflicts}.}
  4431. %
  4432. \python{Implement a function named \code{build\_interference}
  4433. according to the algorithm suggested above that
  4434. returns the interference graph.}
  4435. \end{exercise}
  4436. \section{Graph Coloring via Sudoku}
  4437. \label{sec:graph-coloring}
  4438. \index{subject}{graph coloring}
  4439. \index{subject}{Sudoku}
  4440. \index{subject}{color}
  4441. We come to the main event, mapping variables to registers and stack
  4442. locations. Variables that interfere with each other must be mapped to
  4443. different locations. In terms of the interference graph, this means
  4444. that adjacent vertices must be mapped to different locations. If we
  4445. think of locations as colors, the register allocation problem becomes
  4446. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4447. The reader may be more familiar with the graph coloring problem than he
  4448. or she realizes; the popular game of Sudoku is an instance of the
  4449. graph coloring problem. The following describes how to build a graph
  4450. out of an initial Sudoku board.
  4451. \begin{itemize}
  4452. \item There is one vertex in the graph for each Sudoku square.
  4453. \item There is an edge between two vertices if the corresponding squares
  4454. are in the same row, in the same column, or if the squares are in
  4455. the same $3\times 3$ region.
  4456. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4457. \item Based on the initial assignment of numbers to squares in the
  4458. Sudoku board, assign the corresponding colors to the corresponding
  4459. vertices in the graph.
  4460. \end{itemize}
  4461. If you can color the remaining vertices in the graph with the nine
  4462. colors, then you have also solved the corresponding game of Sudoku.
  4463. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4464. the corresponding graph with colored vertices. We map the Sudoku
  4465. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4466. sampling of the vertices (the colored ones) because showing edges for
  4467. all of the vertices would make the graph unreadable.
  4468. \begin{figure}[tbp]
  4469. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4470. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4471. \caption{A Sudoku game board and the corresponding colored graph.}
  4472. \label{fig:sudoku-graph}
  4473. \end{figure}
  4474. Some techniques for playing Sudoku correspond to heuristics used in
  4475. graph coloring algorithms. For example, one of the basic techniques
  4476. for Sudoku is called Pencil Marks. The idea is to use a process of
  4477. elimination to determine what numbers are no longer available for a
  4478. square and write down those numbers in the square (writing very
  4479. small). For example, if the number $1$ is assigned to a square, then
  4480. write the pencil mark $1$ in all the squares in the same row, column,
  4481. and region to indicate that $1$ is no longer an option for those other
  4482. squares.
  4483. %
  4484. The Pencil Marks technique corresponds to the notion of
  4485. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4486. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4487. are no longer available. In graph terminology, we have the following
  4488. definition:
  4489. \begin{equation*}
  4490. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4491. \text{ and } \mathrm{color}(v) = c \}
  4492. \end{equation*}
  4493. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4494. edge with $u$.
  4495. The Pencil Marks technique leads to a simple strategy for filling in
  4496. numbers: if there is a square with only one possible number left, then
  4497. choose that number! But what if there are no squares with only one
  4498. possibility left? One brute-force approach is to try them all: choose
  4499. the first one and if that ultimately leads to a solution, great. If
  4500. not, backtrack and choose the next possibility. One good thing about
  4501. Pencil Marks is that it reduces the degree of branching in the search
  4502. tree. Nevertheless, backtracking can be terribly time consuming. One
  4503. way to reduce the amount of backtracking is to use the
  4504. most-constrained-first heuristic (aka. minimum remaining
  4505. values)~\citep{Russell2003}. That is, when choosing a square, always
  4506. choose one with the fewest possibilities left (the vertex with the
  4507. highest saturation). The idea is that choosing highly constrained
  4508. squares earlier rather than later is better because later on there may
  4509. not be any possibilities left in the highly saturated squares.
  4510. However, register allocation is easier than Sudoku because the
  4511. register allocator can fall back to assigning variables to stack
  4512. locations when the registers run out. Thus, it makes sense to replace
  4513. backtracking with greedy search: make the best choice at the time and
  4514. keep going. We still wish to minimize the number of colors needed, so
  4515. we use the most-constrained-first heuristic in the greedy search.
  4516. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4517. algorithm for register allocation based on saturation and the
  4518. most-constrained-first heuristic. It is roughly equivalent to the
  4519. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4520. %,Gebremedhin:1999fk,Omari:2006uq
  4521. Just as in Sudoku, the algorithm represents colors with integers. The
  4522. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4523. for register allocation. The integers $k$ and larger correspond to
  4524. stack locations. The registers that are not used for register
  4525. allocation, such as \code{rax}, are assigned to negative integers. In
  4526. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4527. %% One might wonder why we include registers at all in the liveness
  4528. %% analysis and interference graph. For example, we never allocate a
  4529. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4530. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4531. %% to use register for passing arguments to functions, it will be
  4532. %% necessary for those registers to appear in the interference graph
  4533. %% because those registers will also be assigned to variables, and we
  4534. %% don't want those two uses to encroach on each other. Regarding
  4535. %% registers such as \code{rax} and \code{rsp} that are not used for
  4536. %% variables, we could omit them from the interference graph but that
  4537. %% would require adding special cases to our algorithm, which would
  4538. %% complicate the logic for little gain.
  4539. \begin{figure}[btp]
  4540. \centering
  4541. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4542. Algorithm: DSATUR
  4543. Input: a graph |$G$|
  4544. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4545. |$W \gets \mathrm{vertices}(G)$|
  4546. while |$W \neq \emptyset$| do
  4547. pick a vertex |$u$| from |$W$| with the highest saturation,
  4548. breaking ties randomly
  4549. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4550. |$\mathrm{color}[u] \gets c$|
  4551. |$W \gets W - \{u\}$|
  4552. \end{lstlisting}
  4553. \caption{The saturation-based greedy graph coloring algorithm.}
  4554. \label{fig:satur-algo}
  4555. \end{figure}
  4556. {\if\edition\racketEd
  4557. With the DSATUR algorithm in hand, let us return to the running
  4558. example and consider how to color the interference graph in
  4559. Figure~\ref{fig:interfere}.
  4560. %
  4561. We start by assigning the register nodes to their own color. For
  4562. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4563. assigned $-2$. The variables are not yet colored, so they are
  4564. annotated with a dash. We then update the saturation for vertices that
  4565. are adjacent to a register, obtaining the following annotated
  4566. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4567. it interferes with both \code{rax} and \code{rsp}.
  4568. \[
  4569. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4570. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4571. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4572. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4573. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4574. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4575. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4576. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4577. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4578. \draw (t1) to (rax);
  4579. \draw (t1) to (z);
  4580. \draw (z) to (y);
  4581. \draw (z) to (w);
  4582. \draw (x) to (w);
  4583. \draw (y) to (w);
  4584. \draw (v) to (w);
  4585. \draw (v) to (rsp);
  4586. \draw (w) to (rsp);
  4587. \draw (x) to (rsp);
  4588. \draw (y) to (rsp);
  4589. \path[-.,bend left=15] (z) edge node {} (rsp);
  4590. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4591. \draw (rax) to (rsp);
  4592. \end{tikzpicture}
  4593. \]
  4594. The algorithm says to select a maximally saturated vertex. So we pick
  4595. $\ttm{t}$ and color it with the first available integer, which is
  4596. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4597. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4598. \[
  4599. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4600. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4601. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4602. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4603. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4604. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4605. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4606. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4607. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4608. \draw (t1) to (rax);
  4609. \draw (t1) to (z);
  4610. \draw (z) to (y);
  4611. \draw (z) to (w);
  4612. \draw (x) to (w);
  4613. \draw (y) to (w);
  4614. \draw (v) to (w);
  4615. \draw (v) to (rsp);
  4616. \draw (w) to (rsp);
  4617. \draw (x) to (rsp);
  4618. \draw (y) to (rsp);
  4619. \path[-.,bend left=15] (z) edge node {} (rsp);
  4620. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4621. \draw (rax) to (rsp);
  4622. \end{tikzpicture}
  4623. \]
  4624. We repeat the process, selecting a maximally saturated vertex,
  4625. choosing is \code{z}, and color it with the first available number, which
  4626. is $1$. We add $1$ to the saturation for the neighboring vertices
  4627. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4628. \[
  4629. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4630. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4631. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4632. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4633. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4634. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4635. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4636. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4637. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4638. \draw (t1) to (rax);
  4639. \draw (t1) to (z);
  4640. \draw (z) to (y);
  4641. \draw (z) to (w);
  4642. \draw (x) to (w);
  4643. \draw (y) to (w);
  4644. \draw (v) to (w);
  4645. \draw (v) to (rsp);
  4646. \draw (w) to (rsp);
  4647. \draw (x) to (rsp);
  4648. \draw (y) to (rsp);
  4649. \path[-.,bend left=15] (z) edge node {} (rsp);
  4650. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4651. \draw (rax) to (rsp);
  4652. \end{tikzpicture}
  4653. \]
  4654. The most saturated vertices are now \code{w} and \code{y}. We color
  4655. \code{w} with the first available color, which is $0$.
  4656. \[
  4657. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4658. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4659. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4660. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4661. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4662. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4663. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4664. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4665. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4666. \draw (t1) to (rax);
  4667. \draw (t1) to (z);
  4668. \draw (z) to (y);
  4669. \draw (z) to (w);
  4670. \draw (x) to (w);
  4671. \draw (y) to (w);
  4672. \draw (v) to (w);
  4673. \draw (v) to (rsp);
  4674. \draw (w) to (rsp);
  4675. \draw (x) to (rsp);
  4676. \draw (y) to (rsp);
  4677. \path[-.,bend left=15] (z) edge node {} (rsp);
  4678. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4679. \draw (rax) to (rsp);
  4680. \end{tikzpicture}
  4681. \]
  4682. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4683. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4684. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4685. and \code{z}, whose colors are $0$ and $1$ respectively.
  4686. \[
  4687. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4688. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4689. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4690. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4691. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4692. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4693. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4694. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4695. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4696. \draw (t1) to (rax);
  4697. \draw (t1) to (z);
  4698. \draw (z) to (y);
  4699. \draw (z) to (w);
  4700. \draw (x) to (w);
  4701. \draw (y) to (w);
  4702. \draw (v) to (w);
  4703. \draw (v) to (rsp);
  4704. \draw (w) to (rsp);
  4705. \draw (x) to (rsp);
  4706. \draw (y) to (rsp);
  4707. \path[-.,bend left=15] (z) edge node {} (rsp);
  4708. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4709. \draw (rax) to (rsp);
  4710. \end{tikzpicture}
  4711. \]
  4712. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4713. \[
  4714. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4715. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4716. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4717. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4718. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4719. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4720. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4721. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4722. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4723. \draw (t1) to (rax);
  4724. \draw (t1) to (z);
  4725. \draw (z) to (y);
  4726. \draw (z) to (w);
  4727. \draw (x) to (w);
  4728. \draw (y) to (w);
  4729. \draw (v) to (w);
  4730. \draw (v) to (rsp);
  4731. \draw (w) to (rsp);
  4732. \draw (x) to (rsp);
  4733. \draw (y) to (rsp);
  4734. \path[-.,bend left=15] (z) edge node {} (rsp);
  4735. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4736. \draw (rax) to (rsp);
  4737. \end{tikzpicture}
  4738. \]
  4739. In the last step of the algorithm, we color \code{x} with $1$.
  4740. \[
  4741. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4742. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4743. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4744. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4745. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4746. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4747. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4748. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4749. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4750. \draw (t1) to (rax);
  4751. \draw (t1) to (z);
  4752. \draw (z) to (y);
  4753. \draw (z) to (w);
  4754. \draw (x) to (w);
  4755. \draw (y) to (w);
  4756. \draw (v) to (w);
  4757. \draw (v) to (rsp);
  4758. \draw (w) to (rsp);
  4759. \draw (x) to (rsp);
  4760. \draw (y) to (rsp);
  4761. \path[-.,bend left=15] (z) edge node {} (rsp);
  4762. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4763. \draw (rax) to (rsp);
  4764. \end{tikzpicture}
  4765. \]
  4766. So we obtain the following coloring:
  4767. \[
  4768. \{
  4769. \ttm{rax} \mapsto -1,
  4770. \ttm{rsp} \mapsto -2,
  4771. \ttm{t} \mapsto 0,
  4772. \ttm{z} \mapsto 1,
  4773. \ttm{x} \mapsto 1,
  4774. \ttm{y} \mapsto 2,
  4775. \ttm{w} \mapsto 0,
  4776. \ttm{v} \mapsto 1
  4777. \}
  4778. \]
  4779. \fi}
  4780. %
  4781. {\if\edition\pythonEd
  4782. %
  4783. With the DSATUR algorithm in hand, let us return to the running
  4784. example and consider how to color the interference graph in
  4785. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4786. to indicate that it has not yet been assigned a color. The saturation
  4787. sets are also shown for each node; all of them start as the empty set.
  4788. (We do not include the register nodes in the graph below because there
  4789. were no interference edges involving registers in this program, but in
  4790. general there can be.)
  4791. %
  4792. \[
  4793. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4794. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4795. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4796. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4797. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4798. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4799. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4800. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4801. \draw (t0) to (t1);
  4802. \draw (t0) to (z);
  4803. \draw (z) to (y);
  4804. \draw (z) to (w);
  4805. \draw (x) to (w);
  4806. \draw (y) to (w);
  4807. \draw (v) to (w);
  4808. \end{tikzpicture}
  4809. \]
  4810. The algorithm says to select a maximally saturated vertex, but they
  4811. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4812. then color it with the first available integer, which is $0$. We mark
  4813. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4814. they interfere with $\ttm{tmp\_0}$.
  4815. \[
  4816. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4817. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4818. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4819. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4820. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4821. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4822. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4823. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4824. \draw (t0) to (t1);
  4825. \draw (t0) to (z);
  4826. \draw (z) to (y);
  4827. \draw (z) to (w);
  4828. \draw (x) to (w);
  4829. \draw (y) to (w);
  4830. \draw (v) to (w);
  4831. \end{tikzpicture}
  4832. \]
  4833. We repeat the process. The most saturated vertices are \code{z} and
  4834. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4835. available number, which is $1$. We add $1$ to the saturation for the
  4836. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4837. \[
  4838. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4839. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4840. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4841. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4842. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4843. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4844. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4845. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4846. \draw (t0) to (t1);
  4847. \draw (t0) to (z);
  4848. \draw (z) to (y);
  4849. \draw (z) to (w);
  4850. \draw (x) to (w);
  4851. \draw (y) to (w);
  4852. \draw (v) to (w);
  4853. \end{tikzpicture}
  4854. \]
  4855. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4856. \code{y}. We color \code{w} with the first available color, which
  4857. is $0$.
  4858. \[
  4859. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4860. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4861. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4862. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4863. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4864. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4865. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4866. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4867. \draw (t0) to (t1);
  4868. \draw (t0) to (z);
  4869. \draw (z) to (y);
  4870. \draw (z) to (w);
  4871. \draw (x) to (w);
  4872. \draw (y) to (w);
  4873. \draw (v) to (w);
  4874. \end{tikzpicture}
  4875. \]
  4876. Now \code{y} is the most saturated, so we color it with $2$.
  4877. \[
  4878. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4879. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4880. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4881. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4882. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4883. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4884. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4885. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4886. \draw (t0) to (t1);
  4887. \draw (t0) to (z);
  4888. \draw (z) to (y);
  4889. \draw (z) to (w);
  4890. \draw (x) to (w);
  4891. \draw (y) to (w);
  4892. \draw (v) to (w);
  4893. \end{tikzpicture}
  4894. \]
  4895. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4896. We choose to color \code{v} with $1$.
  4897. \[
  4898. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4899. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4900. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4901. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4902. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4903. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4904. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4905. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4906. \draw (t0) to (t1);
  4907. \draw (t0) to (z);
  4908. \draw (z) to (y);
  4909. \draw (z) to (w);
  4910. \draw (x) to (w);
  4911. \draw (y) to (w);
  4912. \draw (v) to (w);
  4913. \end{tikzpicture}
  4914. \]
  4915. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4916. \[
  4917. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4918. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4919. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4920. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4921. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4922. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4923. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4924. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4925. \draw (t0) to (t1);
  4926. \draw (t0) to (z);
  4927. \draw (z) to (y);
  4928. \draw (z) to (w);
  4929. \draw (x) to (w);
  4930. \draw (y) to (w);
  4931. \draw (v) to (w);
  4932. \end{tikzpicture}
  4933. \]
  4934. So we obtain the following coloring:
  4935. \[
  4936. \{ \ttm{tmp\_0} \mapsto 0,
  4937. \ttm{tmp\_1} \mapsto 1,
  4938. \ttm{z} \mapsto 1,
  4939. \ttm{x} \mapsto 1,
  4940. \ttm{y} \mapsto 2,
  4941. \ttm{w} \mapsto 0,
  4942. \ttm{v} \mapsto 1 \}
  4943. \]
  4944. \fi}
  4945. We recommend creating an auxiliary function named \code{color\_graph}
  4946. that takes an interference graph and a list of all the variables in
  4947. the program. This function should return a mapping of variables to
  4948. their colors (represented as natural numbers). By creating this helper
  4949. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  4950. when we add support for functions.
  4951. To prioritize the processing of highly saturated nodes inside the
  4952. \code{color\_graph} function, we recommend using the priority queue
  4953. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4954. addition, you will need to maintain a mapping from variables to their
  4955. ``handles'' in the priority queue so that you can notify the priority
  4956. queue when their saturation changes.}
  4957. {\if\edition\racketEd
  4958. \begin{figure}[tp]
  4959. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4960. \small
  4961. \begin{tcolorbox}[title=Priority Queue]
  4962. A \emph{priority queue} is a collection of items in which the
  4963. removal of items is governed by priority. In a ``min'' queue,
  4964. lower priority items are removed first. An implementation is in
  4965. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4966. queue} \index{subject}{minimum priority queue}
  4967. \begin{description}
  4968. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4969. priority queue that uses the $\itm{cmp}$ predicate to determine
  4970. whether its first argument has lower or equal priority to its
  4971. second argument.
  4972. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4973. items in the queue.
  4974. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4975. the item into the queue and returns a handle for the item in the
  4976. queue.
  4977. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4978. the lowest priority.
  4979. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4980. notifies the queue that the priority has decreased for the item
  4981. associated with the given handle.
  4982. \end{description}
  4983. \end{tcolorbox}
  4984. %\end{wrapfigure}
  4985. \caption{The priority queue data structure.}
  4986. \label{fig:priority-queue}
  4987. \end{figure}
  4988. \fi}
  4989. With the coloring complete, we finalize the assignment of variables to
  4990. registers and stack locations. We map the first $k$ colors to the $k$
  4991. registers and the rest of the colors to stack locations. Suppose for
  4992. the moment that we have just one register to use for register
  4993. allocation, \key{rcx}. Then we have the following map from colors to
  4994. locations.
  4995. \[
  4996. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4997. \]
  4998. Composing this mapping with the coloring, we arrive at the following
  4999. assignment of variables to locations.
  5000. {\if\edition\racketEd
  5001. \begin{gather*}
  5002. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5003. \ttm{w} \mapsto \key{\%rcx}, \,
  5004. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5005. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5006. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5007. \ttm{t} \mapsto \key{\%rcx} \}
  5008. \end{gather*}
  5009. \fi}
  5010. {\if\edition\pythonEd
  5011. \begin{gather*}
  5012. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5013. \ttm{w} \mapsto \key{\%rcx}, \,
  5014. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5015. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5016. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5017. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5018. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5019. \end{gather*}
  5020. \fi}
  5021. Adapt the code from the \code{assign\_homes} pass
  5022. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  5023. assigned location. Applying the above assignment to our running
  5024. example, on the left, yields the program on the right.
  5025. % why frame size of 32? -JGS
  5026. \begin{center}
  5027. {\if\edition\racketEd
  5028. \begin{minipage}{0.3\textwidth}
  5029. \begin{lstlisting}
  5030. movq $1, v
  5031. movq $42, w
  5032. movq v, x
  5033. addq $7, x
  5034. movq x, y
  5035. movq x, z
  5036. addq w, z
  5037. movq y, t
  5038. negq t
  5039. movq z, %rax
  5040. addq t, %rax
  5041. jmp conclusion
  5042. \end{lstlisting}
  5043. \end{minipage}
  5044. $\Rightarrow\qquad$
  5045. \begin{minipage}{0.45\textwidth}
  5046. \begin{lstlisting}
  5047. movq $1, -8(%rbp)
  5048. movq $42, %rcx
  5049. movq -8(%rbp), -8(%rbp)
  5050. addq $7, -8(%rbp)
  5051. movq -8(%rbp), -16(%rbp)
  5052. movq -8(%rbp), -8(%rbp)
  5053. addq %rcx, -8(%rbp)
  5054. movq -16(%rbp), %rcx
  5055. negq %rcx
  5056. movq -8(%rbp), %rax
  5057. addq %rcx, %rax
  5058. jmp conclusion
  5059. \end{lstlisting}
  5060. \end{minipage}
  5061. \fi}
  5062. {\if\edition\pythonEd
  5063. \begin{minipage}{0.3\textwidth}
  5064. \begin{lstlisting}
  5065. movq $1, v
  5066. movq $42, w
  5067. movq v, x
  5068. addq $7, x
  5069. movq x, y
  5070. movq x, z
  5071. addq w, z
  5072. movq y, tmp_0
  5073. negq tmp_0
  5074. movq z, tmp_1
  5075. addq tmp_0, tmp_1
  5076. movq tmp_1, %rdi
  5077. callq print_int
  5078. \end{lstlisting}
  5079. \end{minipage}
  5080. $\Rightarrow\qquad$
  5081. \begin{minipage}{0.45\textwidth}
  5082. \begin{lstlisting}
  5083. movq $1, -8(%rbp)
  5084. movq $42, %rcx
  5085. movq -8(%rbp), -8(%rbp)
  5086. addq $7, -8(%rbp)
  5087. movq -8(%rbp), -16(%rbp)
  5088. movq -8(%rbp), -8(%rbp)
  5089. addq %rcx, -8(%rbp)
  5090. movq -16(%rbp), %rcx
  5091. negq %rcx
  5092. movq -8(%rbp), -8(%rbp)
  5093. addq %rcx, -8(%rbp)
  5094. movq -8(%rbp), %rdi
  5095. callq print_int
  5096. \end{lstlisting}
  5097. \end{minipage}
  5098. \fi}
  5099. \end{center}
  5100. \begin{exercise}\normalfont
  5101. %
  5102. Implement the compiler pass \code{allocate\_registers}.
  5103. %
  5104. Create five programs that exercise all aspects of the register
  5105. allocation algorithm, including spilling variables to the stack.
  5106. %
  5107. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  5108. \code{run-tests.rkt} script with the three new passes:
  5109. \code{uncover\_live}, \code{build\_interference}, and
  5110. \code{allocate\_registers}.
  5111. %
  5112. Temporarily remove the \code{print\_x86} pass from the list of passes
  5113. and the call to \code{compiler-tests}.
  5114. Run the script to test the register allocator.
  5115. }
  5116. %
  5117. \python{Run the \code{run-tests.py} script to to check whether the
  5118. output programs produce the same result as the input programs.}
  5119. \end{exercise}
  5120. \section{Patch Instructions}
  5121. \label{sec:patch-instructions}
  5122. The remaining step in the compilation to x86 is to ensure that the
  5123. instructions have at most one argument that is a memory access.
  5124. %
  5125. In the running example, the instruction \code{movq -8(\%rbp),
  5126. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5127. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5128. then move \code{rax} into \code{-16(\%rbp)}.
  5129. %
  5130. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5131. problematic, but they can simply be deleted. In general, we recommend
  5132. deleting all the trivial moves whose source and destination are the
  5133. same location.
  5134. %
  5135. The following is the output of \code{patch\_instructions} on the
  5136. running example.
  5137. \begin{center}
  5138. {\if\edition\racketEd
  5139. \begin{minipage}{0.4\textwidth}
  5140. \begin{lstlisting}
  5141. movq $1, -8(%rbp)
  5142. movq $42, %rcx
  5143. movq -8(%rbp), -8(%rbp)
  5144. addq $7, -8(%rbp)
  5145. movq -8(%rbp), -16(%rbp)
  5146. movq -8(%rbp), -8(%rbp)
  5147. addq %rcx, -8(%rbp)
  5148. movq -16(%rbp), %rcx
  5149. negq %rcx
  5150. movq -8(%rbp), %rax
  5151. addq %rcx, %rax
  5152. jmp conclusion
  5153. \end{lstlisting}
  5154. \end{minipage}
  5155. $\Rightarrow\qquad$
  5156. \begin{minipage}{0.45\textwidth}
  5157. \begin{lstlisting}
  5158. movq $1, -8(%rbp)
  5159. movq $42, %rcx
  5160. addq $7, -8(%rbp)
  5161. movq -8(%rbp), %rax
  5162. movq %rax, -16(%rbp)
  5163. addq %rcx, -8(%rbp)
  5164. movq -16(%rbp), %rcx
  5165. negq %rcx
  5166. movq -8(%rbp), %rax
  5167. addq %rcx, %rax
  5168. jmp conclusion
  5169. \end{lstlisting}
  5170. \end{minipage}
  5171. \fi}
  5172. {\if\edition\pythonEd
  5173. \begin{minipage}{0.4\textwidth}
  5174. \begin{lstlisting}
  5175. movq $1, -8(%rbp)
  5176. movq $42, %rcx
  5177. movq -8(%rbp), -8(%rbp)
  5178. addq $7, -8(%rbp)
  5179. movq -8(%rbp), -16(%rbp)
  5180. movq -8(%rbp), -8(%rbp)
  5181. addq %rcx, -8(%rbp)
  5182. movq -16(%rbp), %rcx
  5183. negq %rcx
  5184. movq -8(%rbp), -8(%rbp)
  5185. addq %rcx, -8(%rbp)
  5186. movq -8(%rbp), %rdi
  5187. callq print_int
  5188. \end{lstlisting}
  5189. \end{minipage}
  5190. $\Rightarrow\qquad$
  5191. \begin{minipage}{0.45\textwidth}
  5192. \begin{lstlisting}
  5193. movq $1, -8(%rbp)
  5194. movq $42, %rcx
  5195. addq $7, -8(%rbp)
  5196. movq -8(%rbp), %rax
  5197. movq %rax, -16(%rbp)
  5198. addq %rcx, -8(%rbp)
  5199. movq -16(%rbp), %rcx
  5200. negq %rcx
  5201. addq %rcx, -8(%rbp)
  5202. movq -8(%rbp), %rdi
  5203. callq print_int
  5204. \end{lstlisting}
  5205. \end{minipage}
  5206. \fi}
  5207. \end{center}
  5208. \begin{exercise}\normalfont
  5209. %
  5210. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5211. %
  5212. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5213. %in the \code{run-tests.rkt} script.
  5214. %
  5215. Run the script to test the \code{patch\_instructions} pass.
  5216. \end{exercise}
  5217. \section{Prelude and Conclusion}
  5218. \label{sec:print-x86-reg-alloc}
  5219. \index{subject}{calling conventions}
  5220. \index{subject}{prelude}\index{subject}{conclusion}
  5221. Recall that this pass generates the prelude and conclusion
  5222. instructions to satisfy the x86 calling conventions
  5223. (Section~\ref{sec:calling-conventions}). With the addition of the
  5224. register allocator, the callee-saved registers used by the register
  5225. allocator must be saved in the prelude and restored in the conclusion.
  5226. In the \code{allocate\_registers} pass,
  5227. %
  5228. \racket{add an entry to the \itm{info}
  5229. of \code{X86Program} named \code{used\_callee}}
  5230. %
  5231. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5232. %
  5233. that stores the set of callee-saved registers that were assigned to
  5234. variables. The \code{prelude\_and\_conclusion} pass can then access
  5235. this information to decide which callee-saved registers need to be
  5236. saved and restored.
  5237. %
  5238. When calculating the size of the frame to adjust the \code{rsp} in the
  5239. prelude, make sure to take into account the space used for saving the
  5240. callee-saved registers. Also, don't forget that the frame needs to be
  5241. a multiple of 16 bytes!
  5242. \racket{An overview of all of the passes involved in register
  5243. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5244. {\if\edition\racketEd
  5245. \begin{figure}[tbp]
  5246. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5247. \node (Lvar) at (0,2) {\large \LangVar{}};
  5248. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5249. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5250. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5251. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5252. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5253. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5254. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5255. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5256. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5257. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5258. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5259. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5260. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5261. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5262. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5263. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5264. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5265. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5266. \end{tikzpicture}
  5267. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5268. \label{fig:reg-alloc-passes}
  5269. \end{figure}
  5270. \fi}
  5271. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5272. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5273. use of registers and the stack, we limit the register allocator for
  5274. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5275. the prelude\index{subject}{prelude} of the \code{main} function, we
  5276. push \code{rbx} onto the stack because it is a callee-saved register
  5277. and it was assigned to variable by the register allocator. We
  5278. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5279. reserve space for the one spilled variable. After that subtraction,
  5280. the \code{rsp} is aligned to 16 bytes.
  5281. Moving on to the program proper, we see how the registers were
  5282. allocated.
  5283. %
  5284. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5285. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5286. %
  5287. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5288. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5289. were assigned to \code{rbx}.}
  5290. %
  5291. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5292. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5293. callee-save register \code{rbx} onto the stack. The spilled variables
  5294. must be placed lower on the stack than the saved callee-save
  5295. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5296. \code{-16(\%rbp)}.
  5297. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5298. done in the prelude. We move the stack pointer up by \code{8} bytes
  5299. (the room for spilled variables), then we pop the old values of
  5300. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5301. \code{retq} to return control to the operating system.
  5302. \begin{figure}[tbp]
  5303. % var_test_28.rkt
  5304. % (use-minimal-set-of-registers! #t)
  5305. % and only rbx rcx
  5306. % tmp 0 rbx
  5307. % z 1 rcx
  5308. % y 0 rbx
  5309. % w 2 16(%rbp)
  5310. % v 0 rbx
  5311. % x 0 rbx
  5312. {\if\edition\racketEd
  5313. \begin{lstlisting}
  5314. start:
  5315. movq $1, %rbx
  5316. movq $42, -16(%rbp)
  5317. addq $7, %rbx
  5318. movq %rbx, %rcx
  5319. addq -16(%rbp), %rcx
  5320. negq %rbx
  5321. movq %rcx, %rax
  5322. addq %rbx, %rax
  5323. jmp conclusion
  5324. .globl main
  5325. main:
  5326. pushq %rbp
  5327. movq %rsp, %rbp
  5328. pushq %rbx
  5329. subq $8, %rsp
  5330. jmp start
  5331. conclusion:
  5332. addq $8, %rsp
  5333. popq %rbx
  5334. popq %rbp
  5335. retq
  5336. \end{lstlisting}
  5337. \fi}
  5338. {\if\edition\pythonEd
  5339. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5340. \begin{lstlisting}
  5341. .globl main
  5342. main:
  5343. pushq %rbp
  5344. movq %rsp, %rbp
  5345. pushq %rbx
  5346. subq $8, %rsp
  5347. movq $1, %rcx
  5348. movq $42, %rbx
  5349. addq $7, %rcx
  5350. movq %rcx, -16(%rbp)
  5351. addq %rbx, -16(%rbp)
  5352. negq %rcx
  5353. movq -16(%rbp), %rbx
  5354. addq %rcx, %rbx
  5355. movq %rbx, %rdi
  5356. callq print_int
  5357. addq $8, %rsp
  5358. popq %rbx
  5359. popq %rbp
  5360. retq
  5361. \end{lstlisting}
  5362. \fi}
  5363. \caption{The x86 output from the running example
  5364. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5365. and \code{rcx}.}
  5366. \label{fig:running-example-x86}
  5367. \end{figure}
  5368. \begin{exercise}\normalfont
  5369. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5370. %
  5371. \racket{
  5372. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5373. list of passes and the call to \code{compiler-tests}.}
  5374. %
  5375. Run the script to test the complete compiler for \LangVar{} that
  5376. performs register allocation.
  5377. \end{exercise}
  5378. \section{Challenge: Move Biasing}
  5379. \label{sec:move-biasing}
  5380. \index{subject}{move biasing}
  5381. This section describes an enhancement to the register allocator,
  5382. called move biasing, for students who are looking for an extra
  5383. challenge.
  5384. {\if\edition\racketEd
  5385. To motivate the need for move biasing we return to the running example
  5386. but this time use all of the general purpose registers. So we have
  5387. the following mapping of color numbers to registers.
  5388. \[
  5389. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5390. \]
  5391. Using the same assignment of variables to color numbers that was
  5392. produced by the register allocator described in the last section, we
  5393. get the following program.
  5394. \begin{center}
  5395. \begin{minipage}{0.3\textwidth}
  5396. \begin{lstlisting}
  5397. movq $1, v
  5398. movq $42, w
  5399. movq v, x
  5400. addq $7, x
  5401. movq x, y
  5402. movq x, z
  5403. addq w, z
  5404. movq y, t
  5405. negq t
  5406. movq z, %rax
  5407. addq t, %rax
  5408. jmp conclusion
  5409. \end{lstlisting}
  5410. \end{minipage}
  5411. $\Rightarrow\qquad$
  5412. \begin{minipage}{0.45\textwidth}
  5413. \begin{lstlisting}
  5414. movq $1, %rdx
  5415. movq $42, %rcx
  5416. movq %rdx, %rdx
  5417. addq $7, %rdx
  5418. movq %rdx, %rsi
  5419. movq %rdx, %rdx
  5420. addq %rcx, %rdx
  5421. movq %rsi, %rcx
  5422. negq %rcx
  5423. movq %rdx, %rax
  5424. addq %rcx, %rax
  5425. jmp conclusion
  5426. \end{lstlisting}
  5427. \end{minipage}
  5428. \end{center}
  5429. In the above output code there are two \key{movq} instructions that
  5430. can be removed because their source and target are the same. However,
  5431. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5432. register, we could instead remove three \key{movq} instructions. We
  5433. can accomplish this by taking into account which variables appear in
  5434. \key{movq} instructions with which other variables.
  5435. \fi}
  5436. {\if\edition\pythonEd
  5437. %
  5438. To motivate the need for move biasing we return to the running example
  5439. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5440. remove three trivial move instructions from the running
  5441. example. However, we could remove another trivial move if we were able
  5442. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5443. We say that two variables $p$ and $q$ are \emph{move
  5444. related}\index{subject}{move related} if they participate together in
  5445. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5446. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5447. when there are multiple variables with the same saturation, prefer
  5448. variables that can be assigned to a color that is the same as the
  5449. color of a move related variable. Furthermore, when the register
  5450. allocator chooses a color for a variable, it should prefer a color
  5451. that has already been used for a move-related variable (assuming that
  5452. they do not interfere). Of course, this preference should not override
  5453. the preference for registers over stack locations. So this preference
  5454. should be used as a tie breaker when choosing between registers or
  5455. when choosing between stack locations.
  5456. We recommend representing the move relationships in a graph, similar
  5457. to how we represented interference. The following is the \emph{move
  5458. graph} for our running example.
  5459. {\if\edition\racketEd
  5460. \[
  5461. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5462. \node (rax) at (0,0) {$\ttm{rax}$};
  5463. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5464. \node (t) at (0,2) {$\ttm{t}$};
  5465. \node (z) at (3,2) {$\ttm{z}$};
  5466. \node (x) at (6,2) {$\ttm{x}$};
  5467. \node (y) at (3,0) {$\ttm{y}$};
  5468. \node (w) at (6,0) {$\ttm{w}$};
  5469. \node (v) at (9,0) {$\ttm{v}$};
  5470. \draw (v) to (x);
  5471. \draw (x) to (y);
  5472. \draw (x) to (z);
  5473. \draw (y) to (t);
  5474. \end{tikzpicture}
  5475. \]
  5476. \fi}
  5477. %
  5478. {\if\edition\pythonEd
  5479. \[
  5480. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5481. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5482. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5483. \node (z) at (3,2) {$\ttm{z}$};
  5484. \node (x) at (6,2) {$\ttm{x}$};
  5485. \node (y) at (3,0) {$\ttm{y}$};
  5486. \node (w) at (6,0) {$\ttm{w}$};
  5487. \node (v) at (9,0) {$\ttm{v}$};
  5488. \draw (y) to (t0);
  5489. \draw (z) to (x);
  5490. \draw (z) to (t1);
  5491. \draw (x) to (y);
  5492. \draw (x) to (v);
  5493. \end{tikzpicture}
  5494. \]
  5495. \fi}
  5496. {\if\edition\racketEd
  5497. Now we replay the graph coloring, pausing to see the coloring of
  5498. \code{y}. Recall the following configuration. The most saturated vertices
  5499. were \code{w} and \code{y}.
  5500. \[
  5501. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5502. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5503. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5504. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5505. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5506. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5507. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5508. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5509. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5510. \draw (t1) to (rax);
  5511. \draw (t1) to (z);
  5512. \draw (z) to (y);
  5513. \draw (z) to (w);
  5514. \draw (x) to (w);
  5515. \draw (y) to (w);
  5516. \draw (v) to (w);
  5517. \draw (v) to (rsp);
  5518. \draw (w) to (rsp);
  5519. \draw (x) to (rsp);
  5520. \draw (y) to (rsp);
  5521. \path[-.,bend left=15] (z) edge node {} (rsp);
  5522. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5523. \draw (rax) to (rsp);
  5524. \end{tikzpicture}
  5525. \]
  5526. %
  5527. Last time we chose to color \code{w} with $0$. But this time we see
  5528. that \code{w} is not move related to any vertex, but \code{y} is move
  5529. related to \code{t}. So we choose to color \code{y} the same color as
  5530. \code{t}, $0$.
  5531. \[
  5532. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5533. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5534. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5535. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5536. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5537. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5538. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5539. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5540. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5541. \draw (t1) to (rax);
  5542. \draw (t1) to (z);
  5543. \draw (z) to (y);
  5544. \draw (z) to (w);
  5545. \draw (x) to (w);
  5546. \draw (y) to (w);
  5547. \draw (v) to (w);
  5548. \draw (v) to (rsp);
  5549. \draw (w) to (rsp);
  5550. \draw (x) to (rsp);
  5551. \draw (y) to (rsp);
  5552. \path[-.,bend left=15] (z) edge node {} (rsp);
  5553. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5554. \draw (rax) to (rsp);
  5555. \end{tikzpicture}
  5556. \]
  5557. Now \code{w} is the most saturated, so we color it $2$.
  5558. \[
  5559. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5560. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5561. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5562. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5563. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5564. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5565. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5566. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5567. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5568. \draw (t1) to (rax);
  5569. \draw (t1) to (z);
  5570. \draw (z) to (y);
  5571. \draw (z) to (w);
  5572. \draw (x) to (w);
  5573. \draw (y) to (w);
  5574. \draw (v) to (w);
  5575. \draw (v) to (rsp);
  5576. \draw (w) to (rsp);
  5577. \draw (x) to (rsp);
  5578. \draw (y) to (rsp);
  5579. \path[-.,bend left=15] (z) edge node {} (rsp);
  5580. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5581. \draw (rax) to (rsp);
  5582. \end{tikzpicture}
  5583. \]
  5584. At this point, vertices \code{x} and \code{v} are most saturated, but
  5585. \code{x} is move related to \code{y} and \code{z}, so we color
  5586. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5587. \[
  5588. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5589. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5590. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5591. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5592. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5593. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5594. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5595. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5596. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5597. \draw (t1) to (rax);
  5598. \draw (t) to (z);
  5599. \draw (z) to (y);
  5600. \draw (z) to (w);
  5601. \draw (x) to (w);
  5602. \draw (y) to (w);
  5603. \draw (v) to (w);
  5604. \draw (v) to (rsp);
  5605. \draw (w) to (rsp);
  5606. \draw (x) to (rsp);
  5607. \draw (y) to (rsp);
  5608. \path[-.,bend left=15] (z) edge node {} (rsp);
  5609. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5610. \draw (rax) to (rsp);
  5611. \end{tikzpicture}
  5612. \]
  5613. \fi}
  5614. %
  5615. {\if\edition\pythonEd
  5616. Now we replay the graph coloring, pausing before the coloring of
  5617. \code{w}. Recall the following configuration. The most saturated vertices
  5618. were \code{tmp\_1}, \code{w}, and \code{y}.
  5619. \[
  5620. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5621. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5622. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5623. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5624. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5625. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5626. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5627. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5628. \draw (t0) to (t1);
  5629. \draw (t0) to (z);
  5630. \draw (z) to (y);
  5631. \draw (z) to (w);
  5632. \draw (x) to (w);
  5633. \draw (y) to (w);
  5634. \draw (v) to (w);
  5635. \end{tikzpicture}
  5636. \]
  5637. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5638. or \code{y}, but note that \code{w} is not move related to any
  5639. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5640. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5641. \code{y} and color it $0$, we can delete another move instruction.
  5642. \[
  5643. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5644. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5645. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5646. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5647. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5648. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5649. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5650. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5651. \draw (t0) to (t1);
  5652. \draw (t0) to (z);
  5653. \draw (z) to (y);
  5654. \draw (z) to (w);
  5655. \draw (x) to (w);
  5656. \draw (y) to (w);
  5657. \draw (v) to (w);
  5658. \end{tikzpicture}
  5659. \]
  5660. Now \code{w} is the most saturated, so we color it $2$.
  5661. \[
  5662. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5663. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5664. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5665. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5666. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5667. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5668. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5669. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5670. \draw (t0) to (t1);
  5671. \draw (t0) 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. \end{tikzpicture}
  5678. \]
  5679. To finish the coloring, \code{x} and \code{v} get $0$ and
  5680. \code{tmp\_1} gets $1$.
  5681. \[
  5682. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5683. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5684. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5685. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5686. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5687. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5688. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5689. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5690. \draw (t0) to (t1);
  5691. \draw (t0) to (z);
  5692. \draw (z) to (y);
  5693. \draw (z) to (w);
  5694. \draw (x) to (w);
  5695. \draw (y) to (w);
  5696. \draw (v) to (w);
  5697. \end{tikzpicture}
  5698. \]
  5699. \fi}
  5700. So we have the following assignment of variables to registers.
  5701. {\if\edition\racketEd
  5702. \begin{gather*}
  5703. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5704. \ttm{w} \mapsto \key{\%rsi}, \,
  5705. \ttm{x} \mapsto \key{\%rcx}, \,
  5706. \ttm{y} \mapsto \key{\%rcx}, \,
  5707. \ttm{z} \mapsto \key{\%rdx}, \,
  5708. \ttm{t} \mapsto \key{\%rcx} \}
  5709. \end{gather*}
  5710. \fi}
  5711. {\if\edition\pythonEd
  5712. \begin{gather*}
  5713. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5714. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5715. \ttm{x} \mapsto \key{\%rcx}, \,
  5716. \ttm{y} \mapsto \key{\%rcx}, \\
  5717. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5718. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5719. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5720. \end{gather*}
  5721. \fi}
  5722. We apply this register assignment to the running example, on the left,
  5723. to obtain the code in the middle. The \code{patch\_instructions} then
  5724. deletes the trivial moves to obtain the code on the right.
  5725. {\if\edition\racketEd
  5726. \begin{minipage}{0.25\textwidth}
  5727. \begin{lstlisting}
  5728. movq $1, v
  5729. movq $42, w
  5730. movq v, x
  5731. addq $7, x
  5732. movq x, y
  5733. movq x, z
  5734. addq w, z
  5735. movq y, t
  5736. negq t
  5737. movq z, %rax
  5738. addq t, %rax
  5739. jmp conclusion
  5740. \end{lstlisting}
  5741. \end{minipage}
  5742. $\Rightarrow\qquad$
  5743. \begin{minipage}{0.25\textwidth}
  5744. \begin{lstlisting}
  5745. movq $1, %rcx
  5746. movq $42, %rsi
  5747. movq %rcx, %rcx
  5748. addq $7, %rcx
  5749. movq %rcx, %rcx
  5750. movq %rcx, %rdx
  5751. addq %rsi, %rdx
  5752. movq %rcx, %rcx
  5753. negq %rcx
  5754. movq %rdx, %rax
  5755. addq %rcx, %rax
  5756. jmp conclusion
  5757. \end{lstlisting}
  5758. \end{minipage}
  5759. $\Rightarrow\qquad$
  5760. \begin{minipage}{0.25\textwidth}
  5761. \begin{lstlisting}
  5762. movq $1, %rcx
  5763. movq $42, %rsi
  5764. addq $7, %rcx
  5765. movq %rcx, %rdx
  5766. addq %rsi, %rdx
  5767. negq %rcx
  5768. movq %rdx, %rax
  5769. addq %rcx, %rax
  5770. jmp conclusion
  5771. \end{lstlisting}
  5772. \end{minipage}
  5773. \fi}
  5774. {\if\edition\pythonEd
  5775. \begin{minipage}{0.20\textwidth}
  5776. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5777. movq $1, v
  5778. movq $42, w
  5779. movq v, x
  5780. addq $7, x
  5781. movq x, y
  5782. movq x, z
  5783. addq w, z
  5784. movq y, tmp_0
  5785. negq tmp_0
  5786. movq z, tmp_1
  5787. addq tmp_0, tmp_1
  5788. movq tmp_1, %rdi
  5789. callq _print_int
  5790. \end{lstlisting}
  5791. \end{minipage}
  5792. ${\Rightarrow\qquad}$
  5793. \begin{minipage}{0.30\textwidth}
  5794. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5795. movq $1, %rcx
  5796. movq $42, -16(%rbp)
  5797. movq %rcx, %rcx
  5798. addq $7, %rcx
  5799. movq %rcx, %rcx
  5800. movq %rcx, -8(%rbp)
  5801. addq -16(%rbp), -8(%rbp)
  5802. movq %rcx, %rcx
  5803. negq %rcx
  5804. movq -8(%rbp), -8(%rbp)
  5805. addq %rcx, -8(%rbp)
  5806. movq -8(%rbp), %rdi
  5807. callq _print_int
  5808. \end{lstlisting}
  5809. \end{minipage}
  5810. ${\Rightarrow\qquad}$
  5811. \begin{minipage}{0.20\textwidth}
  5812. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5813. movq $1, %rcx
  5814. movq $42, -16(%rbp)
  5815. addq $7, %rcx
  5816. movq %rcx, -8(%rbp)
  5817. movq -16(%rbp), %rax
  5818. addq %rax, -8(%rbp)
  5819. negq %rcx
  5820. addq %rcx, -8(%rbp)
  5821. movq -8(%rbp), %rdi
  5822. callq print_int
  5823. \end{lstlisting}
  5824. \end{minipage}
  5825. \fi}
  5826. \begin{exercise}\normalfont
  5827. Change your implementation of \code{allocate\_registers} to take move
  5828. biasing into account. Create two new tests that include at least one
  5829. opportunity for move biasing and visually inspect the output x86
  5830. programs to make sure that your move biasing is working properly. Make
  5831. sure that your compiler still passes all of the tests.
  5832. \end{exercise}
  5833. %To do: another neat challenge would be to do
  5834. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5835. %% \subsection{Output of the Running Example}
  5836. %% \label{sec:reg-alloc-output}
  5837. % challenge: prioritize variables based on execution frequencies
  5838. % and the number of uses of a variable
  5839. % challenge: enhance the coloring algorithm using Chaitin's
  5840. % approach of prioritizing high-degree variables
  5841. % by removing low-degree variables (coloring them later)
  5842. % from the interference graph
  5843. \section{Further Reading}
  5844. \label{sec:register-allocation-further-reading}
  5845. Early register allocation algorithms were developed for Fortran
  5846. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5847. of graph coloring began in the late 1970s and early 1980s with the
  5848. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5849. algorithm is based on the following observation of
  5850. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5851. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5852. $v$ removed is also $k$ colorable. To see why, suppose that the
  5853. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5854. different colors, but since there are less than $k$ neighbors, there
  5855. will be one or more colors left over to use for coloring $v$ in $G$.
  5856. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5857. less than $k$ from the graph and recursively colors the rest of the
  5858. graph. Upon returning from the recursion, it colors $v$ with one of
  5859. the available colors and returns. \citet{Chaitin:1982vn} augments
  5860. this algorithm to handle spilling as follows. If there are no vertices
  5861. of degree lower than $k$ then pick a vertex at random, spill it,
  5862. remove it from the graph, and proceed recursively to color the rest of
  5863. the graph.
  5864. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5865. move-related and that don't interfere with each other, a process
  5866. called \emph{coalescing}. While coalescing decreases the number of
  5867. moves, it can make the graph more difficult to
  5868. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5869. which two variables are merged only if they have fewer than $k$
  5870. neighbors of high degree. \citet{George:1996aa} observe that
  5871. conservative coalescing is sometimes too conservative and make it more
  5872. aggressive by iterating the coalescing with the removal of low-degree
  5873. vertices.
  5874. %
  5875. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5876. also propose \emph{biased coloring} in which a variable is assigned to
  5877. the same color as another move-related variable if possible, as
  5878. discussed in Section~\ref{sec:move-biasing}.
  5879. %
  5880. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5881. performs coalescing, graph coloring, and spill code insertion until
  5882. all variables have been assigned a location.
  5883. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5884. spills variables that don't have to be: a high-degree variable can be
  5885. colorable if many of its neighbors are assigned the same color.
  5886. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5887. high-degree vertex is not immediately spilled. Instead the decision is
  5888. deferred until after the recursive call, at which point it is apparent
  5889. whether there is actually an available color or not. We observe that
  5890. this algorithm is equivalent to the smallest-last ordering
  5891. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5892. be registers and the rest to be stack locations.
  5893. %% biased coloring
  5894. Earlier editions of the compiler course at Indiana University
  5895. \citep{Dybvig:2010aa} were based on the algorithm of
  5896. \citet{Briggs:1994kx}.
  5897. The smallest-last ordering algorithm is one of many \emph{greedy}
  5898. coloring algorithms. A greedy coloring algorithm visits all the
  5899. vertices in a particular order and assigns each one the first
  5900. available color. An \emph{offline} greedy algorithm chooses the
  5901. ordering up-front, prior to assigning colors. The algorithm of
  5902. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5903. ordering does not depend on the colors assigned. Other orderings are
  5904. possible. For example, \citet{Chow:1984ys} order variables according
  5905. to an estimate of runtime cost.
  5906. An \emph{online} greedy coloring algorithm uses information about the
  5907. current assignment of colors to influence the order in which the
  5908. remaining vertices are colored. The saturation-based algorithm
  5909. described in this chapter is one such algorithm. We choose to use
  5910. saturation-based coloring because it is fun to introduce graph
  5911. coloring via Sudoku!
  5912. A register allocator may choose to map each variable to just one
  5913. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5914. variable to one or more locations. The later can be achieved by
  5915. \emph{live range splitting}, where a variable is replaced by several
  5916. variables that each handle part of its live
  5917. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5918. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5919. %% replacement algorithm, bottom-up local
  5920. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5921. %% Cooper: top-down (priority bassed), bottom-up
  5922. %% top-down
  5923. %% order variables by priority (estimated cost)
  5924. %% caveat: split variables into two groups:
  5925. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5926. %% color the constrained ones first
  5927. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5928. %% cite J. Cocke for an algorithm that colors variables
  5929. %% in a high-degree first ordering
  5930. %Register Allocation via Usage Counts, Freiburghouse CACM
  5931. \citet{Palsberg:2007si} observe that many of the interference graphs
  5932. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5933. that is, every cycle with four or more edges has an edge which is not
  5934. part of the cycle but which connects two vertices on the cycle. Such
  5935. graphs can be optimally colored by the greedy algorithm with a vertex
  5936. ordering determined by maximum cardinality search.
  5937. In situations where compile time is of utmost importance, such as in
  5938. just-in-time compilers, graph coloring algorithms can be too expensive
  5939. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5940. appropriate.
  5941. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5942. \chapter{Booleans and Conditionals}
  5943. \label{ch:Lif}
  5944. \index{subject}{Boolean}
  5945. \index{subject}{control flow}
  5946. \index{subject}{conditional expression}
  5947. The \LangInt{} and \LangVar{} languages only have a single kind of
  5948. value, the integers. In this chapter we add a second kind of value,
  5949. the Booleans, to create the \LangIf{} language. The Boolean values
  5950. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5951. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5952. language includes several operations that involve Booleans (\key{and},
  5953. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5954. \key{if} expression \python{and statement}. With the addition of
  5955. \key{if}, programs can have non-trivial control flow which
  5956. %
  5957. \racket{impacts \code{explicate\_control} and liveness analysis}
  5958. %
  5959. \python{impacts liveness analysis and motivates a new pass named
  5960. \code{explicate\_control}}.
  5961. %
  5962. Also, because we now have two kinds of values, we need to handle
  5963. programs that apply an operation to the wrong kind of value, such as
  5964. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5965. There are two language design options for such situations. One option
  5966. is to signal an error and the other is to provide a wider
  5967. interpretation of the operation. \racket{The Racket
  5968. language}\python{Python} uses a mixture of these two options,
  5969. depending on the operation and the kind of value. For example, the
  5970. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5971. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5972. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5973. %
  5974. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5975. in Racket because \code{car} expects a pair.}
  5976. %
  5977. \python{On the other hand, \code{1[0]} results in a run-time error
  5978. in Python because an ``\code{int} object is not subscriptable''.}
  5979. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5980. design choices as \racket{Racket}\python{Python}, except much of the
  5981. error detection happens at compile time instead of run
  5982. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5983. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5984. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5985. Racket}\python{MyPy} reports a compile-time error
  5986. %
  5987. \racket{because Racket expects the type of the argument to be of the form
  5988. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5989. %
  5990. \python{stating that a ``value of type \code{int} is not indexable''.}
  5991. The \LangIf{} language performs type checking during compilation like
  5992. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study the
  5993. alternative choice, that is, a dynamically typed language like
  5994. \racket{Racket}\python{Python}.
  5995. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5996. for some operations we are more restrictive, for example, rejecting
  5997. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5998. This chapter is organized as follows. We begin by defining the syntax
  5999. and interpreter for the \LangIf{} language
  6000. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  6001. checking and define a type checker for \LangIf{}
  6002. (Section~\ref{sec:type-check-Lif}).
  6003. %
  6004. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6005. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  6006. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  6007. %
  6008. The remaining sections of this chapter discuss how the addition of
  6009. Booleans and conditional control flow to the language requires changes
  6010. to the existing compiler passes and the addition of new ones. In
  6011. particular, we introduce the \code{shrink} pass to translates some
  6012. operators into others, thereby reducing the number of operators that
  6013. need to be handled in later passes.
  6014. %
  6015. The main event of this chapter is the \code{explicate\_control} pass
  6016. that is responsible for translating \code{if}'s into conditional
  6017. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  6018. %
  6019. Regarding register allocation, there is the interesting question of
  6020. how to handle conditional \code{goto}'s during liveness analysis.
  6021. \section{The \LangIf{} Language}
  6022. \label{sec:lang-if}
  6023. The concrete and abstract syntax of the \LangIf{} language are defined in
  6024. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6025. respectively. The \LangIf{} language includes all of
  6026. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6027. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  6028. \code{if} statement}. We expand the set of operators to include
  6029. \begin{enumerate}
  6030. \item subtraction on integers,
  6031. \item the logical operators \key{and}, \key{or}, and \key{not},
  6032. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6033. for comparing integers or Booleans for equality, and
  6034. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6035. comparing integers.
  6036. \end{enumerate}
  6037. \racket{We reorganize the abstract syntax for the primitive
  6038. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6039. rule for all of them. This means that the grammar no longer checks
  6040. whether the arity of an operators matches the number of
  6041. arguments. That responsibility is moved to the type checker for
  6042. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  6043. \newcommand{\LifGrammarRacket}{
  6044. \begin{array}{lcl}
  6045. \Type &::=& \key{Boolean} \\
  6046. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6047. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6048. \Exp &::=& \CSUB{\Exp}{\Exp} \MID \itm{bool}
  6049. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6050. \MID (\key{not}\;\Exp) \\
  6051. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6052. \end{array}
  6053. }
  6054. \newcommand{\LifASTRacket}{
  6055. \begin{array}{lcl}
  6056. \Type &::=& \key{Boolean} \\
  6057. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6058. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6059. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6060. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6061. \end{array}
  6062. }
  6063. \newcommand{\LintOpAST}{
  6064. \begin{array}{rcl}
  6065. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6066. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6067. \end{array}
  6068. }
  6069. \newcommand{\LifGrammarPython}{
  6070. \begin{array}{rcl}
  6071. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6072. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6073. \MID \key{not}~\Exp \\
  6074. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6075. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6076. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6077. \end{array}
  6078. }
  6079. \newcommand{\LifASTPython}{
  6080. \begin{array}{lcl}
  6081. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6082. \itm{unaryop} &::=& \code{Not()} \\
  6083. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6084. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6085. \Exp &::=& \BOOL{\itm{bool}}
  6086. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6087. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6088. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6089. \end{array}
  6090. }
  6091. \begin{figure}[tp]
  6092. \centering
  6093. \fbox{
  6094. \begin{minipage}{0.96\textwidth}
  6095. {\if\edition\racketEd
  6096. \[
  6097. \begin{array}{l}
  6098. \gray{\LintGrammarRacket{}} \\ \hline
  6099. \gray{\LvarGrammarRacket{}} \\ \hline
  6100. \LifGrammarRacket{} \\
  6101. \begin{array}{lcl}
  6102. \LangIfM{} &::=& \Exp
  6103. \end{array}
  6104. \end{array}
  6105. \]
  6106. \fi}
  6107. {\if\edition\pythonEd
  6108. \[
  6109. \begin{array}{l}
  6110. \gray{\LintGrammarPython} \\ \hline
  6111. \gray{\LvarGrammarPython} \\ \hline
  6112. \LifGrammarPython \\
  6113. \begin{array}{rcl}
  6114. \LangIfM{} &::=& \Stmt^{*}
  6115. \end{array}
  6116. \end{array}
  6117. \]
  6118. \fi}
  6119. \end{minipage}
  6120. }
  6121. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6122. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6123. \label{fig:Lif-concrete-syntax}
  6124. \end{figure}
  6125. \begin{figure}[tp]
  6126. \centering
  6127. \fbox{
  6128. \begin{minipage}{0.96\textwidth}
  6129. {\if\edition\racketEd
  6130. \[
  6131. \begin{array}{l}
  6132. \gray{\LintOpAST} \\ \hline
  6133. \gray{\LvarASTRacket{}} \\ \hline
  6134. \LifASTRacket{} \\
  6135. \begin{array}{lcl}
  6136. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6137. \end{array}
  6138. \end{array}
  6139. \]
  6140. \fi}
  6141. {\if\edition\pythonEd
  6142. \[
  6143. \begin{array}{l}
  6144. \gray{\LintASTPython} \\ \hline
  6145. \gray{\LvarASTPython} \\ \hline
  6146. \LifASTPython \\
  6147. \begin{array}{lcl}
  6148. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6149. \end{array}
  6150. \end{array}
  6151. \]
  6152. \fi}
  6153. \end{minipage}
  6154. }
  6155. \caption{The abstract syntax of \LangIf{}.}
  6156. \label{fig:Lif-syntax}
  6157. \end{figure}
  6158. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6159. which inherits from the interpreter for \LangVar{}
  6160. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6161. evaluate to the corresponding Boolean values. The conditional
  6162. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6163. and then either evaluates $e_2$ or $e_3$ depending on whether
  6164. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6165. \code{and}, \code{or}, and \code{not} behave according to
  6166. propositional logic. In addition, the \code{and} and \code{or}
  6167. operations perform \emph{short-circuit evaluation}.
  6168. %
  6169. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6170. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6171. %
  6172. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6173. evaluated if $e_1$ evaluates to \TRUE{}.
  6174. \racket{With the increase in the number of primitive operations, the
  6175. interpreter would become repetitive without some care. We refactor
  6176. the case for \code{Prim}, moving the code that differs with each
  6177. operation into the \code{interp\_op} method shown in in
  6178. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6179. \code{or} operations separately because of their short-circuiting
  6180. behavior.}
  6181. \begin{figure}[tbp]
  6182. {\if\edition\racketEd
  6183. \begin{lstlisting}
  6184. (define interp_Lif_class
  6185. (class interp_Lvar_class
  6186. (super-new)
  6187. (define/public (interp_op op) ...)
  6188. (define/override ((interp_exp env) e)
  6189. (define recur (interp_exp env))
  6190. (match e
  6191. [(Bool b) b]
  6192. [(If cnd thn els)
  6193. (match (recur cnd)
  6194. [#t (recur thn)]
  6195. [#f (recur els)])]
  6196. [(Prim 'and (list e1 e2))
  6197. (match (recur e1)
  6198. [#t (match (recur e2) [#t #t] [#f #f])]
  6199. [#f #f])]
  6200. [(Prim 'or (list e1 e2))
  6201. (define v1 (recur e1))
  6202. (match v1
  6203. [#t #t]
  6204. [#f (match (recur e2) [#t #t] [#f #f])])]
  6205. [(Prim op args)
  6206. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6207. [else ((super interp_exp env) e)]))
  6208. ))
  6209. (define (interp_Lif p)
  6210. (send (new interp_Lif_class) interp_program p))
  6211. \end{lstlisting}
  6212. \fi}
  6213. {\if\edition\pythonEd
  6214. \begin{lstlisting}
  6215. class InterpLif(InterpLvar):
  6216. def interp_exp(self, e, env):
  6217. match e:
  6218. case IfExp(test, body, orelse):
  6219. if self.interp_exp(test, env):
  6220. return self.interp_exp(body, env)
  6221. else:
  6222. return self.interp_exp(orelse, env)
  6223. case BinOp(left, Sub(), right):
  6224. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6225. case UnaryOp(Not(), v):
  6226. return not self.interp_exp(v, env)
  6227. case BoolOp(And(), values):
  6228. if self.interp_exp(values[0], env):
  6229. return self.interp_exp(values[1], env)
  6230. else:
  6231. return False
  6232. case BoolOp(Or(), values):
  6233. if self.interp_exp(values[0], env):
  6234. return True
  6235. else:
  6236. return self.interp_exp(values[1], env)
  6237. case Compare(left, [cmp], [right]):
  6238. l = self.interp_exp(left, env)
  6239. r = self.interp_exp(right, env)
  6240. return self.interp_cmp(cmp)(l, r)
  6241. case _:
  6242. return super().interp_exp(e, env)
  6243. def interp_stmts(self, ss, env):
  6244. if len(ss) == 0:
  6245. return
  6246. match ss[0]:
  6247. case If(test, body, orelse):
  6248. if self.interp_exp(test, env):
  6249. return self.interp_stmts(body + ss[1:], env)
  6250. else:
  6251. return self.interp_stmts(orelse + ss[1:], env)
  6252. case _:
  6253. return super().interp_stmts(ss, env)
  6254. ...
  6255. \end{lstlisting}
  6256. \fi}
  6257. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6258. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6259. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6260. \label{fig:interp-Lif}
  6261. \end{figure}
  6262. {\if\edition\racketEd
  6263. \begin{figure}[tbp]
  6264. \begin{lstlisting}
  6265. (define/public (interp_op op)
  6266. (match op
  6267. ['+ fx+]
  6268. ['- fx-]
  6269. ['read read-fixnum]
  6270. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6271. ['eq? (lambda (v1 v2)
  6272. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6273. (and (boolean? v1) (boolean? v2))
  6274. (and (vector? v1) (vector? v2)))
  6275. (eq? v1 v2)]))]
  6276. ['< (lambda (v1 v2)
  6277. (cond [(and (fixnum? v1) (fixnum? v2))
  6278. (< v1 v2)]))]
  6279. ['<= (lambda (v1 v2)
  6280. (cond [(and (fixnum? v1) (fixnum? v2))
  6281. (<= v1 v2)]))]
  6282. ['> (lambda (v1 v2)
  6283. (cond [(and (fixnum? v1) (fixnum? v2))
  6284. (> v1 v2)]))]
  6285. ['>= (lambda (v1 v2)
  6286. (cond [(and (fixnum? v1) (fixnum? v2))
  6287. (>= v1 v2)]))]
  6288. [else (error 'interp_op "unknown operator")]))
  6289. \end{lstlisting}
  6290. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6291. \label{fig:interp-op-Lif}
  6292. \end{figure}
  6293. \fi}
  6294. {\if\edition\pythonEd
  6295. \begin{figure}
  6296. \begin{lstlisting}
  6297. class InterpLif(InterpLvar):
  6298. ...
  6299. def interp_cmp(self, cmp):
  6300. match cmp:
  6301. case Lt():
  6302. return lambda x, y: x < y
  6303. case LtE():
  6304. return lambda x, y: x <= y
  6305. case Gt():
  6306. return lambda x, y: x > y
  6307. case GtE():
  6308. return lambda x, y: x >= y
  6309. case Eq():
  6310. return lambda x, y: x == y
  6311. case NotEq():
  6312. return lambda x, y: x != y
  6313. \end{lstlisting}
  6314. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6315. \label{fig:interp-cmp-Lif}
  6316. \end{figure}
  6317. \fi}
  6318. \section{Type Checking \LangIf{} Programs}
  6319. \label{sec:type-check-Lif}
  6320. \index{subject}{type checking}
  6321. \index{subject}{semantic analysis}
  6322. It is helpful to think about type checking in two complementary
  6323. ways. A type checker predicts the type of value that will be produced
  6324. by each expression in the program. For \LangIf{}, we have just two types,
  6325. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6326. {\if\edition\racketEd
  6327. \begin{lstlisting}
  6328. (+ 10 (- (+ 12 20)))
  6329. \end{lstlisting}
  6330. \fi}
  6331. {\if\edition\pythonEd
  6332. \begin{lstlisting}
  6333. 10 + -(12 + 20)
  6334. \end{lstlisting}
  6335. \fi}
  6336. \noindent produces a value of type \INTTY{} while
  6337. {\if\edition\racketEd
  6338. \begin{lstlisting}
  6339. (and (not #f) #t)
  6340. \end{lstlisting}
  6341. \fi}
  6342. {\if\edition\pythonEd
  6343. \begin{lstlisting}
  6344. (not False) and True
  6345. \end{lstlisting}
  6346. \fi}
  6347. \noindent produces a value of type \BOOLTY{}.
  6348. A second way to think about type checking is that it enforces a set of
  6349. rules about which operators can be applied to which kinds of
  6350. values. For example, our type checker for \LangIf{} signals an error
  6351. for the below expression {\if\edition\racketEd
  6352. \begin{lstlisting}
  6353. (not (+ 10 (- (+ 12 20))))
  6354. \end{lstlisting}
  6355. \fi}
  6356. {\if\edition\pythonEd
  6357. \begin{lstlisting}
  6358. not (10 + -(12 + 20))
  6359. \end{lstlisting}
  6360. \fi}
  6361. The subexpression
  6362. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6363. has type \INTTY{} but the type checker enforces the rule that the argument of
  6364. \code{not} must be an expression of type \BOOLTY{}.
  6365. We implement type checking using classes and methods because they
  6366. provide the open recursion needed to reuse code as we extend the type
  6367. checker in later chapters, analogous to the use of classes and methods
  6368. for the interpreters (Section~\ref{sec:extensible-interp}).
  6369. We separate the type checker for the \LangVar{} subset into its own
  6370. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6371. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6372. from the type checker for \LangVar{}. These type checkers are in the
  6373. files
  6374. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6375. and
  6376. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6377. of the support code.
  6378. %
  6379. Each type checker is a structurally recursive function over the AST.
  6380. Given an input expression \code{e}, the type checker either signals an
  6381. error or returns \racket{an expression and} its type (\INTTY{} or
  6382. \BOOLTY{}).
  6383. %
  6384. \racket{It returns an expression because there are situations in which
  6385. we want to change or update the expression.}
  6386. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6387. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6388. \INTTY{}. To handle variables, the type checker uses the environment
  6389. \code{env} to map variables to types.
  6390. %
  6391. \racket{Consider the case for \key{let}. We type check the
  6392. initializing expression to obtain its type \key{T} and then
  6393. associate type \code{T} with the variable \code{x} in the
  6394. environment used to type check the body of the \key{let}. Thus,
  6395. when the type checker encounters a use of variable \code{x}, it can
  6396. find its type in the environment.}
  6397. %
  6398. \python{Consider the case for assignment. We type check the
  6399. initializing expression to obtain its type \key{t}. If the variable
  6400. \code{lhs.id} is already in the environment because there was a
  6401. prior assignment, we check that this initializer has the same type
  6402. as the prior one. If this is the first assignment to the variable,
  6403. we associate type \code{t} with the variable \code{lhs.id} in the
  6404. environment. Thus, when the type checker encounters a use of
  6405. variable \code{x}, it can find its type in the environment.}
  6406. %
  6407. \racket{Regarding primitive operators, we recursively analyze the
  6408. arguments and then invoke \code{type\_check\_op} to check whether
  6409. the argument types are allowed.}
  6410. %
  6411. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6412. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6413. \racket{Several auxiliary methods are used in the type checker. The
  6414. method \code{operator-types} defines a dictionary that maps the
  6415. operator names to their parameter and return types. The
  6416. \code{type-equal?} method determines whether two types are equal,
  6417. which for now simply dispatches to \code{equal?} (deep
  6418. equality). The \code{check-type-equal?} method triggers an error if
  6419. the two types are not equal. The \code{type-check-op} method looks
  6420. up the operator in the \code{operator-types} dictionary and then
  6421. checks whether the argument types are equal to the parameter types.
  6422. The result is the return type of the operator.}
  6423. %
  6424. \python{The auxiliary method \code{check\_type\_equal} triggers
  6425. an error if the two types are not equal.}
  6426. \begin{figure}[tbp]
  6427. {\if\edition\racketEd
  6428. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6429. (define type-check-Lvar_class
  6430. (class object%
  6431. (super-new)
  6432. (define/public (operator-types)
  6433. '((+ . ((Integer Integer) . Integer))
  6434. (- . ((Integer) . Integer))
  6435. (read . (() . Integer))))
  6436. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6437. (define/public (check-type-equal? t1 t2 e)
  6438. (unless (type-equal? t1 t2)
  6439. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6440. (define/public (type-check-op op arg-types e)
  6441. (match (dict-ref (operator-types) op)
  6442. [`(,param-types . ,return-type)
  6443. (for ([at arg-types] [pt param-types])
  6444. (check-type-equal? at pt e))
  6445. return-type]
  6446. [else (error 'type-check-op "unrecognized ~a" op)]))
  6447. (define/public (type-check-exp env)
  6448. (lambda (e)
  6449. (match e
  6450. [(Int n) (values (Int n) 'Integer)]
  6451. [(Var x) (values (Var x) (dict-ref env x))]
  6452. [(Let x e body)
  6453. (define-values (e^ Te) ((type-check-exp env) e))
  6454. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6455. (values (Let x e^ b) Tb)]
  6456. [(Prim op es)
  6457. (define-values (new-es ts)
  6458. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6459. (values (Prim op new-es) (type-check-op op ts e))]
  6460. [else (error 'type-check-exp "couldn't match" e)])))
  6461. (define/public (type-check-program e)
  6462. (match e
  6463. [(Program info body)
  6464. (define-values (body^ Tb) ((type-check-exp '()) body))
  6465. (check-type-equal? Tb 'Integer body)
  6466. (Program info body^)]
  6467. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6468. ))
  6469. (define (type-check-Lvar p)
  6470. (send (new type-check-Lvar_class) type-check-program p))
  6471. \end{lstlisting}
  6472. \fi}
  6473. {\if\edition\pythonEd
  6474. \begin{lstlisting}[escapechar=`]
  6475. class TypeCheckLvar:
  6476. def check_type_equal(self, t1, t2, e):
  6477. if t1 != t2:
  6478. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6479. raise Exception(msg)
  6480. def type_check_exp(self, e, env):
  6481. match e:
  6482. case BinOp(left, (Add() | Sub()), right):
  6483. l = self.type_check_exp(left, env)
  6484. check_type_equal(l, int, left)
  6485. r = self.type_check_exp(right, env)
  6486. check_type_equal(r, int, right)
  6487. return int
  6488. case UnaryOp(USub(), v):
  6489. t = self.type_check_exp(v, env)
  6490. check_type_equal(t, int, v)
  6491. return int
  6492. case Name(id):
  6493. return env[id]
  6494. case Constant(value) if isinstance(value, int):
  6495. return int
  6496. case Call(Name('input_int'), []):
  6497. return int
  6498. def type_check_stmts(self, ss, env):
  6499. if len(ss) == 0:
  6500. return
  6501. match ss[0]:
  6502. case Assign([lhs], value):
  6503. t = self.type_check_exp(value, env)
  6504. if lhs.id in env:
  6505. check_type_equal(env[lhs.id], t, value)
  6506. else:
  6507. env[lhs.id] = t
  6508. return self.type_check_stmts(ss[1:], env)
  6509. case Expr(Call(Name('print'), [arg])):
  6510. t = self.type_check_exp(arg, env)
  6511. check_type_equal(t, int, arg)
  6512. return self.type_check_stmts(ss[1:], env)
  6513. case Expr(value):
  6514. self.type_check_exp(value, env)
  6515. return self.type_check_stmts(ss[1:], env)
  6516. def type_check_P(self, p):
  6517. match p:
  6518. case Module(body):
  6519. self.type_check_stmts(body, {})
  6520. \end{lstlisting}
  6521. \fi}
  6522. \caption{Type checker for the \LangVar{} language.}
  6523. \label{fig:type-check-Lvar}
  6524. \end{figure}
  6525. \begin{figure}[tbp]
  6526. {\if\edition\racketEd
  6527. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6528. (define type-check-Lif_class
  6529. (class type-check-Lvar_class
  6530. (super-new)
  6531. (inherit check-type-equal?)
  6532. (define/override (operator-types)
  6533. (append '((- . ((Integer Integer) . Integer))
  6534. (and . ((Boolean Boolean) . Boolean))
  6535. (or . ((Boolean Boolean) . Boolean))
  6536. (< . ((Integer Integer) . Boolean))
  6537. (<= . ((Integer Integer) . Boolean))
  6538. (> . ((Integer Integer) . Boolean))
  6539. (>= . ((Integer Integer) . Boolean))
  6540. (not . ((Boolean) . Boolean))
  6541. )
  6542. (super operator-types)))
  6543. (define/override (type-check-exp env)
  6544. (lambda (e)
  6545. (match e
  6546. [(Bool b) (values (Bool b) 'Boolean)]
  6547. [(Prim 'eq? (list e1 e2))
  6548. (define-values (e1^ T1) ((type-check-exp env) e1))
  6549. (define-values (e2^ T2) ((type-check-exp env) e2))
  6550. (check-type-equal? T1 T2 e)
  6551. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6552. [(If cnd thn els)
  6553. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6554. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6555. (define-values (els^ Te) ((type-check-exp env) els))
  6556. (check-type-equal? Tc 'Boolean e)
  6557. (check-type-equal? Tt Te e)
  6558. (values (If cnd^ thn^ els^) Te)]
  6559. [else ((super type-check-exp env) e)])))
  6560. ))
  6561. (define (type-check-Lif p)
  6562. (send (new type-check-Lif_class) type-check-program p))
  6563. \end{lstlisting}
  6564. \fi}
  6565. {\if\edition\pythonEd
  6566. \begin{lstlisting}
  6567. class TypeCheckLif(TypeCheckLvar):
  6568. def type_check_exp(self, e, env):
  6569. match e:
  6570. case Constant(value) if isinstance(value, bool):
  6571. return bool
  6572. case BinOp(left, Sub(), right):
  6573. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6574. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6575. return int
  6576. case UnaryOp(Not(), v):
  6577. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6578. return bool
  6579. case BoolOp(op, values):
  6580. left = values[0] ; right = values[1]
  6581. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6582. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6583. return bool
  6584. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6585. or isinstance(cmp, NotEq):
  6586. l = self.type_check_exp(left, env)
  6587. r = self.type_check_exp(right, env)
  6588. check_type_equal(l, r, e)
  6589. return bool
  6590. case Compare(left, [cmp], [right]):
  6591. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6592. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6593. return bool
  6594. case IfExp(test, body, orelse):
  6595. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6596. b = self.type_check_exp(body, env)
  6597. o = self.type_check_exp(orelse, env)
  6598. check_type_equal(b, o, e)
  6599. return b
  6600. case _:
  6601. return super().type_check_exp(e, env)
  6602. def type_check_stmts(self, ss, env):
  6603. if len(ss) == 0:
  6604. return
  6605. match ss[0]:
  6606. case If(test, body, orelse):
  6607. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6608. b = self.type_check_stmts(body, env)
  6609. o = self.type_check_stmts(orelse, env)
  6610. check_type_equal(b, o, ss[0])
  6611. return self.type_check_stmts(ss[1:], env)
  6612. case _:
  6613. return super().type_check_stmts(ss, env)
  6614. \end{lstlisting}
  6615. \fi}
  6616. \caption{Type checker for the \LangIf{} language.}
  6617. \label{fig:type-check-Lif}
  6618. \end{figure}
  6619. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6620. checker for \LangIf{}.
  6621. %
  6622. The type of a Boolean constant is \BOOLTY{}.
  6623. %
  6624. \racket{The \code{operator-types} function adds dictionary entries for
  6625. the other new operators.}
  6626. %
  6627. \python{Logical not requires its argument to be a \BOOLTY{} and
  6628. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6629. %
  6630. The equality operators require the two arguments to have the same
  6631. type.
  6632. %
  6633. \python{The other comparisons (less-than, etc.) require their
  6634. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6635. %
  6636. The condition of an \code{if} must
  6637. be of \BOOLTY{} type and the two branches must have the same type.
  6638. \begin{exercise}\normalfont
  6639. Create 10 new test programs in \LangIf{}. Half of the programs should
  6640. have a type error. For those programs, create an empty file with the
  6641. same base name but with file extension \code{.tyerr}. For example, if
  6642. the test
  6643. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6644. is expected to error, then create
  6645. an empty file named \code{cond\_test\_14.tyerr}.
  6646. %
  6647. \racket{This indicates to \code{interp-tests} and
  6648. \code{compiler-tests} that a type error is expected. }
  6649. %
  6650. The other half of the test programs should not have type errors.
  6651. %
  6652. \racket{In the \code{run-tests.rkt} script, change the second argument
  6653. of \code{interp-tests} and \code{compiler-tests} to
  6654. \code{type-check-Lif}, which causes the type checker to run prior to
  6655. the compiler passes. Temporarily change the \code{passes} to an
  6656. empty list and run the script, thereby checking that the new test
  6657. programs either type check or not as intended.}
  6658. %
  6659. Run the test script to check that these test programs type check as
  6660. expected.
  6661. \end{exercise}
  6662. \clearpage
  6663. \section{The \LangCIf{} Intermediate Language}
  6664. \label{sec:Cif}
  6665. {\if\edition\racketEd
  6666. %
  6667. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6668. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6669. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6670. language adds logical and comparison operators to the \Exp{}
  6671. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6672. non-terminal.
  6673. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6674. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6675. statement is a comparison operation and the branches are \code{goto}
  6676. statements, making it straightforward to compile \code{if} statements
  6677. to x86.
  6678. %
  6679. \fi}
  6680. %
  6681. {\if\edition\pythonEd
  6682. %
  6683. The output of \key{explicate\_control} is a language similar to the
  6684. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6685. \code{goto} statements, so we name it \LangCIf{}. The
  6686. concrete syntax for \LangCIf{} is defined in
  6687. Figure~\ref{fig:c1-concrete-syntax}
  6688. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6689. %
  6690. The \LangCIf{} language supports the same operators as \LangIf{} but
  6691. the arguments of operators are restricted to atomic expressions. The
  6692. \LangCIf{} language does not include \code{if} expressions but it does
  6693. include a restricted form of \code{if} statment. The condition must be
  6694. a comparison and the two branches may only contain \code{goto}
  6695. statements. These restrictions make it easier to translate \code{if}
  6696. statements to x86.
  6697. %
  6698. \fi}
  6699. %
  6700. Besides the \code{goto} statement, \LangCIf{}, also adds a
  6701. \code{return} statement to finish a function call with a specified value.
  6702. %
  6703. The \key{CProgram} construct contains
  6704. %
  6705. \racket{an alist}\python{a dictionary}
  6706. %
  6707. mapping labels to
  6708. \racket{$\Tail$ expressions, which can be \code{return} statements,
  6709. an assignment statement followed by a $\Tail$ expression, a
  6710. \code{goto}, or a conditional \code{goto}.}
  6711. \python{lists of statements, which comprise of assignment statements
  6712. and end in a \code{return} statement, a \code{goto}, or a
  6713. conditional \code{goto}.
  6714. \index{subject}{basic block}
  6715. Statement lists of this form are called
  6716. \emph{basic blocks}: there is a control transfer at the end and
  6717. control only enters at the beginning of the list, which is marked by
  6718. the label. }
  6719. \newcommand{\CifGrammarRacket}{
  6720. \begin{array}{lcl}
  6721. \Atm &::=& \itm{bool} \\
  6722. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6723. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6724. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6725. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6726. \end{array}
  6727. }
  6728. \newcommand{\CifASTRacket}{
  6729. \begin{array}{lcl}
  6730. \Atm &::=& \BOOL{\itm{bool}} \\
  6731. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6732. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6733. \Tail &::= & \GOTO{\itm{label}} \\
  6734. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6735. \end{array}
  6736. }
  6737. \newcommand{\CifGrammarPython}{
  6738. \begin{array}{lcl}
  6739. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6740. \Exp &::= & \Atm \MID \CREAD{}
  6741. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6742. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6743. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6744. \Stmt &::=& \CPRINT{\Exp} \MID \Exp \\
  6745. &\MID& \CASSIGN{\Var}{\Exp}
  6746. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6747. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6748. \end{array}
  6749. }
  6750. \newcommand{\CifASTPython}{
  6751. \begin{array}{lcl}
  6752. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6753. \Exp &::= & \Atm \MID \READ{} \\
  6754. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6755. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6756. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6757. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6758. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6759. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6760. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6761. \end{array}
  6762. }
  6763. \begin{figure}[tbp]
  6764. \fbox{
  6765. \begin{minipage}{0.96\textwidth}
  6766. \small
  6767. {\if\edition\racketEd
  6768. \[
  6769. \begin{array}{l}
  6770. \gray{\CvarGrammarRacket} \\ \hline
  6771. \CifGrammarRacket \\
  6772. \begin{array}{lcl}
  6773. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6774. \end{array}
  6775. \end{array}
  6776. \]
  6777. \fi}
  6778. {\if\edition\pythonEd
  6779. \[
  6780. \begin{array}{l}
  6781. \CifGrammarPython \\
  6782. \begin{array}{lcl}
  6783. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6784. \end{array}
  6785. \end{array}
  6786. \]
  6787. \fi}
  6788. \end{minipage}
  6789. }
  6790. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6791. \label{fig:c1-concrete-syntax}
  6792. \end{figure}
  6793. \begin{figure}[tp]
  6794. \fbox{
  6795. \begin{minipage}{0.96\textwidth}
  6796. \small
  6797. {\if\edition\racketEd
  6798. \[
  6799. \begin{array}{l}
  6800. \gray{\CvarASTRacket} \\ \hline
  6801. \CifASTRacket \\
  6802. \begin{array}{lcl}
  6803. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6804. \end{array}
  6805. \end{array}
  6806. \]
  6807. \fi}
  6808. {\if\edition\pythonEd
  6809. \[
  6810. \begin{array}{l}
  6811. \CifASTPython \\
  6812. \begin{array}{lcl}
  6813. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6814. \end{array}
  6815. \end{array}
  6816. \]
  6817. \fi}
  6818. \end{minipage}
  6819. }
  6820. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6821. (Figure~\ref{fig:c0-syntax})}.}
  6822. \label{fig:c1-syntax}
  6823. \end{figure}
  6824. \section{The \LangXIf{} Language}
  6825. \label{sec:x86-if}
  6826. \index{subject}{x86} To implement the new logical operations, the comparison
  6827. operations, and the \key{if} expression\python{ and statement}, we need to delve further into
  6828. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6829. define the concrete and abstract syntax for the \LangXIf{} subset
  6830. of x86, which includes instructions for logical operations,
  6831. comparisons, and \racket{conditional} jumps.
  6832. One challenge is that x86 does not provide an instruction that
  6833. directly implements logical negation (\code{not} in \LangIf{} and
  6834. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6835. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6836. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6837. bit of its arguments, and writes the results into its second argument.
  6838. Recall the truth table for exclusive-or:
  6839. \begin{center}
  6840. \begin{tabular}{l|cc}
  6841. & 0 & 1 \\ \hline
  6842. 0 & 0 & 1 \\
  6843. 1 & 1 & 0
  6844. \end{tabular}
  6845. \end{center}
  6846. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6847. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6848. for the bit $1$, the result is the opposite of the second bit. Thus,
  6849. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6850. the first argument as follows, where $\Arg$ is the translation of
  6851. $\Atm$.
  6852. \[
  6853. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6854. \qquad\Rightarrow\qquad
  6855. \begin{array}{l}
  6856. \key{movq}~ \Arg\key{,} \Var\\
  6857. \key{xorq}~ \key{\$1,} \Var
  6858. \end{array}
  6859. \]
  6860. \begin{figure}[tp]
  6861. \fbox{
  6862. \begin{minipage}{0.96\textwidth}
  6863. \[
  6864. \begin{array}{lcl}
  6865. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6866. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6867. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6868. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6869. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6870. \key{subq} \; \Arg\key{,} \Arg \MID
  6871. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6872. && \gray{ \key{callq} \; \itm{label} \MID
  6873. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6874. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6875. \MID \key{xorq}~\Arg\key{,}~\Arg
  6876. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6877. && \key{set}cc~\Arg
  6878. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6879. \MID \key{j}cc~\itm{label}
  6880. \\
  6881. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6882. & & \gray{ \key{main:} \; \Instr\ldots }
  6883. \end{array}
  6884. \]
  6885. \end{minipage}
  6886. }
  6887. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6888. \label{fig:x86-1-concrete}
  6889. \end{figure}
  6890. \begin{figure}[tp]
  6891. \fbox{
  6892. \begin{minipage}{0.98\textwidth}
  6893. \small
  6894. {\if\edition\racketEd
  6895. \[
  6896. \begin{array}{lcl}
  6897. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6898. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6899. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6900. \MID \BYTEREG{\itm{bytereg}} \\
  6901. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6902. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6903. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6904. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6905. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6906. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6907. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6908. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6909. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6910. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6911. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6912. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6913. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6914. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6915. \end{array}
  6916. \]
  6917. \fi}
  6918. %
  6919. {\if\edition\pythonEd
  6920. \[
  6921. \begin{array}{lcl}
  6922. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  6923. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  6924. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6925. \MID \BYTEREG{\itm{bytereg}} \\
  6926. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  6927. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  6928. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  6929. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  6930. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  6931. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6932. \MID \PUSHQ{\Arg}} \\
  6933. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6934. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  6935. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  6936. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  6937. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  6938. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  6939. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6940. \end{array}
  6941. \]
  6942. \fi}
  6943. \end{minipage}
  6944. }
  6945. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6946. \label{fig:x86-1}
  6947. \end{figure}
  6948. Next we consider the x86 instructions that are relevant for compiling
  6949. the comparison operations. The \key{cmpq} instruction compares its two
  6950. arguments to determine whether one argument is less than, equal, or
  6951. greater than the other argument. The \key{cmpq} instruction is unusual
  6952. regarding the order of its arguments and where the result is
  6953. placed. The argument order is backwards: if you want to test whether
  6954. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6955. \key{cmpq} is placed in the special EFLAGS register. This register
  6956. cannot be accessed directly but it can be queried by a number of
  6957. instructions, including the \key{set} instruction. The instruction
  6958. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6959. depending on whether the comparison comes out according to the
  6960. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6961. for less-or-equal, \key{g} for greater, \key{ge} for
  6962. greater-or-equal). The \key{set} instruction has a quirk in
  6963. that its destination argument must be single byte register, such as
  6964. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6965. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6966. instruction can be used to move from a single byte register to a
  6967. normal 64-bit register. The abstract syntax for the \code{set}
  6968. instruction differs from the concrete syntax in that it separates the
  6969. instruction name from the condition code.
  6970. \python{The x86 instructions for jumping are relevant to the
  6971. compilation of \key{if} expressions.}
  6972. %
  6973. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6974. counter to the address of the instruction after the specified
  6975. label.}
  6976. %
  6977. \racket{The x86 instruction for conditional jump is relevant to the
  6978. compilation of \key{if} expressions.}
  6979. %
  6980. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6981. counter to point to the instruction after \itm{label} depending on
  6982. whether the result in the EFLAGS register matches the condition code
  6983. \itm{cc}, otherwise the jump instruction falls through to the next
  6984. instruction. Like the abstract syntax for \code{set}, the abstract
  6985. syntax for conditional jump separates the instruction name from the
  6986. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6987. to \code{jle foo}. Because the conditional jump instruction relies on
  6988. the EFLAGS register, it is common for it to be immediately preceded by
  6989. a \key{cmpq} instruction to set the EFLAGS register.
  6990. \section{Shrink the \LangIf{} Language}
  6991. \label{sec:shrink-Lif}
  6992. The \LangIf{} language includes several features that are easily
  6993. expressible with other features. For example, \code{and} and \code{or}
  6994. are expressible using \code{if} as follows.
  6995. \begin{align*}
  6996. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6997. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6998. \end{align*}
  6999. By performing these translations in the front-end of the compiler,
  7000. subsequent passes of the compiler do not need to deal with these features,
  7001. making the passes shorter.
  7002. %% For example, subtraction is
  7003. %% expressible using addition and negation.
  7004. %% \[
  7005. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  7006. %% \]
  7007. %% Several of the comparison operations are expressible using less-than
  7008. %% and logical negation.
  7009. %% \[
  7010. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  7011. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  7012. %% \]
  7013. %% The \key{let} is needed in the above translation to ensure that
  7014. %% expression $e_1$ is evaluated before $e_2$.
  7015. On the other hand, sometimes translations reduce the efficiency of the
  7016. generated code by increasing the number of instructions. For example,
  7017. expressing subtraction in terms of negation
  7018. \[
  7019. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7020. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7021. \]
  7022. produces code with two x86 instructions (\code{negq} and \code{addq})
  7023. instead of just one (\code{subq}).
  7024. %% However,
  7025. %% these differences typically do not affect the number of accesses to
  7026. %% memory, which is the primary factor that determines execution time on
  7027. %% modern computer architectures.
  7028. \begin{exercise}\normalfont
  7029. %
  7030. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7031. the language by translating them to \code{if} expressions in \LangIf{}.
  7032. %
  7033. Create four test programs that involve these operators.
  7034. %
  7035. {\if\edition\racketEd
  7036. In the \code{run-tests.rkt} script, add the following entry for
  7037. \code{shrink} to the list of passes (it should be the only pass at
  7038. this point).
  7039. \begin{lstlisting}
  7040. (list "shrink" shrink interp_Lif type-check-Lif)
  7041. \end{lstlisting}
  7042. This instructs \code{interp-tests} to run the intepreter
  7043. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7044. output of \code{shrink}.
  7045. \fi}
  7046. %
  7047. Run the script to test your compiler on all the test programs.
  7048. \end{exercise}
  7049. {\if\edition\racketEd
  7050. \section{Uniquify Variables}
  7051. \label{sec:uniquify-Lif}
  7052. Add cases to \code{uniquify-exp} to handle Boolean constants and
  7053. \code{if} expressions.
  7054. \begin{exercise}\normalfont
  7055. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7056. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7057. \begin{lstlisting}
  7058. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7059. \end{lstlisting}
  7060. Run the script to test your compiler.
  7061. \end{exercise}
  7062. \fi}
  7063. \section{Remove Complex Operands}
  7064. \label{sec:remove-complex-opera-Lif}
  7065. The output language of \code{remove\_complex\_operands} is
  7066. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  7067. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7068. but the \code{if} expression is not. All three sub-expressions of an
  7069. \code{if} are allowed to be complex expressions but the operands of
  7070. \code{not} and the comparisons must be atomic.
  7071. %
  7072. \python{We add a new language form, the \code{Begin} expression, to aid
  7073. in the translation of \code{if} expressions. When we recursively
  7074. process the two branches of the \code{if}, we generate temporary
  7075. variables and their initializing expressions. However, these
  7076. expressions may contain side effects and should only be executed
  7077. when the condition of the \code{if} is true (for the ``then''
  7078. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7079. a way to initialize the temporary variables within the two branches
  7080. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7081. form execute the statements $ss$ and then returns the result of
  7082. expression $e$.}
  7083. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  7084. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  7085. according to whether the output needs to be \Exp{} or \Atm{} as
  7086. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  7087. particularly important to \textbf{not} replace its condition with a
  7088. temporary variable because that would interfere with the generation of
  7089. high-quality output in the \code{explicate\_control} pass.
  7090. \newcommand{\LifMonadASTPython}{
  7091. \begin{array}{rcl}
  7092. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7093. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7094. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7095. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7096. \Atm &::=& \BOOL{\itm{bool}}\\
  7097. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7098. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7099. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7100. \end{array}
  7101. }
  7102. \begin{figure}[tp]
  7103. \centering
  7104. \fbox{
  7105. \begin{minipage}{0.96\textwidth}
  7106. {\if\edition\racketEd
  7107. \[
  7108. \begin{array}{rcl}
  7109. Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  7110. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7111. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7112. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7113. &\MID& \UNIOP{\key{not}}{\Atm} \\
  7114. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7115. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7116. \end{array}
  7117. \]
  7118. \fi}
  7119. {\if\edition\pythonEd
  7120. \[
  7121. \begin{array}{l}
  7122. \gray{\LvarMonadASTPython} \\ \hline
  7123. \LifMonadASTPython \\
  7124. \begin{array}{rcl}
  7125. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7126. \end{array}
  7127. \end{array}
  7128. \]
  7129. \fi}
  7130. \end{minipage}
  7131. }
  7132. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  7133. \label{fig:Lif-anf-syntax}
  7134. \end{figure}
  7135. \begin{exercise}\normalfont
  7136. %
  7137. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7138. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7139. %
  7140. Create three new \LangIf{} programs that exercise the interesting
  7141. code in this pass.
  7142. %
  7143. {\if\edition\racketEd
  7144. In the \code{run-tests.rkt} script, add the following entry to the
  7145. list of \code{passes} and then run the script to test your compiler.
  7146. \begin{lstlisting}
  7147. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  7148. \end{lstlisting}
  7149. \fi}
  7150. \end{exercise}
  7151. \section{Explicate Control}
  7152. \label{sec:explicate-control-Lif}
  7153. \racket{Recall that the purpose of \code{explicate\_control} is to
  7154. make the order of evaluation explicit in the syntax of the program.
  7155. With the addition of \key{if} this get more interesting.}
  7156. %
  7157. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7158. %
  7159. The main challenge to overcome is that the condition of an \key{if}
  7160. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7161. condition must be a comparison.
  7162. As a motivating example, consider the following program that has an
  7163. \key{if} expression nested in the condition of another \key{if}.%
  7164. \python{\footnote{Programmers rarely write nested \code{if}
  7165. expressions, but it is not uncommon for the condition of an
  7166. \code{if} statement to be a call of a function that also contains an
  7167. \code{if} statement. When such a function is inlined, the result is
  7168. a nested \code{if} that requires the techniques discussed in this
  7169. section.}}
  7170. % cond_test_41.rkt, if_lt_eq.py
  7171. \begin{center}
  7172. \begin{minipage}{0.96\textwidth}
  7173. {\if\edition\racketEd
  7174. \begin{lstlisting}
  7175. (let ([x (read)])
  7176. (let ([y (read)])
  7177. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7178. (+ y 2)
  7179. (+ y 10))))
  7180. \end{lstlisting}
  7181. \fi}
  7182. {\if\edition\pythonEd
  7183. \begin{lstlisting}
  7184. x = input_int()
  7185. y = input_int()
  7186. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7187. \end{lstlisting}
  7188. \fi}
  7189. \end{minipage}
  7190. \end{center}
  7191. %
  7192. The naive way to compile \key{if} and the comparison operations would
  7193. be to handle each of them in isolation, regardless of their context.
  7194. Each comparison would be translated into a \key{cmpq} instruction
  7195. followed by several instructions to move the result from the EFLAGS
  7196. register into a general purpose register or stack location. Each
  7197. \key{if} would be translated into a \key{cmpq} instruction followed by
  7198. a conditional jump. The generated code for the inner \key{if} in the
  7199. above example would be as follows.
  7200. \begin{center}
  7201. \begin{minipage}{0.96\textwidth}
  7202. \begin{lstlisting}
  7203. cmpq $1, x
  7204. setl %al
  7205. movzbq %al, tmp
  7206. cmpq $1, tmp
  7207. je then_branch_1
  7208. jmp else_branch_1
  7209. \end{lstlisting}
  7210. \end{minipage}
  7211. \end{center}
  7212. However, if we take context into account we can do better and reduce
  7213. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7214. Our goal will be to compile \key{if} expressions so that the relevant
  7215. comparison instruction appears directly before the conditional jump.
  7216. For example, we want to generate the following code for the inner
  7217. \code{if}.
  7218. \begin{center}
  7219. \begin{minipage}{0.96\textwidth}
  7220. \begin{lstlisting}
  7221. cmpq $1, x
  7222. jl then_branch_1
  7223. jmp else_branch_1
  7224. \end{lstlisting}
  7225. \end{minipage}
  7226. \end{center}
  7227. One way to achieve this goal is to reorganize the code at the level of
  7228. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7229. the following code.
  7230. \begin{center}
  7231. \begin{minipage}{0.96\textwidth}
  7232. {\if\edition\racketEd
  7233. \begin{lstlisting}
  7234. (let ([x (read)])
  7235. (let ([y (read)])
  7236. (if (< x 1)
  7237. (if (eq? x 0)
  7238. (+ y 2)
  7239. (+ y 10))
  7240. (if (eq? x 2)
  7241. (+ y 2)
  7242. (+ y 10)))))
  7243. \end{lstlisting}
  7244. \fi}
  7245. {\if\edition\pythonEd
  7246. \begin{lstlisting}
  7247. x = input_int()
  7248. y = intput_int()
  7249. print(((y + 2) if x == 0 else (y + 10)) \
  7250. if (x < 1) \
  7251. else ((y + 2) if (x == 2) else (y + 10)))
  7252. \end{lstlisting}
  7253. \fi}
  7254. \end{minipage}
  7255. \end{center}
  7256. Unfortunately, this approach duplicates the two branches from the
  7257. outer \code{if} and a compiler must never duplicate code! After all,
  7258. the two branches could have been very large expressions.
  7259. We need a way to perform the above transformation but without
  7260. duplicating code. That is, we need a way for different parts of a
  7261. program to refer to the same piece of code.
  7262. %
  7263. Put another way, we need to move away from abstract syntax
  7264. \emph{trees} and instead use \emph{graphs}.
  7265. %
  7266. At the level of x86 assembly this is straightforward because we can
  7267. label the code for each branch and insert jumps in all the places that
  7268. need to execute the branch.
  7269. %
  7270. Likewise, our language \LangCIf{} provides the ability to label a
  7271. sequence of code and to jump to a label via \code{goto}.
  7272. %
  7273. %% In particular, we use a standard program representation called a
  7274. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7275. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7276. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7277. %% edge represents a jump to another block.
  7278. %
  7279. %% The nice thing about the output of \code{explicate\_control} is that
  7280. %% there are no unnecessary comparisons and every comparison is part of a
  7281. %% conditional jump.
  7282. %% The down-side of this output is that it includes
  7283. %% trivial blocks, such as the blocks labeled \code{block92} through
  7284. %% \code{block95}, that only jump to another block. We discuss a solution
  7285. %% to this problem in Section~\ref{sec:opt-jumps}.
  7286. {\if\edition\racketEd
  7287. %
  7288. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7289. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7290. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7291. former function translates expressions in tail position whereas the
  7292. later function translates expressions on the right-hand-side of a
  7293. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7294. have a new kind of position to deal with: the predicate position of
  7295. the \key{if}. We need another function, \code{explicate\_pred}, that
  7296. decides how to compile an \key{if} by analyzing its predicate. So
  7297. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7298. tails for the then-branch and else-branch and outputs a tail. In the
  7299. following paragraphs we discuss specific cases in the
  7300. \code{explicate\_tail}, \code{explicate\_assign}, and
  7301. \code{explicate\_pred} functions.
  7302. %
  7303. \fi}
  7304. %
  7305. {\if\edition\pythonEd
  7306. %
  7307. We recommend implementing \code{explicate\_control} using the
  7308. following four auxiliary functions.
  7309. \begin{description}
  7310. \item[\code{explicate\_effect}] generates code for expressions as
  7311. statements, so their result is ignored and only their side effects
  7312. matter.
  7313. \item[\code{explicate\_assign}] generates code for expressions
  7314. on the right-hand side of an assignment.
  7315. \item[\code{explicate\_pred}] generates code for an \code{if}
  7316. expression or statement by analyzing the condition expression.
  7317. \item[\code{explicate\_stmt}] generates code for statements.
  7318. \end{description}
  7319. These four functions should build the dictionary of basic blocks. The
  7320. following auxiliary function can be used to create a new basic block
  7321. from a list of statements. It returns a \code{goto} statement that
  7322. jumps to the new basic block.
  7323. \begin{center}
  7324. \begin{minipage}{\textwidth}
  7325. \begin{lstlisting}
  7326. def create_block(stmts, basic_blocks):
  7327. label = label_name(generate_name('block'))
  7328. basic_blocks[label] = stmts
  7329. return Goto(label)
  7330. \end{lstlisting}
  7331. \end{minipage}
  7332. \end{center}
  7333. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7334. \code{explicate\_control} pass.
  7335. The \code{explicate\_effect} function has three parameters: 1) the
  7336. expression to be compiled, 2) the already-compiled code for this
  7337. expression's \emph{continuation}, that is, the list of statements that
  7338. should execute after this expression, and 3) the dictionary of
  7339. generated basic blocks. The \code{explicate\_effect} function returns
  7340. a list of \LangCIf{} statements and it may add to the dictionary of
  7341. basic blocks.
  7342. %
  7343. Let's consider a few of the cases for the expression to be compiled.
  7344. If the expression to be compiled is a constant, then it can be
  7345. discarded because it has no side effects. If it's a \CREAD{}, then it
  7346. has a side-effect and should be preserved. So the expression should be
  7347. translated into a statement using the \code{Expr} AST class. If the
  7348. expression to be compiled is an \code{if} expression, we translate the
  7349. two branches using \code{explicate\_effect} and then translate the
  7350. condition expression using \code{explicate\_pred}, which generates
  7351. code for the entire \code{if}.
  7352. The \code{explicate\_assign} function has four parameters: 1) the
  7353. right-hand-side of the assignment, 2) the left-hand-side of the
  7354. assignment (the variable), 3) the continuation, and 4) the dictionary
  7355. of basic blocks. The \code{explicate\_assign} function returns a list
  7356. of \LangCIf{} statements and it may add to the dictionary of basic
  7357. blocks.
  7358. When the right-hand-side is an \code{if} expression, there is some
  7359. work to do. In particular, the two branches should be translated using
  7360. \code{explicate\_assign} and the condition expression should be
  7361. translated using \code{explicate\_pred}. Otherwise we can simply
  7362. generate an assignment statement, with the given left and right-hand
  7363. sides, concatenated with its continuation.
  7364. \begin{figure}[tbp]
  7365. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7366. def explicate_effect(e, cont, basic_blocks):
  7367. match e:
  7368. case IfExp(test, body, orelse):
  7369. ...
  7370. case Call(func, args):
  7371. ...
  7372. case Begin(body, result):
  7373. ...
  7374. case _:
  7375. ...
  7376. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7377. match rhs:
  7378. case IfExp(test, body, orelse):
  7379. ...
  7380. case Begin(body, result):
  7381. ...
  7382. case _:
  7383. return [Assign([lhs], rhs)] + cont
  7384. def explicate_pred(cnd, thn, els, basic_blocks):
  7385. match cnd:
  7386. case Compare(left, [op], [right]):
  7387. goto_thn = create_block(thn, basic_blocks)
  7388. goto_els = create_block(els, basic_blocks)
  7389. return [If(cnd, [goto_thn], [goto_els])]
  7390. case Constant(True):
  7391. return thn;
  7392. case Constant(False):
  7393. return els;
  7394. case UnaryOp(Not(), operand):
  7395. ...
  7396. case IfExp(test, body, orelse):
  7397. ...
  7398. case Begin(body, result):
  7399. ...
  7400. case _:
  7401. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7402. [create_block(els, basic_blocks)],
  7403. [create_block(thn, basic_blocks)])]
  7404. def explicate_stmt(s, cont, basic_blocks):
  7405. match s:
  7406. case Assign([lhs], rhs):
  7407. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7408. case Expr(value):
  7409. return explicate_effect(value, cont, basic_blocks)
  7410. case If(test, body, orelse):
  7411. ...
  7412. def explicate_control(p):
  7413. match p:
  7414. case Module(body):
  7415. new_body = [Return(Constant(0))]
  7416. basic_blocks = {}
  7417. for s in reversed(body):
  7418. new_body = explicate_stmt(s, new_body, basic_blocks)
  7419. basic_blocks[label_name('start')] = new_body
  7420. return CProgram(basic_blocks)
  7421. \end{lstlisting}
  7422. \caption{Skeleton for the \code{explicate\_control} pass.}
  7423. \label{fig:explicate-control-Lif}
  7424. \end{figure}
  7425. \fi}
  7426. {\if\edition\racketEd
  7427. %
  7428. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7429. additional cases for Boolean constants and \key{if}. The cases for
  7430. \code{if} should recursively compile the two branches using either
  7431. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7432. cases should then invoke \code{explicate\_pred} on the condition
  7433. expression, passing in the generated code for the two branches. For
  7434. example, consider the following program with an \code{if} in tail
  7435. position.
  7436. \begin{lstlisting}
  7437. (let ([x (read)])
  7438. (if (eq? x 0) 42 777))
  7439. \end{lstlisting}
  7440. The two branches are recursively compiled to \code{return 42;} and
  7441. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7442. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7443. used as the result for \code{explicate\_tail}.
  7444. Next let us consider a program with an \code{if} on the right-hand
  7445. side of a \code{let}.
  7446. \begin{lstlisting}
  7447. (let ([y (read)])
  7448. (let ([x (if (eq? y 0) 40 777)])
  7449. (+ x 2)))
  7450. \end{lstlisting}
  7451. Note that the body of the inner \code{let} will have already been
  7452. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7453. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7454. to recursively process both branches of the \code{if}, so we generate
  7455. the following block using an auxiliary function named \code{create\_block}.
  7456. \begin{lstlisting}
  7457. block_6:
  7458. return (+ x 2)
  7459. \end{lstlisting}
  7460. and use \code{goto block\_6;} as the \code{cont} argument for
  7461. compiling the branches. So the two branches compile to
  7462. \begin{lstlisting}
  7463. x = 40;
  7464. goto block_6;
  7465. \end{lstlisting}
  7466. and
  7467. \begin{lstlisting}
  7468. x = 777;
  7469. goto block_6;
  7470. \end{lstlisting}
  7471. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7472. 0)} and the above code for the branches.
  7473. \fi}
  7474. {\if\edition\racketEd
  7475. \begin{figure}[tbp]
  7476. \begin{lstlisting}
  7477. (define (explicate_pred cnd thn els)
  7478. (match cnd
  7479. [(Var x) ___]
  7480. [(Let x rhs body) ___]
  7481. [(Prim 'not (list e)) ___]
  7482. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7483. (IfStmt (Prim op es) (create_block thn)
  7484. (create_block els))]
  7485. [(Bool b) (if b thn els)]
  7486. [(If cnd^ thn^ els^) ___]
  7487. [else (error "explicate_pred unhandled case" cnd)]))
  7488. \end{lstlisting}
  7489. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7490. \label{fig:explicate-pred}
  7491. \end{figure}
  7492. \fi}
  7493. \racket{The skeleton for the \code{explicate\_pred} function is given
  7494. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7495. 1) \code{cnd}, the condition expression of the \code{if},
  7496. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7497. and 3) \code{els}, the code generated by
  7498. explicate for the ``else'' branch. The \code{explicate\_pred}
  7499. function should match on \code{cnd} with a case for
  7500. every kind of expression that can have type \code{Boolean}.}
  7501. %
  7502. \python{The \code{explicate\_pred} function has four parameters: 1)
  7503. the condition expression, 2) the generated statements for the
  7504. ``then'' branch, 3) the generated statements for the ``else''
  7505. branch, and 4) the dictionary of basic blocks. The
  7506. \code{explicate\_pred} function returns a list of \LangCIf{}
  7507. statements and it may add to the dictionary of basic blocks.}
  7508. Consider the case for comparison operators. We translate the
  7509. comparison to an \code{if} statement whose branches are \code{goto}
  7510. statements created by applying \code{create\_block} to the code
  7511. generated for the \code{thn} and \code{els} branches. Let us
  7512. illustrate this translation with an example. Returning
  7513. to the program with an \code{if} expression in tail position,
  7514. we invoke \code{explicate\_pred} on its condition
  7515. \racket{\code{(eq? x 0)}}
  7516. \python{\code{x == 0}}
  7517. which happens to be a comparison operator.
  7518. {\if\edition\racketEd
  7519. \begin{lstlisting}
  7520. (let ([x (read)])
  7521. (if (eq? x 0) 42 777))
  7522. \end{lstlisting}
  7523. \fi}
  7524. {\if\edition\pythonEd
  7525. \begin{lstlisting}
  7526. x = input_int()
  7527. 42 if x == 0 else 777
  7528. \end{lstlisting}
  7529. \fi}
  7530. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7531. statements, from which we now create the following blocks.
  7532. \begin{center}
  7533. \begin{minipage}{\textwidth}
  7534. \begin{lstlisting}
  7535. block_1:
  7536. return 42;
  7537. block_2:
  7538. return 777;
  7539. \end{lstlisting}
  7540. \end{minipage}
  7541. \end{center}
  7542. %
  7543. So \code{explicate\_pred} compiles the comparison
  7544. \racket{\code{(eq? x 0)}}
  7545. \python{\code{x == 0}}
  7546. to the following \code{if} statement.
  7547. %
  7548. {\if\edition\racketEd
  7549. \begin{center}
  7550. \begin{minipage}{\textwidth}
  7551. \begin{lstlisting}
  7552. if (eq? x 0)
  7553. goto block_1;
  7554. else
  7555. goto block_2;
  7556. \end{lstlisting}
  7557. \end{minipage}
  7558. \end{center}
  7559. \fi}
  7560. {\if\edition\pythonEd
  7561. \begin{center}
  7562. \begin{minipage}{\textwidth}
  7563. \begin{lstlisting}
  7564. if x == 0:
  7565. goto block_1;
  7566. else
  7567. goto block_2;
  7568. \end{lstlisting}
  7569. \end{minipage}
  7570. \end{center}
  7571. \fi}
  7572. Next consider the case for Boolean constants. We perform a kind of
  7573. partial evaluation\index{subject}{partial evaluation} and output
  7574. either the \code{thn} or \code{els} branch depending on whether the
  7575. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7576. following program.
  7577. {\if\edition\racketEd
  7578. \begin{center}
  7579. \begin{minipage}{\textwidth}
  7580. \begin{lstlisting}
  7581. (if #t 42 777)
  7582. \end{lstlisting}
  7583. \end{minipage}
  7584. \end{center}
  7585. \fi}
  7586. {\if\edition\pythonEd
  7587. \begin{center}
  7588. \begin{minipage}{\textwidth}
  7589. \begin{lstlisting}
  7590. 42 if True else 777
  7591. \end{lstlisting}
  7592. \end{minipage}
  7593. \end{center}
  7594. \fi}
  7595. %
  7596. Again, the two branches \code{42} and \code{777} were compiled to
  7597. \code{return} statements, so \code{explicate\_pred} compiles the
  7598. constant
  7599. \racket{\code{\#t}}
  7600. \python{\code{True}}
  7601. to the code for the ``then'' branch.
  7602. \begin{center}
  7603. \begin{minipage}{\textwidth}
  7604. \begin{lstlisting}
  7605. return 42;
  7606. \end{lstlisting}
  7607. \end{minipage}
  7608. \end{center}
  7609. %
  7610. This case demonstrates that we sometimes discard the \code{thn} or
  7611. \code{els} blocks that are input to \code{explicate\_pred}.
  7612. The case for \key{if} expressions in \code{explicate\_pred} is
  7613. particularly illuminating because it deals with the challenges we
  7614. discussed above regarding nested \key{if} expressions
  7615. (Figure~\ref{fig:explicate-control-s1-38}). The
  7616. \racket{\lstinline{thn^}}\python{\code{body}} and
  7617. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7618. \key{if} inherit their context from the current one, that is,
  7619. predicate context. So you should recursively apply
  7620. \code{explicate\_pred} to the
  7621. \racket{\lstinline{thn^}}\python{\code{body}} and
  7622. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7623. those recursive calls, pass \code{thn} and \code{els} as the extra
  7624. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7625. inside each recursive call. As discussed above, to avoid duplicating
  7626. code, we need to add them to the dictionary of basic blocks so that we
  7627. can instead refer to them by name and execute them with a \key{goto}.
  7628. {\if\edition\pythonEd
  7629. %
  7630. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7631. three parameters: 1) the statement to be compiled, 2) the code for its
  7632. continuation, and 3) the dictionary of basic blocks. The
  7633. \code{explicate\_stmt} returns a list of statements and it may add to
  7634. the dictionary of basic blocks. The cases for assignment and an
  7635. expression-statement are given in full in the skeleton code: they
  7636. simply dispatch to \code{explicate\_assign} and
  7637. \code{explicate\_effect}, respectively. The case for \code{if}
  7638. statements is not given, and is similar to the case for \code{if}
  7639. expressions.
  7640. The \code{explicate\_control} function itself is given in
  7641. Figure~\ref{fig:explicate-control-Lif}. It applies
  7642. \code{explicate\_stmt} to each statement in the program, from back to
  7643. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7644. used as the continuation parameter in the next call to
  7645. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7646. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7647. the dictionary of basic blocks, labeling it as the ``start'' block.
  7648. %
  7649. \fi}
  7650. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7651. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7652. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7653. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7654. %% results from the two recursive calls. We complete the case for
  7655. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7656. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7657. %% the result $B_5$.
  7658. %% \[
  7659. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7660. %% \quad\Rightarrow\quad
  7661. %% B_5
  7662. %% \]
  7663. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7664. %% inherit the current context, so they are in tail position. Thus, the
  7665. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7666. %% \code{explicate\_tail}.
  7667. %% %
  7668. %% We need to pass $B_0$ as the accumulator argument for both of these
  7669. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7670. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7671. %% to the control-flow graph and obtain a promised goto $G_0$.
  7672. %% %
  7673. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7674. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7675. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7676. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7677. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7678. %% \[
  7679. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7680. %% \]
  7681. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7682. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7683. %% should not be confused with the labels for the blocks that appear in
  7684. %% the generated code. We initially construct unlabeled blocks; we only
  7685. %% attach labels to blocks when we add them to the control-flow graph, as
  7686. %% we see in the next case.
  7687. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7688. %% function. The context of the \key{if} is an assignment to some
  7689. %% variable $x$ and then the control continues to some promised block
  7690. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7691. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7692. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7693. %% branches of the \key{if} inherit the current context, so they are in
  7694. %% assignment positions. Let $B_2$ be the result of applying
  7695. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7696. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7697. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7698. %% the result of applying \code{explicate\_pred} to the predicate
  7699. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7700. %% translates to the promise $B_4$.
  7701. %% \[
  7702. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7703. %% \]
  7704. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7705. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7706. \code{remove\_complex\_operands} pass and then the
  7707. \code{explicate\_control} pass on the example program. We walk through
  7708. the output program.
  7709. %
  7710. Following the order of evaluation in the output of
  7711. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7712. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7713. in the predicate of the inner \key{if}. In the output of
  7714. \code{explicate\_control}, in the
  7715. block labeled \code{start}, are two assignment statements followed by a
  7716. \code{if} statement that branches to \code{block\_8} or
  7717. \code{block\_9}. The blocks associated with those labels contain the
  7718. translations of the code
  7719. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7720. and
  7721. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7722. respectively. In particular, we start \code{block\_8} with the
  7723. comparison
  7724. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7725. and then branch to \code{block\_4} or \code{block\_5}.
  7726. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7727. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7728. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7729. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7730. and go directly to \code{block\_2} and \code{block\_3},
  7731. which we investigate in Section~\ref{sec:opt-jumps}.
  7732. Getting back to the example, \code{block\_2} and \code{block\_3},
  7733. corresponds to the two branches of the outer \key{if}, i.e.,
  7734. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7735. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7736. %
  7737. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7738. %
  7739. \python{The \code{block\_1} corresponds to the \code{print} statment
  7740. at the end of the program.}
  7741. \begin{figure}[tbp]
  7742. {\if\edition\racketEd
  7743. \begin{tabular}{lll}
  7744. \begin{minipage}{0.4\textwidth}
  7745. % cond_test_41.rkt
  7746. \begin{lstlisting}
  7747. (let ([x (read)])
  7748. (let ([y (read)])
  7749. (if (if (< x 1)
  7750. (eq? x 0)
  7751. (eq? x 2))
  7752. (+ y 2)
  7753. (+ y 10))))
  7754. \end{lstlisting}
  7755. \end{minipage}
  7756. &
  7757. $\Rightarrow$
  7758. &
  7759. \begin{minipage}{0.55\textwidth}
  7760. \begin{lstlisting}
  7761. start:
  7762. x = (read);
  7763. y = (read);
  7764. if (< x 1)
  7765. goto block_8;
  7766. else
  7767. goto block_9;
  7768. block_8:
  7769. if (eq? x 0)
  7770. goto block_4;
  7771. else
  7772. goto block_5;
  7773. block_9:
  7774. if (eq? x 2)
  7775. goto block_6;
  7776. else
  7777. goto block_7;
  7778. block_4:
  7779. goto block_2;
  7780. block_5:
  7781. goto block_3;
  7782. block_6:
  7783. goto block_2;
  7784. block_7:
  7785. goto block_3;
  7786. block_2:
  7787. return (+ y 2);
  7788. block_3:
  7789. return (+ y 10);
  7790. \end{lstlisting}
  7791. \end{minipage}
  7792. \end{tabular}
  7793. \fi}
  7794. {\if\edition\pythonEd
  7795. \begin{tabular}{lll}
  7796. \begin{minipage}{0.4\textwidth}
  7797. % cond_test_41.rkt
  7798. \begin{lstlisting}
  7799. x = input_int()
  7800. y = input_int()
  7801. print(y + 2 \
  7802. if (x == 0 \
  7803. if x < 1 \
  7804. else x == 2) \
  7805. else y + 10)
  7806. \end{lstlisting}
  7807. \end{minipage}
  7808. &
  7809. $\Rightarrow$
  7810. &
  7811. \begin{minipage}{0.55\textwidth}
  7812. \begin{lstlisting}
  7813. start:
  7814. x = input_int()
  7815. y = input_int()
  7816. if x < 1:
  7817. goto block_8
  7818. else:
  7819. goto block_9
  7820. block_8:
  7821. if x == 0:
  7822. goto block_4
  7823. else:
  7824. goto block_5
  7825. block_9:
  7826. if x == 2:
  7827. goto block_6
  7828. else:
  7829. goto block_7
  7830. block_4:
  7831. goto block_2
  7832. block_5:
  7833. goto block_3
  7834. block_6:
  7835. goto block_2
  7836. block_7:
  7837. goto block_3
  7838. block_2:
  7839. tmp_0 = y + 2
  7840. goto block_1
  7841. block_3:
  7842. tmp_0 = y + 10
  7843. goto block_1
  7844. block_1:
  7845. print(tmp_0)
  7846. return 0
  7847. \end{lstlisting}
  7848. \end{minipage}
  7849. \end{tabular}
  7850. \fi}
  7851. \caption{Translation from \LangIf{} to \LangCIf{}
  7852. via the \code{explicate\_control}.}
  7853. \label{fig:explicate-control-s1-38}
  7854. \end{figure}
  7855. {\if\edition\racketEd
  7856. The way in which the \code{shrink} pass transforms logical operations
  7857. such as \code{and} and \code{or} can impact the quality of code
  7858. generated by \code{explicate\_control}. For example, consider the
  7859. following program.
  7860. % cond_test_21.rkt, and_eq_input.py
  7861. \begin{lstlisting}
  7862. (if (and (eq? (read) 0) (eq? (read) 1))
  7863. 0
  7864. 42)
  7865. \end{lstlisting}
  7866. The \code{and} operation should transform into something that the
  7867. \code{explicate\_pred} function can still analyze and descend through to
  7868. reach the underlying \code{eq?} conditions. Ideally, your
  7869. \code{explicate\_control} pass should generate code similar to the
  7870. following for the above program.
  7871. \begin{center}
  7872. \begin{lstlisting}
  7873. start:
  7874. tmp1 = (read);
  7875. if (eq? tmp1 0) goto block40;
  7876. else goto block39;
  7877. block40:
  7878. tmp2 = (read);
  7879. if (eq? tmp2 1) goto block38;
  7880. else goto block39;
  7881. block38:
  7882. return 0;
  7883. block39:
  7884. return 42;
  7885. \end{lstlisting}
  7886. \end{center}
  7887. \fi}
  7888. \begin{exercise}\normalfont
  7889. \racket{
  7890. Implement the pass \code{explicate\_control} by adding the cases for
  7891. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7892. \code{explicate\_assign} functions. Implement the auxiliary function
  7893. \code{explicate\_pred} for predicate contexts.}
  7894. \python{Implement \code{explicate\_control} pass with its
  7895. four auxiliary functions.}
  7896. %
  7897. Create test cases that exercise all of the new cases in the code for
  7898. this pass.
  7899. %
  7900. {\if\edition\racketEd
  7901. Add the following entry to the list of \code{passes} in
  7902. \code{run-tests.rkt} and then run this script to test your compiler.
  7903. \begin{lstlisting}
  7904. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7905. \end{lstlisting}
  7906. \fi}
  7907. \end{exercise}
  7908. \clearpage
  7909. \section{Select Instructions}
  7910. \label{sec:select-Lif}
  7911. \index{subject}{instruction selection}
  7912. The \code{select\_instructions} pass translates \LangCIf{} to
  7913. \LangXIfVar{}.
  7914. %
  7915. \racket{Recall that we implement this pass using three auxiliary
  7916. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7917. $\Tail$.}
  7918. %
  7919. \racket{For $\Atm$, we have new cases for the Booleans.}
  7920. %
  7921. \python{We begin with the Boolean constants.}
  7922. We take the usual approach of encoding them as integers.
  7923. \[
  7924. \TRUE{} \quad\Rightarrow\quad \key{1}
  7925. \qquad\qquad
  7926. \FALSE{} \quad\Rightarrow\quad \key{0}
  7927. \]
  7928. For translating statements, we discuss a selection of cases. The \code{not}
  7929. operation can be implemented in terms of \code{xorq} as we discussed
  7930. at the beginning of this section. Given an assignment, if the
  7931. left-hand side variable is the same as the argument of \code{not},
  7932. then just the \code{xorq} instruction suffices.
  7933. \[
  7934. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7935. \quad\Rightarrow\quad
  7936. \key{xorq}~\key{\$}1\key{,}~\Var
  7937. \]
  7938. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7939. semantics of x86. In the following translation, let $\Arg$ be the
  7940. result of translating $\Atm$ to x86.
  7941. \[
  7942. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7943. \quad\Rightarrow\quad
  7944. \begin{array}{l}
  7945. \key{movq}~\Arg\key{,}~\Var\\
  7946. \key{xorq}~\key{\$}1\key{,}~\Var
  7947. \end{array}
  7948. \]
  7949. Next consider the cases for equality. Translating this operation to
  7950. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7951. instruction discussed above. We recommend translating an assignment
  7952. with an equality on the right-hand side into a sequence of three
  7953. instructions. \\
  7954. \begin{tabular}{lll}
  7955. \begin{minipage}{0.4\textwidth}
  7956. \begin{lstlisting}
  7957. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7958. \end{lstlisting}
  7959. \end{minipage}
  7960. &
  7961. $\Rightarrow$
  7962. &
  7963. \begin{minipage}{0.4\textwidth}
  7964. \begin{lstlisting}
  7965. cmpq |$\Arg_2$|, |$\Arg_1$|
  7966. sete %al
  7967. movzbq %al, |$\Var$|
  7968. \end{lstlisting}
  7969. \end{minipage}
  7970. \end{tabular} \\
  7971. The translations for the other comparison operators are similar to the
  7972. above but use different suffixes for the \code{set} instruction.
  7973. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7974. \key{goto} and \key{if} statements. Both are straightforward to
  7975. translate to x86.}
  7976. %
  7977. A \key{goto} statement becomes a jump instruction.
  7978. \[
  7979. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7980. \]
  7981. %
  7982. An \key{if} statement becomes a compare instruction followed by a
  7983. conditional jump (for the ``then'' branch) and the fall-through is to
  7984. a regular jump (for the ``else'' branch).\\
  7985. \begin{tabular}{lll}
  7986. \begin{minipage}{0.4\textwidth}
  7987. \begin{lstlisting}
  7988. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7989. goto |$\ell_1$||$\racket{\key{;}}$|
  7990. else|$\python{\key{:}}$|
  7991. goto |$\ell_2$||$\racket{\key{;}}$|
  7992. \end{lstlisting}
  7993. \end{minipage}
  7994. &
  7995. $\Rightarrow$
  7996. &
  7997. \begin{minipage}{0.4\textwidth}
  7998. \begin{lstlisting}
  7999. cmpq |$\Arg_2$|, |$\Arg_1$|
  8000. je |$\ell_1$|
  8001. jmp |$\ell_2$|
  8002. \end{lstlisting}
  8003. \end{minipage}
  8004. \end{tabular} \\
  8005. Again, the translations for the other comparison operators are similar to the
  8006. above but use different suffixes for the conditional jump instruction.
  8007. \python{Regarding the \key{return} statement, we recommend treating it
  8008. as an assignment to the \key{rax} register followed by a jump to the
  8009. conclusion of the \code{main} function.}
  8010. \begin{exercise}\normalfont
  8011. Expand your \code{select\_instructions} pass to handle the new
  8012. features of the \LangIf{} language.
  8013. %
  8014. {\if\edition\racketEd
  8015. Add the following entry to the list of \code{passes} in
  8016. \code{run-tests.rkt}
  8017. \begin{lstlisting}
  8018. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8019. \end{lstlisting}
  8020. \fi}
  8021. %
  8022. Run the script to test your compiler on all the test programs.
  8023. \end{exercise}
  8024. \section{Register Allocation}
  8025. \label{sec:register-allocation-Lif}
  8026. \index{subject}{register allocation}
  8027. The changes required for \LangIf{} affect liveness analysis, building the
  8028. interference graph, and assigning homes, but the graph coloring
  8029. algorithm itself does not change.
  8030. \subsection{Liveness Analysis}
  8031. \label{sec:liveness-analysis-Lif}
  8032. \index{subject}{liveness analysis}
  8033. Recall that for \LangVar{} we implemented liveness analysis for a
  8034. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8035. the addition of \key{if} expressions to \LangIf{},
  8036. \code{explicate\_control} produces many basic blocks.
  8037. %% We recommend that you create a new auxiliary function named
  8038. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8039. %% control-flow graph.
  8040. The first question is: in what order should we process the basic blocks?
  8041. Recall that to perform liveness analysis on a basic block we need to
  8042. know the live-after set for the last instruction in the block. If a
  8043. basic block has no successors (i.e. contains no jumps to other
  8044. blocks), then it has an empty live-after set and we can immediately
  8045. apply liveness analysis to it. If a basic block has some successors,
  8046. then we need to complete liveness analysis on those blocks
  8047. first. These ordering contraints are the reverse of a
  8048. \emph{topological order}\index{subject}{topological order} on a graph
  8049. representation of the program. In particular, the \emph{control flow
  8050. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8051. of a program has a node for each basic block and an edge for each jump
  8052. from one block to another. It is straightforward to generate a CFG
  8053. from the dictionary of basic blocks. One then transposes the CFG and
  8054. applies the topological sort algorithm.
  8055. %
  8056. %
  8057. \racket{We recommend using the \code{tsort} and \code{transpose}
  8058. functions of the Racket \code{graph} package to accomplish this.}
  8059. %
  8060. \python{We provide implementations of \code{topological\_sort} and
  8061. \code{transpose} in the file \code{graph.py} of the support code.}
  8062. %
  8063. As an aside, a topological ordering is only guaranteed to exist if the
  8064. graph does not contain any cycles. This is the case for the
  8065. control-flow graphs that we generate from \LangIf{} programs.
  8066. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8067. and learn how to handle cycles in the control-flow graph.
  8068. \racket{You'll need to construct a directed graph to represent the
  8069. control-flow graph. Do not use the \code{directed-graph} of the
  8070. \code{graph} package because that only allows at most one edge
  8071. between each pair of vertices, but a control-flow graph may have
  8072. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8073. file in the support code implements a graph representation that
  8074. allows multiple edges between a pair of vertices.}
  8075. {\if\edition\racketEd
  8076. The next question is how to analyze jump instructions. Recall that in
  8077. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8078. \code{label->live} that maps each label to the set of live locations
  8079. at the beginning of its block. We use \code{label->live} to determine
  8080. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8081. that we have many basic blocks, \code{label->live} needs to be updated
  8082. as we process the blocks. In particular, after performing liveness
  8083. analysis on a block, we take the live-before set of its first
  8084. instruction and associate that with the block's label in the
  8085. \code{label->live}.
  8086. \fi}
  8087. %
  8088. {\if\edition\pythonEd
  8089. %
  8090. The next question is how to analyze jump instructions. The locations
  8091. that are live before a \code{jmp} should be the locations in
  8092. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8093. maintaining a dictionary named \code{live\_before\_block} that maps each
  8094. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8095. block. After performing liveness analysis on each block, we take the
  8096. live-before set of its first instruction and associate that with the
  8097. block's label in the \code{live\_before\_block} dictionary.
  8098. %
  8099. \fi}
  8100. In \LangXIfVar{} we also have the conditional jump
  8101. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8102. this instruction is particularly interesting because, during
  8103. compilation, we do not know which way a conditional jump will go. So
  8104. we do not know whether to use the live-before set for the following
  8105. instruction or the live-before set for the block associated with the
  8106. $\itm{label}$. However, there is no harm to the correctness of the
  8107. generated code if we classify more locations as live than the ones
  8108. that are truly live during one particular execution of the
  8109. instruction. Thus, we can take the union of the live-before sets from
  8110. the following instruction and from the mapping for $\itm{label}$ in
  8111. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8112. The auxiliary functions for computing the variables in an
  8113. instruction's argument and for computing the variables read-from ($R$)
  8114. or written-to ($W$) by an instruction need to be updated to handle the
  8115. new kinds of arguments and instructions in \LangXIfVar{}.
  8116. \begin{exercise}\normalfont
  8117. {\if\edition\racketEd
  8118. %
  8119. Update the \code{uncover\_live} pass to apply liveness analysis to
  8120. every basic block in the program.
  8121. %
  8122. Add the following entry to the list of \code{passes} in the
  8123. \code{run-tests.rkt} script.
  8124. \begin{lstlisting}
  8125. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8126. \end{lstlisting}
  8127. \fi}
  8128. {\if\edition\pythonEd
  8129. %
  8130. Update the \code{uncover\_live} function to perform liveness analysis,
  8131. in reverse topological order, on all of the basic blocks in the
  8132. program.
  8133. %
  8134. \fi}
  8135. % Check that the live-after sets that you generate for
  8136. % example X matches the following... -Jeremy
  8137. \end{exercise}
  8138. \subsection{Build the Interference Graph}
  8139. \label{sec:build-interference-Lif}
  8140. Many of the new instructions in \LangXIfVar{} can be handled in the
  8141. same way as the instructions in \LangXVar{}.
  8142. % Thus, if your code was
  8143. % already quite general, it will not need to be changed to handle the
  8144. % new instructions. If your code is not general enough, we recommend that
  8145. % you change your code to be more general. For example, you can factor
  8146. % out the computing of the the read and write sets for each kind of
  8147. % instruction into auxiliary functions.
  8148. %
  8149. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8150. similar to the \key{movq} instruction. See rule number 1 in
  8151. Section~\ref{sec:build-interference}.
  8152. \begin{exercise}\normalfont
  8153. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8154. {\if\edition\racketEd
  8155. Add the following entries to the list of \code{passes} in the
  8156. \code{run-tests.rkt} script.
  8157. \begin{lstlisting}
  8158. (list "build_interference" build_interference interp-pseudo-x86-1)
  8159. (list "allocate_registers" allocate_registers interp-x86-1)
  8160. \end{lstlisting}
  8161. \fi}
  8162. % Check that the interference graph that you generate for
  8163. % example X matches the following graph G... -Jeremy
  8164. \end{exercise}
  8165. \section{Patch Instructions}
  8166. The new instructions \key{cmpq} and \key{movzbq} have some special
  8167. restrictions that need to be handled in the \code{patch\_instructions}
  8168. pass.
  8169. %
  8170. The second argument of the \key{cmpq} instruction must not be an
  8171. immediate value (such as an integer). So if you are comparing two
  8172. immediates, we recommend inserting a \key{movq} instruction to put the
  8173. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8174. one memory reference.
  8175. %
  8176. The second argument of the \key{movzbq} must be a register.
  8177. \begin{exercise}\normalfont
  8178. %
  8179. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8180. %
  8181. {\if\edition\racketEd
  8182. Add the following entry to the list of \code{passes} in
  8183. \code{run-tests.rkt} and then run this script to test your compiler.
  8184. \begin{lstlisting}
  8185. (list "patch_instructions" patch_instructions interp-x86-1)
  8186. \end{lstlisting}
  8187. \fi}
  8188. \end{exercise}
  8189. {\if\edition\pythonEd
  8190. \section{Prelude and Conclusion}
  8191. \label{sec:prelude-conclusion-cond}
  8192. The generation of the \code{main} function with its prelude and
  8193. conclusion must change to accomodate how the program now consists of
  8194. one or more basic blocks. After the prelude in \code{main}, jump to
  8195. the \code{start} block. Place the conclusion in a basic block labelled
  8196. with \code{conclusion}.
  8197. \fi}
  8198. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8199. \LangIf{} translated to x86, showing the results of
  8200. \code{explicate\_control}, \code{select\_instructions}, and the final
  8201. x86 assembly.
  8202. \begin{figure}[tbp]
  8203. {\if\edition\racketEd
  8204. \begin{tabular}{lll}
  8205. \begin{minipage}{0.4\textwidth}
  8206. % cond_test_20.rkt, eq_input.py
  8207. \begin{lstlisting}
  8208. (if (eq? (read) 1) 42 0)
  8209. \end{lstlisting}
  8210. $\Downarrow$
  8211. \begin{lstlisting}
  8212. start:
  8213. tmp7951 = (read);
  8214. if (eq? tmp7951 1)
  8215. goto block7952;
  8216. else
  8217. goto block7953;
  8218. block7952:
  8219. return 42;
  8220. block7953:
  8221. return 0;
  8222. \end{lstlisting}
  8223. $\Downarrow$
  8224. \begin{lstlisting}
  8225. start:
  8226. callq read_int
  8227. movq %rax, tmp7951
  8228. cmpq $1, tmp7951
  8229. je block7952
  8230. jmp block7953
  8231. block7953:
  8232. movq $0, %rax
  8233. jmp conclusion
  8234. block7952:
  8235. movq $42, %rax
  8236. jmp conclusion
  8237. \end{lstlisting}
  8238. \end{minipage}
  8239. &
  8240. $\Rightarrow\qquad$
  8241. \begin{minipage}{0.4\textwidth}
  8242. \begin{lstlisting}
  8243. start:
  8244. callq read_int
  8245. movq %rax, %rcx
  8246. cmpq $1, %rcx
  8247. je block7952
  8248. jmp block7953
  8249. block7953:
  8250. movq $0, %rax
  8251. jmp conclusion
  8252. block7952:
  8253. movq $42, %rax
  8254. jmp conclusion
  8255. .globl main
  8256. main:
  8257. pushq %rbp
  8258. movq %rsp, %rbp
  8259. pushq %r13
  8260. pushq %r12
  8261. pushq %rbx
  8262. pushq %r14
  8263. subq $0, %rsp
  8264. jmp start
  8265. conclusion:
  8266. addq $0, %rsp
  8267. popq %r14
  8268. popq %rbx
  8269. popq %r12
  8270. popq %r13
  8271. popq %rbp
  8272. retq
  8273. \end{lstlisting}
  8274. \end{minipage}
  8275. \end{tabular}
  8276. \fi}
  8277. {\if\edition\pythonEd
  8278. \begin{tabular}{lll}
  8279. \begin{minipage}{0.4\textwidth}
  8280. % cond_test_20.rkt, eq_input.py
  8281. \begin{lstlisting}
  8282. print(42 if input_int() == 1 else 0)
  8283. \end{lstlisting}
  8284. $\Downarrow$
  8285. \begin{lstlisting}
  8286. start:
  8287. tmp_0 = input_int()
  8288. if tmp_0 == 1:
  8289. goto block_3
  8290. else:
  8291. goto block_4
  8292. block_3:
  8293. tmp_1 = 42
  8294. goto block_2
  8295. block_4:
  8296. tmp_1 = 0
  8297. goto block_2
  8298. block_2:
  8299. print(tmp_1)
  8300. return 0
  8301. \end{lstlisting}
  8302. $\Downarrow$
  8303. \begin{lstlisting}
  8304. start:
  8305. callq read_int
  8306. movq %rax, tmp_0
  8307. cmpq 1, tmp_0
  8308. je block_3
  8309. jmp block_4
  8310. block_3:
  8311. movq 42, tmp_1
  8312. jmp block_2
  8313. block_4:
  8314. movq 0, tmp_1
  8315. jmp block_2
  8316. block_2:
  8317. movq tmp_1, %rdi
  8318. callq print_int
  8319. movq 0, %rax
  8320. jmp conclusion
  8321. \end{lstlisting}
  8322. \end{minipage}
  8323. &
  8324. $\Rightarrow\qquad$
  8325. \begin{minipage}{0.4\textwidth}
  8326. \begin{lstlisting}
  8327. .globl main
  8328. main:
  8329. pushq %rbp
  8330. movq %rsp, %rbp
  8331. subq $0, %rsp
  8332. jmp start
  8333. start:
  8334. callq read_int
  8335. movq %rax, %rcx
  8336. cmpq $1, %rcx
  8337. je block_3
  8338. jmp block_4
  8339. block_3:
  8340. movq $42, %rcx
  8341. jmp block_2
  8342. block_4:
  8343. movq $0, %rcx
  8344. jmp block_2
  8345. block_2:
  8346. movq %rcx, %rdi
  8347. callq print_int
  8348. movq $0, %rax
  8349. jmp conclusion
  8350. conclusion:
  8351. addq $0, %rsp
  8352. popq %rbp
  8353. retq
  8354. \end{lstlisting}
  8355. \end{minipage}
  8356. \end{tabular}
  8357. \fi}
  8358. \caption{Example compilation of an \key{if} expression to x86, showing
  8359. the results of \code{explicate\_control},
  8360. \code{select\_instructions}, and the final x86 assembly code. }
  8361. \label{fig:if-example-x86}
  8362. \end{figure}
  8363. \begin{figure}[tbp]
  8364. {\if\edition\racketEd
  8365. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8366. \node (Lif) at (0,2) {\large \LangIf{}};
  8367. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8368. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8369. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8370. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8371. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8372. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8373. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8374. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8375. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8376. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8377. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8378. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8379. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8380. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8381. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8382. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8383. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8384. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8385. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8386. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8387. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8388. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8389. \end{tikzpicture}
  8390. \fi}
  8391. {\if\edition\pythonEd
  8392. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8393. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8394. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8395. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8396. \node (C-1) at (3,0) {\large \LangCIf{}};
  8397. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8398. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8399. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8400. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8401. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8402. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8403. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8404. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8405. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8406. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8407. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8408. \end{tikzpicture}
  8409. \fi}
  8410. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8411. \label{fig:Lif-passes}
  8412. \end{figure}
  8413. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8414. compilation of \LangIf{}.
  8415. \section{Challenge: Optimize Blocks and Remove Jumps}
  8416. \label{sec:opt-jumps}
  8417. We discuss two optional challenges that involve optimizing the
  8418. control-flow of the program.
  8419. \subsection{Optimize Blocks}
  8420. The algorithm for \code{explicate\_control} that we discussed in
  8421. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8422. blocks. It does so in two different ways.
  8423. %
  8424. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8425. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8426. a new basic block from a single \code{goto} statement, whereas we
  8427. could have simply returned the \code{goto} statement. We can solve
  8428. this problem by modifying the \code{create\_block} function to
  8429. recognize this situation.
  8430. Second, \code{explicate\_control} creates a basic block whenever a
  8431. continuation \emph{might} get used more than once (whenever a
  8432. continuation is passed into two or more recursive calls). However,
  8433. some continuation parameters may not be used at all. For example, consider the
  8434. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8435. discard the \code{els} branch. So the question is how can we decide
  8436. whether to create a basic block?
  8437. The solution to this conundrum is to use \emph{lazy
  8438. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8439. to delay creating a basic block until the point in time where we know
  8440. it will be used.
  8441. %
  8442. {\if\edition\racketEd
  8443. %
  8444. Racket provides support for
  8445. lazy evaluation with the
  8446. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8447. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8448. \index{subject}{delay} creates a
  8449. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8450. expressions is postponed. When \key{(force}
  8451. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8452. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8453. result of $e_n$ is cached in the promise and returned. If \code{force}
  8454. is applied again to the same promise, then the cached result is
  8455. returned. If \code{force} is applied to an argument that is not a
  8456. promise, \code{force} simply returns the argument.
  8457. %
  8458. \fi}
  8459. %
  8460. {\if\edition\pythonEd
  8461. %
  8462. While Python does not provide direct support for lazy evaluation, it
  8463. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8464. by wrapping it inside a function with no parameters. We can
  8465. \emph{force} its evaluation by calling the function. However, in some
  8466. cases of \code{explicate\_pred}, etc., we will return a list of
  8467. statements and in other cases we will return a function that computes
  8468. a list of statements. We use the term \emph{promise} to refer to a
  8469. value that may be delayed. To uniformly deal with
  8470. promises, we define the following \code{force} function that checks
  8471. whether its input is delayed (i.e., whether it is a function) and then
  8472. either 1) calls the function, or 2) returns the input.
  8473. \begin{lstlisting}
  8474. def force(promise):
  8475. if isinstance(promise, types.FunctionType):
  8476. return promise()
  8477. else:
  8478. return promise
  8479. \end{lstlisting}
  8480. %
  8481. \fi}
  8482. We use promises for the input and output of the functions
  8483. \code{explicate\_pred}, \code{explicate\_assign},
  8484. %
  8485. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8486. %
  8487. So instead of taking and returning lists of statments, they take and
  8488. return promises. Furthermore, when we come to a situation in which a
  8489. continuation might be used more than once, as in the case for
  8490. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8491. that creates a basic block for each continuation (if there is not
  8492. already one) and then returns a \code{goto} statement to that basic
  8493. block.
  8494. %
  8495. {\if\edition\racketEd
  8496. %
  8497. The following auxiliary function named \code{create\_block} accomplishes
  8498. this task. It begins with \code{delay} to create a promise. When
  8499. forced, this promise will force the original promise. If that returns
  8500. a \code{goto} (because the block was already added to the control-flow
  8501. graph), then we return the \code{goto}. Otherwise we add the block to
  8502. the control-flow graph with another auxiliary function named
  8503. \code{add-node}. That function returns the label for the new block,
  8504. which we use to create a \code{goto}.
  8505. \begin{lstlisting}
  8506. (define (create_block tail)
  8507. (delay
  8508. (define t (force tail))
  8509. (match t
  8510. [(Goto label) (Goto label)]
  8511. [else (Goto (add-node t))])))
  8512. \end{lstlisting}
  8513. \fi}
  8514. {\if\edition\pythonEd
  8515. %
  8516. Here is the new version of the \code{create\_block} auxiliary function
  8517. that works on promises and that checks whether the block consists of a
  8518. solitary \code{goto} statement.\\
  8519. \begin{minipage}{\textwidth}
  8520. \begin{lstlisting}
  8521. def create_block(promise, basic_blocks):
  8522. stmts = force(promise)
  8523. match stmts:
  8524. case [Goto(l)]:
  8525. return Goto(l)
  8526. case _:
  8527. label = label_name(generate_name('block'))
  8528. basic_blocks[label] = stmts
  8529. return Goto(label)
  8530. \end{lstlisting}
  8531. \end{minipage}
  8532. \fi}
  8533. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8534. \code{explicate\_control} on the example of the nested \code{if}
  8535. expressions with the two improvements discussed above. As you can
  8536. see, the number of basic blocks has been reduced from 10 blocks (see
  8537. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8538. \begin{figure}[tbp]
  8539. {\if\edition\racketEd
  8540. \begin{tabular}{lll}
  8541. \begin{minipage}{0.4\textwidth}
  8542. % cond_test_41.rkt
  8543. \begin{lstlisting}
  8544. (let ([x (read)])
  8545. (let ([y (read)])
  8546. (if (if (< x 1)
  8547. (eq? x 0)
  8548. (eq? x 2))
  8549. (+ y 2)
  8550. (+ y 10))))
  8551. \end{lstlisting}
  8552. \end{minipage}
  8553. &
  8554. $\Rightarrow$
  8555. &
  8556. \begin{minipage}{0.55\textwidth}
  8557. \begin{lstlisting}
  8558. start:
  8559. x = (read);
  8560. y = (read);
  8561. if (< x 1) goto block40;
  8562. else goto block41;
  8563. block40:
  8564. if (eq? x 0) goto block38;
  8565. else goto block39;
  8566. block41:
  8567. if (eq? x 2) goto block38;
  8568. else goto block39;
  8569. block38:
  8570. return (+ y 2);
  8571. block39:
  8572. return (+ y 10);
  8573. \end{lstlisting}
  8574. \end{minipage}
  8575. \end{tabular}
  8576. \fi}
  8577. {\if\edition\pythonEd
  8578. \begin{tabular}{lll}
  8579. \begin{minipage}{0.4\textwidth}
  8580. % cond_test_41.rkt
  8581. \begin{lstlisting}
  8582. x = input_int()
  8583. y = input_int()
  8584. print(y + 2 \
  8585. if (x == 0 \
  8586. if x < 1 \
  8587. else x == 2) \
  8588. else y + 10)
  8589. \end{lstlisting}
  8590. \end{minipage}
  8591. &
  8592. $\Rightarrow$
  8593. &
  8594. \begin{minipage}{0.55\textwidth}
  8595. \begin{lstlisting}
  8596. start:
  8597. x = input_int()
  8598. y = input_int()
  8599. if x < 1:
  8600. goto block_4
  8601. else:
  8602. goto block_5
  8603. block_4:
  8604. if x == 0:
  8605. goto block_2
  8606. else:
  8607. goto block_3
  8608. block_5:
  8609. if x == 2:
  8610. goto block_2
  8611. else:
  8612. goto block_3
  8613. block_2:
  8614. tmp_0 = y + 2
  8615. goto block_1
  8616. block_3:
  8617. tmp_0 = y + 10
  8618. goto block_1
  8619. block_1:
  8620. print(tmp_0)
  8621. return 0
  8622. \end{lstlisting}
  8623. \end{minipage}
  8624. \end{tabular}
  8625. \fi}
  8626. \caption{Translation from \LangIf{} to \LangCIf{}
  8627. via the improved \code{explicate\_control}.}
  8628. \label{fig:explicate-control-challenge}
  8629. \end{figure}
  8630. %% Recall that in the example output of \code{explicate\_control} in
  8631. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8632. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8633. %% block. The first goal of this challenge assignment is to remove those
  8634. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8635. %% \code{explicate\_control} on the left and shows the result of bypassing
  8636. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8637. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8638. %% \code{block55}. The optimized code on the right of
  8639. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8640. %% \code{then} branch jumping directly to \code{block55}. The story is
  8641. %% similar for the \code{else} branch, as well as for the two branches in
  8642. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8643. %% have been optimized in this way, there are no longer any jumps to
  8644. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8645. %% \begin{figure}[tbp]
  8646. %% \begin{tabular}{lll}
  8647. %% \begin{minipage}{0.4\textwidth}
  8648. %% \begin{lstlisting}
  8649. %% block62:
  8650. %% tmp54 = (read);
  8651. %% if (eq? tmp54 2) then
  8652. %% goto block59;
  8653. %% else
  8654. %% goto block60;
  8655. %% block61:
  8656. %% tmp53 = (read);
  8657. %% if (eq? tmp53 0) then
  8658. %% goto block57;
  8659. %% else
  8660. %% goto block58;
  8661. %% block60:
  8662. %% goto block56;
  8663. %% block59:
  8664. %% goto block55;
  8665. %% block58:
  8666. %% goto block56;
  8667. %% block57:
  8668. %% goto block55;
  8669. %% block56:
  8670. %% return (+ 700 77);
  8671. %% block55:
  8672. %% return (+ 10 32);
  8673. %% start:
  8674. %% tmp52 = (read);
  8675. %% if (eq? tmp52 1) then
  8676. %% goto block61;
  8677. %% else
  8678. %% goto block62;
  8679. %% \end{lstlisting}
  8680. %% \end{minipage}
  8681. %% &
  8682. %% $\Rightarrow$
  8683. %% &
  8684. %% \begin{minipage}{0.55\textwidth}
  8685. %% \begin{lstlisting}
  8686. %% block62:
  8687. %% tmp54 = (read);
  8688. %% if (eq? tmp54 2) then
  8689. %% goto block55;
  8690. %% else
  8691. %% goto block56;
  8692. %% block61:
  8693. %% tmp53 = (read);
  8694. %% if (eq? tmp53 0) then
  8695. %% goto block55;
  8696. %% else
  8697. %% goto block56;
  8698. %% block56:
  8699. %% return (+ 700 77);
  8700. %% block55:
  8701. %% return (+ 10 32);
  8702. %% start:
  8703. %% tmp52 = (read);
  8704. %% if (eq? tmp52 1) then
  8705. %% goto block61;
  8706. %% else
  8707. %% goto block62;
  8708. %% \end{lstlisting}
  8709. %% \end{minipage}
  8710. %% \end{tabular}
  8711. %% \caption{Optimize jumps by removing trivial blocks.}
  8712. %% \label{fig:optimize-jumps}
  8713. %% \end{figure}
  8714. %% The name of this pass is \code{optimize-jumps}. We recommend
  8715. %% implementing this pass in two phases. The first phrase builds a hash
  8716. %% table that maps labels to possibly improved labels. The second phase
  8717. %% changes the target of each \code{goto} to use the improved label. If
  8718. %% the label is for a trivial block, then the hash table should map the
  8719. %% label to the first non-trivial block that can be reached from this
  8720. %% label by jumping through trivial blocks. If the label is for a
  8721. %% non-trivial block, then the hash table should map the label to itself;
  8722. %% we do not want to change jumps to non-trivial blocks.
  8723. %% The first phase can be accomplished by constructing an empty hash
  8724. %% table, call it \code{short-cut}, and then iterating over the control
  8725. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8726. %% then update the hash table, mapping the block's source to the target
  8727. %% of the \code{goto}. Also, the hash table may already have mapped some
  8728. %% labels to the block's source, to you must iterate through the hash
  8729. %% table and update all of those so that they instead map to the target
  8730. %% of the \code{goto}.
  8731. %% For the second phase, we recommend iterating through the $\Tail$ of
  8732. %% each block in the program, updating the target of every \code{goto}
  8733. %% according to the mapping in \code{short-cut}.
  8734. \begin{exercise}\normalfont
  8735. Implement the improvements to the \code{explicate\_control} pass.
  8736. Check that it removes trivial blocks in a few example programs. Then
  8737. check that your compiler still passes all of your tests.
  8738. \end{exercise}
  8739. \subsection{Remove Jumps}
  8740. There is an opportunity for removing jumps that is apparent in the
  8741. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8742. ends with a jump to \code{block7953} and there are no other jumps to
  8743. \code{block7953} in the rest of the program. In this situation we can
  8744. avoid the runtime overhead of this jump by merging \code{block7953}
  8745. into the preceding block, in this case the \code{start} block.
  8746. Figure~\ref{fig:remove-jumps} shows the output of
  8747. \code{select\_instructions} on the left and the result of this
  8748. optimization on the right.
  8749. \begin{figure}[tbp]
  8750. {\if\edition\racketEd
  8751. \begin{tabular}{lll}
  8752. \begin{minipage}{0.5\textwidth}
  8753. % cond_test_20.rkt
  8754. \begin{lstlisting}
  8755. start:
  8756. callq read_int
  8757. movq %rax, tmp7951
  8758. cmpq $1, tmp7951
  8759. je block7952
  8760. jmp block7953
  8761. block7953:
  8762. movq $0, %rax
  8763. jmp conclusion
  8764. block7952:
  8765. movq $42, %rax
  8766. jmp conclusion
  8767. \end{lstlisting}
  8768. \end{minipage}
  8769. &
  8770. $\Rightarrow\qquad$
  8771. \begin{minipage}{0.4\textwidth}
  8772. \begin{lstlisting}
  8773. start:
  8774. callq read_int
  8775. movq %rax, tmp7951
  8776. cmpq $1, tmp7951
  8777. je block7952
  8778. movq $0, %rax
  8779. jmp conclusion
  8780. block7952:
  8781. movq $42, %rax
  8782. jmp conclusion
  8783. \end{lstlisting}
  8784. \end{minipage}
  8785. \end{tabular}
  8786. \fi}
  8787. {\if\edition\pythonEd
  8788. \begin{tabular}{lll}
  8789. \begin{minipage}{0.5\textwidth}
  8790. % cond_test_20.rkt
  8791. \begin{lstlisting}
  8792. start:
  8793. callq read_int
  8794. movq %rax, tmp_0
  8795. cmpq 1, tmp_0
  8796. je block_3
  8797. jmp block_4
  8798. block_3:
  8799. movq 42, tmp_1
  8800. jmp block_2
  8801. block_4:
  8802. movq 0, tmp_1
  8803. jmp block_2
  8804. block_2:
  8805. movq tmp_1, %rdi
  8806. callq print_int
  8807. movq 0, %rax
  8808. jmp conclusion
  8809. \end{lstlisting}
  8810. \end{minipage}
  8811. &
  8812. $\Rightarrow\qquad$
  8813. \begin{minipage}{0.4\textwidth}
  8814. \begin{lstlisting}
  8815. start:
  8816. callq read_int
  8817. movq %rax, tmp_0
  8818. cmpq 1, tmp_0
  8819. je block_3
  8820. movq 0, tmp_1
  8821. jmp block_2
  8822. block_3:
  8823. movq 42, tmp_1
  8824. jmp block_2
  8825. block_2:
  8826. movq tmp_1, %rdi
  8827. callq print_int
  8828. movq 0, %rax
  8829. jmp conclusion
  8830. \end{lstlisting}
  8831. \end{minipage}
  8832. \end{tabular}
  8833. \fi}
  8834. \caption{Merging basic blocks by removing unnecessary jumps.}
  8835. \label{fig:remove-jumps}
  8836. \end{figure}
  8837. \begin{exercise}\normalfont
  8838. %
  8839. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8840. into their preceding basic block, when there is only one preceding
  8841. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8842. %
  8843. {\if\edition\racketEd
  8844. In the \code{run-tests.rkt} script, add the following entry to the
  8845. list of \code{passes} between \code{allocate\_registers}
  8846. and \code{patch\_instructions}.
  8847. \begin{lstlisting}
  8848. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8849. \end{lstlisting}
  8850. \fi}
  8851. %
  8852. Run the script to test your compiler.
  8853. %
  8854. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8855. blocks on several test programs.
  8856. \end{exercise}
  8857. \section{Further Reading}
  8858. \label{sec:cond-further-reading}
  8859. The algorithm for the \code{explicate\_control} pass is based on the
  8860. \code{explose-basic-blocks} pass in the course notes of
  8861. \citet{Dybvig:2010aa}.
  8862. %
  8863. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8864. \citet{Appel:2003fk}, and is related to translations into continuation
  8865. passing
  8866. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8867. %
  8868. The treatment of conditionals in the \code{explicate\_control} pass is
  8869. similar to short-cut boolean
  8870. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8871. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8872. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8873. \chapter{Loops and Dataflow Analysis}
  8874. \label{ch:Lwhile}
  8875. % TODO: define R'_8
  8876. % TODO: multi-graph
  8877. {\if\edition\racketEd
  8878. %
  8879. In this chapter we study two features that are the hallmarks of
  8880. imperative programming languages: loops and assignments to local
  8881. variables. The following example demonstrates these new features by
  8882. computing the sum of the first five positive integers.
  8883. % similar to loop_test_1.rkt
  8884. \begin{lstlisting}
  8885. (let ([sum 0])
  8886. (let ([i 5])
  8887. (begin
  8888. (while (> i 0)
  8889. (begin
  8890. (set! sum (+ sum i))
  8891. (set! i (- i 1))))
  8892. sum)))
  8893. \end{lstlisting}
  8894. The \code{while} loop consists of a condition and a
  8895. body\footnote{The \code{while} loop in particular is not a built-in
  8896. feature of the Racket language, but Racket includes many looping
  8897. constructs and it is straightforward to define \code{while} as a
  8898. macro.}. The body is evaluated repeatedly so long as the condition
  8899. remains true.
  8900. %
  8901. The \code{set!} consists of a variable and a right-hand-side
  8902. expression. The \code{set!} updates value of the variable to the
  8903. value of the right-hand-side.
  8904. %
  8905. The primary purpose of both the \code{while} loop and \code{set!} is
  8906. to cause side effects, so they do not have a meaningful result
  8907. value. Instead their result is the \code{\#<void>} value. The
  8908. expression \code{(void)} is an explicit way to create the
  8909. \code{\#<void>} value and it has type \code{Void}. The
  8910. \code{\#<void>} value can be passed around just like other values
  8911. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8912. compared for equality with another \code{\#<void>} value. However,
  8913. there are no other operations specific to the the \code{\#<void>}
  8914. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8915. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8916. \code{\#f} otherwise.
  8917. %
  8918. \footnote{Racket's \code{Void} type corresponds to what is called the
  8919. \code{Unit} type in the programming languages literature. Racket's
  8920. \code{Void} type is inhabited by a single value \code{\#<void>}
  8921. which corresponds to \code{unit} or \code{()} in the
  8922. literature~\citep{Pierce:2002hj}.}.
  8923. %
  8924. With the addition of side-effecting features such as \code{while} loop
  8925. and \code{set!}, it is helpful to also include in a language feature
  8926. for sequencing side effects: the \code{begin} expression. It consists
  8927. of one or more subexpressions that are evaluated left-to-right.
  8928. %
  8929. \fi}
  8930. {\if\edition\pythonEd
  8931. %
  8932. In this chapter we study loops, one of the hallmarks of imperative
  8933. programming languages. The following example demonstrates the
  8934. \code{while} loop by computing the sum of the first five positive
  8935. integers.
  8936. \begin{lstlisting}
  8937. sum = 0
  8938. i = 5
  8939. while i > 0:
  8940. sum = sum + i
  8941. i = i - 1
  8942. print(sum)
  8943. \end{lstlisting}
  8944. The \code{while} loop consists of a condition expression and a body (a
  8945. sequence of statements). The body is evaluated repeatedly so long as
  8946. the condition remains true.
  8947. %
  8948. \fi}
  8949. \section{The \LangLoop{} Language}
  8950. \newcommand{\LwhileGrammarRacket}{
  8951. \begin{array}{lcl}
  8952. \Type &::=& \key{Void}\\
  8953. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8954. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8955. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8956. \end{array}
  8957. }
  8958. \newcommand{\LwhileASTRacket}{
  8959. \begin{array}{lcl}
  8960. \Type &::=& \key{Void}\\
  8961. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  8962. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  8963. \end{array}
  8964. }
  8965. \newcommand{\LwhileGrammarPython}{
  8966. \begin{array}{rcl}
  8967. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  8968. \end{array}
  8969. }
  8970. \newcommand{\LwhileASTPython}{
  8971. \begin{array}{lcl}
  8972. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  8973. \end{array}
  8974. }
  8975. \begin{figure}[tp]
  8976. \centering
  8977. \fbox{
  8978. \begin{minipage}{0.96\textwidth}
  8979. \small
  8980. {\if\edition\racketEd
  8981. \[
  8982. \begin{array}{l}
  8983. \gray{\LintGrammarRacket{}} \\ \hline
  8984. \gray{\LvarGrammarRacket{}} \\ \hline
  8985. \gray{\LifGrammarRacket{}} \\ \hline
  8986. \LwhileGrammarRacket \\
  8987. \begin{array}{lcl}
  8988. \LangLoopM{} &::=& \Exp
  8989. \end{array}
  8990. \end{array}
  8991. \]
  8992. \fi}
  8993. {\if\edition\pythonEd
  8994. \[
  8995. \begin{array}{l}
  8996. \gray{\LintGrammarPython} \\ \hline
  8997. \gray{\LvarGrammarPython} \\ \hline
  8998. \gray{\LifGrammarPython} \\ \hline
  8999. \LwhileGrammarPython \\
  9000. \begin{array}{rcl}
  9001. \LangLoopM{} &::=& \Stmt^{*}
  9002. \end{array}
  9003. \end{array}
  9004. \]
  9005. \fi}
  9006. \end{minipage}
  9007. }
  9008. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  9009. \label{fig:Lwhile-concrete-syntax}
  9010. \end{figure}
  9011. \begin{figure}[tp]
  9012. \centering
  9013. \fbox{
  9014. \begin{minipage}{0.96\textwidth}
  9015. \small
  9016. {\if\edition\racketEd
  9017. \[
  9018. \begin{array}{l}
  9019. \gray{\LintOpAST} \\ \hline
  9020. \gray{\LvarASTRacket{}} \\ \hline
  9021. \gray{\LifASTRacket{}} \\ \hline
  9022. \LwhileASTRacket{} \\
  9023. \begin{array}{lcl}
  9024. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9025. \end{array}
  9026. \end{array}
  9027. \]
  9028. \fi}
  9029. {\if\edition\pythonEd
  9030. \[
  9031. \begin{array}{l}
  9032. \gray{\LintASTPython} \\ \hline
  9033. \gray{\LvarASTPython} \\ \hline
  9034. \gray{\LifASTPython} \\ \hline
  9035. \LwhileASTPython \\
  9036. \begin{array}{lcl}
  9037. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9038. \end{array}
  9039. \end{array}
  9040. \]
  9041. \fi}
  9042. \end{minipage}
  9043. }
  9044. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9045. \label{fig:Lwhile-syntax}
  9046. \end{figure}
  9047. The concrete syntax of \LangLoop{} is defined in
  9048. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9049. in Figure~\ref{fig:Lwhile-syntax}.
  9050. %
  9051. The definitional interpreter for \LangLoop{} is shown in
  9052. Figure~\ref{fig:interp-Rwhile}.
  9053. %
  9054. {\if\edition\racketEd
  9055. %
  9056. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9057. and \code{Void} and we make changes to the cases for \code{Var} and
  9058. \code{Let} regarding variables. To support assignment to variables and
  9059. to make their lifetimes indefinite (see the second example in
  9060. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9061. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9062. value.
  9063. %
  9064. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9065. variable in the environment to obtain a boxed value and then we change
  9066. it using \code{set-box!} to the result of evaluating the right-hand
  9067. side. The result value of a \code{SetBang} is \code{void}.
  9068. %
  9069. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9070. if the result is true, 2) evaluate the body.
  9071. The result value of a \code{while} loop is also \code{void}.
  9072. %
  9073. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9074. subexpressions \itm{es} for their effects and then evaluates
  9075. and returns the result from \itm{body}.
  9076. %
  9077. The $\VOID{}$ expression produces the \code{void} value.
  9078. %
  9079. \fi}
  9080. {\if\edition\pythonEd
  9081. %
  9082. We add a new case for \code{While} in the \code{interp\_stmts}
  9083. function, where we repeatedly interpret the \code{body} so long as the
  9084. \code{test} expression remains true.
  9085. %
  9086. \fi}
  9087. \begin{figure}[tbp]
  9088. {\if\edition\racketEd
  9089. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9090. (define interp-Rwhile_class
  9091. (class interp-Rany_class
  9092. (super-new)
  9093. (define/override ((interp-exp env) e)
  9094. (define recur (interp-exp env))
  9095. (match e
  9096. [(SetBang x rhs)
  9097. (set-box! (lookup x env) (recur rhs))]
  9098. [(WhileLoop cnd body)
  9099. (define (loop)
  9100. (cond [(recur cnd) (recur body) (loop)]
  9101. [else (void)]))
  9102. (loop)]
  9103. [(Begin es body)
  9104. (for ([e es]) (recur e))
  9105. (recur body)]
  9106. [(Void) (void)]
  9107. [else ((super interp-exp env) e)]))
  9108. ))
  9109. (define (interp-Rwhile p)
  9110. (send (new interp-Rwhile_class) interp-program p))
  9111. \end{lstlisting}
  9112. \fi}
  9113. {\if\edition\pythonEd
  9114. \begin{lstlisting}
  9115. class InterpLwhile(InterpLif):
  9116. def interp_stmts(self, ss, env):
  9117. if len(ss) == 0:
  9118. return
  9119. match ss[0]:
  9120. case While(test, body, []):
  9121. while self.interp_exp(test, env):
  9122. self.interp_stmts(body, env)
  9123. return self.interp_stmts(ss[1:], env)
  9124. case _:
  9125. return super().interp_stmts(ss, env)
  9126. \end{lstlisting}
  9127. \fi}
  9128. \caption{Interpreter for \LangLoop{}.}
  9129. \label{fig:interp-Rwhile}
  9130. \end{figure}
  9131. The type checker for \LangLoop{} is defined in
  9132. Figure~\ref{fig:type-check-Rwhile}.
  9133. %
  9134. {\if\edition\racketEd
  9135. %
  9136. For \LangLoop{} we add a type named \code{Void} and the only value of
  9137. this type is the \code{void} value.
  9138. %
  9139. The type checking of the \code{SetBang} expression requires the type of
  9140. the variable and the right-hand-side to agree. The result type is
  9141. \code{Void}. For \code{while}, the condition must be a
  9142. \code{Boolean}. The result type is also \code{Void}. For
  9143. \code{Begin}, the result type is the type of its last subexpression.
  9144. %
  9145. \fi}
  9146. %
  9147. {\if\edition\pythonEd
  9148. %
  9149. A \code{while} loop is well typed if the type of the \code{test}
  9150. expression is \code{bool} and the statements in the \code{body} are
  9151. well typed.
  9152. %
  9153. \fi}
  9154. \begin{figure}[tbp]
  9155. {\if\edition\racketEd
  9156. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9157. (define type-check-Rwhile_class
  9158. (class type-check-Rany_class
  9159. (super-new)
  9160. (inherit check-type-equal?)
  9161. (define/override (type-check-exp env)
  9162. (lambda (e)
  9163. (define recur (type-check-exp env))
  9164. (match e
  9165. [(SetBang x rhs)
  9166. (define-values (rhs^ rhsT) (recur rhs))
  9167. (define varT (dict-ref env x))
  9168. (check-type-equal? rhsT varT e)
  9169. (values (SetBang x rhs^) 'Void)]
  9170. [(WhileLoop cnd body)
  9171. (define-values (cnd^ Tc) (recur cnd))
  9172. (check-type-equal? Tc 'Boolean e)
  9173. (define-values (body^ Tbody) ((type-check-exp env) body))
  9174. (values (WhileLoop cnd^ body^) 'Void)]
  9175. [(Begin es body)
  9176. (define-values (es^ ts)
  9177. (for/lists (l1 l2) ([e es]) (recur e)))
  9178. (define-values (body^ Tbody) (recur body))
  9179. (values (Begin es^ body^) Tbody)]
  9180. [else ((super type-check-exp env) e)])))
  9181. ))
  9182. (define (type-check-Rwhile p)
  9183. (send (new type-check-Rwhile_class) type-check-program p))
  9184. \end{lstlisting}
  9185. \fi}
  9186. {\if\edition\pythonEd
  9187. \begin{lstlisting}
  9188. class TypeCheckLwhile(TypeCheckLif):
  9189. def type_check_stmts(self, ss, env):
  9190. if len(ss) == 0:
  9191. return
  9192. match ss[0]:
  9193. case While(test, body, []):
  9194. test_t = self.type_check_exp(test, env)
  9195. check_type_equal(bool, test_t, test)
  9196. body_t = self.type_check_stmts(body, env)
  9197. return self.type_check_stmts(ss[1:], env)
  9198. case _:
  9199. return super().type_check_stmts(ss, env)
  9200. \end{lstlisting}
  9201. \fi}
  9202. \caption{Type checker for the \LangLoop{} language.}
  9203. \label{fig:type-check-Rwhile}
  9204. \end{figure}
  9205. {\if\edition\racketEd
  9206. %
  9207. At first glance, the translation of these language features to x86
  9208. seems straightforward because the \LangCIf{} intermediate language
  9209. already supports all of the ingredients that we need: assignment,
  9210. \code{goto}, conditional branching, and sequencing. However, there are
  9211. complications that arise which we discuss in the next section. After
  9212. that we introduce the changes necessary to the existing passes.
  9213. %
  9214. \fi}
  9215. {\if\edition\pythonEd
  9216. %
  9217. At first glance, the translation of \code{while} loops to x86 seems
  9218. straightforward because the \LangCIf{} intermediate language already
  9219. supports \code{goto} and conditional branching. However, there are
  9220. complications that arise which we discuss in the next section. After
  9221. that we introduce the changes necessary to the existing passes.
  9222. %
  9223. \fi}
  9224. \section{Cyclic Control Flow and Dataflow Analysis}
  9225. \label{sec:dataflow-analysis}
  9226. Up until this point the control-flow graphs of the programs generated
  9227. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9228. each \code{while} loop introduces a cycle in the control-flow graph.
  9229. But does that matter?
  9230. %
  9231. Indeed it does. Recall that for register allocation, the compiler
  9232. performs liveness analysis to determine which variables can share the
  9233. same register. To accomplish this we analyzed the control-flow graph
  9234. in reverse topological order
  9235. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9236. only well-defined for acyclic graphs.
  9237. Let us return to the example of computing the sum of the first five
  9238. positive integers. Here is the program after instruction selection but
  9239. before register allocation.
  9240. \begin{center}
  9241. {\if\edition\racketEd
  9242. \begin{minipage}{0.45\textwidth}
  9243. \begin{lstlisting}
  9244. (define (main) : Integer
  9245. mainstart:
  9246. movq $0, sum
  9247. movq $5, i
  9248. jmp block5
  9249. block5:
  9250. movq i, tmp3
  9251. cmpq tmp3, $0
  9252. jl block7
  9253. jmp block8
  9254. \end{lstlisting}
  9255. \end{minipage}
  9256. \begin{minipage}{0.45\textwidth}
  9257. \begin{lstlisting}
  9258. block7:
  9259. addq i, sum
  9260. movq $1, tmp4
  9261. negq tmp4
  9262. addq tmp4, i
  9263. jmp block5
  9264. block8:
  9265. movq $27, %rax
  9266. addq sum, %rax
  9267. jmp mainconclusion
  9268. )
  9269. \end{lstlisting}
  9270. \end{minipage}
  9271. \fi}
  9272. {\if\edition\pythonEd
  9273. \begin{minipage}{0.45\textwidth}
  9274. \begin{lstlisting}
  9275. mainstart:
  9276. movq $0, sum
  9277. movq $5, i
  9278. jmp block5
  9279. block5:
  9280. cmpq $0, i
  9281. jg block7
  9282. jmp block8
  9283. \end{lstlisting}
  9284. \end{minipage}
  9285. \begin{minipage}{0.45\textwidth}
  9286. \begin{lstlisting}
  9287. block7:
  9288. addq i, sum
  9289. subq $1, i
  9290. jmp block5
  9291. block8:
  9292. movq sum, %rdi
  9293. callq print_int
  9294. movq $0, %rax
  9295. jmp mainconclusion
  9296. \end{lstlisting}
  9297. \end{minipage}
  9298. \fi}
  9299. \end{center}
  9300. Recall that liveness analysis works backwards, starting at the end
  9301. of each function. For this example we could start with \code{block8}
  9302. because we know what is live at the beginning of the conclusion,
  9303. just \code{rax} and \code{rsp}. So the live-before set
  9304. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9305. %
  9306. Next we might try to analyze \code{block5} or \code{block7}, but
  9307. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9308. we are stuck.
  9309. The way out of this impasse is to realize that we can compute an
  9310. under-approximation of the live-before set by starting with empty
  9311. live-after sets. By \emph{under-approximation}, we mean that the set
  9312. only contains variables that are live for some execution of the
  9313. program, but the set may be missing some variables. Next, the
  9314. under-approximations for each block can be improved by 1) updating the
  9315. live-after set for each block using the approximate live-before sets
  9316. from the other blocks and 2) perform liveness analysis again on each
  9317. block. In fact, by iterating this process, the under-approximations
  9318. eventually become the correct solutions!
  9319. %
  9320. This approach of iteratively analyzing a control-flow graph is
  9321. applicable to many static analysis problems and goes by the name
  9322. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9323. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9324. Washington.
  9325. Let us apply this approach to the above example. We use the empty set
  9326. for the initial live-before set for each block. Let $m_0$ be the
  9327. following mapping from label names to sets of locations (variables and
  9328. registers).
  9329. \begin{center}
  9330. \begin{lstlisting}
  9331. mainstart: {}, block5: {}, block7: {}, block8: {}
  9332. \end{lstlisting}
  9333. \end{center}
  9334. Using the above live-before approximations, we determine the
  9335. live-after for each block and then apply liveness analysis to each
  9336. block. This produces our next approximation $m_1$ of the live-before
  9337. sets.
  9338. \begin{center}
  9339. \begin{lstlisting}
  9340. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9341. \end{lstlisting}
  9342. \end{center}
  9343. For the second round, the live-after for \code{mainstart} is the
  9344. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9345. liveness analysis for \code{mainstart} computes the empty set. The
  9346. live-after for \code{block5} is the union of the live-before sets for
  9347. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9348. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9349. sum\}}. The live-after for \code{block7} is the live-before for
  9350. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9351. So the liveness analysis for \code{block7} remains \code{\{i,
  9352. sum\}}. Together these yield the following approximation $m_2$ of
  9353. the live-before sets.
  9354. \begin{center}
  9355. \begin{lstlisting}
  9356. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9357. \end{lstlisting}
  9358. \end{center}
  9359. In the preceding iteration, only \code{block5} changed, so we can
  9360. limit our attention to \code{mainstart} and \code{block7}, the two
  9361. blocks that jump to \code{block5}. As a result, the live-before sets
  9362. for \code{mainstart} and \code{block7} are updated to include
  9363. \code{rsp}, yielding the following approximation $m_3$.
  9364. \begin{center}
  9365. \begin{lstlisting}
  9366. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9367. \end{lstlisting}
  9368. \end{center}
  9369. Because \code{block7} changed, we analyze \code{block5} once more, but
  9370. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9371. our approximations have converged, so $m_3$ is the solution.
  9372. This iteration process is guaranteed to converge to a solution by the
  9373. Kleene Fixed-Point Theorem, a general theorem about functions on
  9374. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9375. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9376. elements, a least element $\bot$ (pronounced bottom), and a join
  9377. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9378. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9379. working with join semi-lattices.} When two elements are ordered $m_i
  9380. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9381. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9382. approximation than $m_i$. The bottom element $\bot$ represents the
  9383. complete lack of information, i.e., the worst approximation. The join
  9384. operator takes two lattice elements and combines their information,
  9385. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9386. bound}
  9387. A dataflow analysis typically involves two lattices: one lattice to
  9388. represent abstract states and another lattice that aggregates the
  9389. abstract states of all the blocks in the control-flow graph. For
  9390. liveness analysis, an abstract state is a set of locations. We form
  9391. the lattice $L$ by taking its elements to be sets of locations, the
  9392. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9393. set, and the join operator to be set union.
  9394. %
  9395. We form a second lattice $M$ by taking its elements to be mappings
  9396. from the block labels to sets of locations (elements of $L$). We
  9397. order the mappings point-wise, using the ordering of $L$. So given any
  9398. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9399. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9400. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9401. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9402. We can think of one iteration of liveness analysis applied to the
  9403. whole program as being a function $f$ on the lattice $M$. It takes a
  9404. mapping as input and computes a new mapping.
  9405. \[
  9406. f(m_i) = m_{i+1}
  9407. \]
  9408. Next let us think for a moment about what a final solution $m_s$
  9409. should look like. If we perform liveness analysis using the solution
  9410. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9411. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9412. \[
  9413. f(m_s) = m_s
  9414. \]
  9415. Furthermore, the solution should only include locations that are
  9416. forced to be there by performing liveness analysis on the program, so
  9417. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9418. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9419. monotone (better inputs produce better outputs), then the least fixed
  9420. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9421. chain} obtained by starting at $\bot$ and iterating $f$ as
  9422. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9423. \[
  9424. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9425. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9426. \]
  9427. When a lattice contains only finitely-long ascending chains, then
  9428. every Kleene chain tops out at some fixed point after some number of
  9429. iterations of $f$.
  9430. \[
  9431. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9432. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9433. \]
  9434. The liveness analysis is indeed a monotone function and the lattice
  9435. $M$ only has finitely-long ascending chains because there are only a
  9436. finite number of variables and blocks in the program. Thus we are
  9437. guaranteed that iteratively applying liveness analysis to all blocks
  9438. in the program will eventually produce the least fixed point solution.
  9439. Next let us consider dataflow analysis in general and discuss the
  9440. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9441. %
  9442. The algorithm has four parameters: the control-flow graph \code{G}, a
  9443. function \code{transfer} that applies the analysis to one block, the
  9444. \code{bottom} and \code{join} operator for the lattice of abstract
  9445. states. The \code{analyze\_dataflow} function is formulated as a
  9446. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9447. function come from the predecessor nodes in the control-flow
  9448. graph. However, liveness analysis is a \emph{backward} dataflow
  9449. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9450. function with the transpose of the control-flow graph.
  9451. The algorithm begins by creating the bottom mapping, represented by a
  9452. hash table. It then pushes all of the nodes in the control-flow graph
  9453. onto the work list (a queue). The algorithm repeats the \code{while}
  9454. loop as long as there are items in the work list. In each iteration, a
  9455. node is popped from the work list and processed. The \code{input} for
  9456. the node is computed by taking the join of the abstract states of all
  9457. the predecessor nodes. The \code{transfer} function is then applied to
  9458. obtain the \code{output} abstract state. If the output differs from
  9459. the previous state for this block, the mapping for this block is
  9460. updated and its successor nodes are pushed onto the work list.
  9461. \begin{figure}[tb]
  9462. {\if\edition\racketEd
  9463. \begin{lstlisting}
  9464. (define (analyze_dataflow G transfer bottom join)
  9465. (define mapping (make-hash))
  9466. (for ([v (in-vertices G)])
  9467. (dict-set! mapping v bottom))
  9468. (define worklist (make-queue))
  9469. (for ([v (in-vertices G)])
  9470. (enqueue! worklist v))
  9471. (define trans-G (transpose G))
  9472. (while (not (queue-empty? worklist))
  9473. (define node (dequeue! worklist))
  9474. (define input (for/fold ([state bottom])
  9475. ([pred (in-neighbors trans-G node)])
  9476. (join state (dict-ref mapping pred))))
  9477. (define output (transfer node input))
  9478. (cond [(not (equal? output (dict-ref mapping node)))
  9479. (dict-set! mapping node output)
  9480. (for ([v (in-neighbors G node)])
  9481. (enqueue! worklist v))]))
  9482. mapping)
  9483. \end{lstlisting}
  9484. \fi}
  9485. {\if\edition\pythonEd
  9486. \begin{lstlisting}
  9487. def analyze_dataflow(G, transfer, bottom, join):
  9488. trans_G = transpose(G)
  9489. mapping = dict((v, bottom) for v in G.vertices())
  9490. worklist = deque(G.vertices)
  9491. while worklist:
  9492. node = worklist.pop()
  9493. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9494. output = transfer(node, input)
  9495. if output != mapping[node]:
  9496. mapping[node] = output
  9497. worklist.extend(G.adjacent(node))
  9498. \end{lstlisting}
  9499. \fi}
  9500. \caption{Generic work list algorithm for dataflow analysis}
  9501. \label{fig:generic-dataflow}
  9502. \end{figure}
  9503. {\if\edition\racketEd
  9504. \section{Mutable Variables \& Remove Complex Operands}
  9505. There is a subtle interaction between the addition of \code{set!}, the
  9506. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9507. evaluation of Racket. Consider the following example.
  9508. \begin{lstlisting}
  9509. (let ([x 2])
  9510. (+ x (begin (set! x 40) x)))
  9511. \end{lstlisting}
  9512. The result of this program is \code{42} because the first read from
  9513. \code{x} produces \code{2} and the second produces \code{40}. However,
  9514. if we naively apply the \code{remove\_complex\_operands} pass to this
  9515. example we obtain the following program whose result is \code{80}!
  9516. \begin{lstlisting}
  9517. (let ([x 2])
  9518. (let ([tmp (begin (set! x 40) x)])
  9519. (+ x tmp)))
  9520. \end{lstlisting}
  9521. The problem is that, with mutable variables, the ordering between
  9522. reads and writes is important, and the
  9523. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9524. before the first read of \code{x}.
  9525. We recommend solving this problem by giving special treatment to reads
  9526. from mutable variables, that is, variables that occur on the left-hand
  9527. side of a \code{set!}. We mark each read from a mutable variable with
  9528. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9529. that the read operation is effectful in that it can produce different
  9530. results at different points in time. Let's apply this idea to the
  9531. following variation that also involves a variable that is not mutated.
  9532. % loop_test_24.rkt
  9533. \begin{lstlisting}
  9534. (let ([x 2])
  9535. (let ([y 0])
  9536. (+ y (+ x (begin (set! x 40) x)))))
  9537. \end{lstlisting}
  9538. We analyze the above program to discover that variable \code{x} is
  9539. mutable but \code{y} is not. We then transform the program as follows,
  9540. replacing each occurence of \code{x} with \code{(get! x)}.
  9541. \begin{lstlisting}
  9542. (let ([x 2])
  9543. (let ([y 0])
  9544. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9545. \end{lstlisting}
  9546. Now that we have a clear distinction between reads from mutable and
  9547. immutable variables, we can apply the \code{remove\_complex\_operands}
  9548. pass, where reads from immutable variables are still classified as
  9549. atomic expressions but reads from mutable variables are classified as
  9550. complex. Thus, \code{remove\_complex\_operands} yields the following
  9551. program.
  9552. \begin{lstlisting}
  9553. (let ([x 2])
  9554. (let ([y 0])
  9555. (+ y (let ([t1 (get! x)])
  9556. (let ([t2 (begin (set! x 40) (get! x))])
  9557. (+ t1 t2))))))
  9558. \end{lstlisting}
  9559. The temporary variable \code{t1} gets the value of \code{x} before the
  9560. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9561. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9562. do not generate a temporary variable for the occurence of \code{y}
  9563. because it's an immutable variable. We want to avoid such unnecessary
  9564. extra temporaries because they would needless increase the number of
  9565. variables, making it more likely for some of them to be spilled. The
  9566. result of this program is \code{42}, the same as the result prior to
  9567. \code{remove\_complex\_operands}.
  9568. The approach that we've sketched above requires only a small
  9569. modification to \code{remove\_complex\_operands} to handle
  9570. \code{get!}. However, it requires a new pass, called
  9571. \code{uncover-get!}, that we discuss in
  9572. Section~\ref{sec:uncover-get-bang}.
  9573. As an aside, this problematic interaction between \code{set!} and the
  9574. pass \code{remove\_complex\_operands} is particular to Racket and not
  9575. its predecessor, the Scheme language. The key difference is that
  9576. Scheme does not specify an order of evaluation for the arguments of an
  9577. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9578. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9579. would be correct results for the example program. Interestingly,
  9580. Racket is implemented on top of the Chez Scheme
  9581. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9582. presented in this section (using extra \code{let} bindings to control
  9583. the order of evaluation) is used in the translation from Racket to
  9584. Scheme~\citep{Flatt:2019tb}.
  9585. \fi} % racket
  9586. Having discussed the complications that arise from adding support for
  9587. assignment and loops, we turn to discussing the individual compilation
  9588. passes.
  9589. {\if\edition\racketEd
  9590. \section{Uncover \texttt{get!}}
  9591. \label{sec:uncover-get-bang}
  9592. The goal of this pass it to mark uses of mutable variables so that
  9593. \code{remove\_complex\_operands} can treat them as complex expressions
  9594. and thereby preserve their ordering relative to the side-effects in
  9595. other operands. So the first step is to collect all the mutable
  9596. variables. We recommend creating an auxilliary function for this,
  9597. named \code{collect-set!}, that recursively traverses expressions,
  9598. returning a set of all variables that occur on the left-hand side of a
  9599. \code{set!}. Here's an exerpt of its implementation.
  9600. \begin{center}
  9601. \begin{minipage}{\textwidth}
  9602. \begin{lstlisting}
  9603. (define (collect-set! e)
  9604. (match e
  9605. [(Var x) (set)]
  9606. [(Int n) (set)]
  9607. [(Let x rhs body)
  9608. (set-union (collect-set! rhs) (collect-set! body))]
  9609. [(SetBang var rhs)
  9610. (set-union (set var) (collect-set! rhs))]
  9611. ...))
  9612. \end{lstlisting}
  9613. \end{minipage}
  9614. \end{center}
  9615. By placing this pass after \code{uniquify}, we need not worry about
  9616. variable shadowing and our logic for \code{let} can remain simple, as
  9617. in the exerpt above.
  9618. The second step is to mark the occurences of the mutable variables
  9619. with the new \code{GetBang} AST node (\code{get!} in concrete
  9620. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9621. function, which takes two parameters: the set of mutable varaibles
  9622. \code{set!-vars}, and the expression \code{e} to be processed. The
  9623. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9624. mutable variable or leaves it alone if not.
  9625. \begin{center}
  9626. \begin{minipage}{\textwidth}
  9627. \begin{lstlisting}
  9628. (define ((uncover-get!-exp set!-vars) e)
  9629. (match e
  9630. [(Var x)
  9631. (if (set-member? set!-vars x)
  9632. (GetBang x)
  9633. (Var x))]
  9634. ...))
  9635. \end{lstlisting}
  9636. \end{minipage}
  9637. \end{center}
  9638. To wrap things up, define the \code{uncover-get!} function for
  9639. processing a whole program, using \code{collect-set!} to obtain the
  9640. set of mutable variables and then \code{uncover-get!-exp} to replace
  9641. their occurences with \code{GetBang}.
  9642. \fi}
  9643. \section{Remove Complex Operands}
  9644. \label{sec:rco-loop}
  9645. {\if\edition\racketEd
  9646. %
  9647. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9648. \code{while} are all complex expressions. The subexpressions of
  9649. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9650. %
  9651. \fi}
  9652. {\if\edition\pythonEd
  9653. %
  9654. The change needed for this pass is to add a case for the \code{while}
  9655. statement. The condition of a \code{while} loop is allowed to be a
  9656. complex expression, just like the condition of the \code{if}
  9657. statement.
  9658. %
  9659. \fi}
  9660. %
  9661. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9662. \LangLoopANF{} of this pass.
  9663. \newcommand{\LwhileMonadASTPython}{
  9664. \begin{array}{rcl}
  9665. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9666. \end{array}
  9667. }
  9668. \begin{figure}[tp]
  9669. \centering
  9670. \fbox{
  9671. \begin{minipage}{0.96\textwidth}
  9672. \small
  9673. {\if\edition\racketEd
  9674. \[
  9675. \begin{array}{rcl}
  9676. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} } \MID \VOID{} \\
  9677. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9678. &\MID& \GETBANG{\Var}
  9679. \MID \SETBANG{\Var}{\Exp} \\
  9680. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9681. \MID \WHILE{\Exp}{\Exp} \\
  9682. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9683. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9684. \end{array}
  9685. \]
  9686. \fi}
  9687. {\if\edition\pythonEd
  9688. \[
  9689. \begin{array}{l}
  9690. \gray{\LvarMonadASTPython} \\ \hline
  9691. \gray{\LifMonadASTPython} \\ \hline
  9692. \LwhileMonadASTPython \\
  9693. \begin{array}{rcl}
  9694. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9695. \end{array}
  9696. \end{array}
  9697. %% \begin{array}{rcl}
  9698. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9699. %% \Exp &::=& \Atm \MID \READ{} \\
  9700. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9701. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9702. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9703. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9704. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9705. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9706. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9707. %% \end{array}
  9708. \]
  9709. \fi}
  9710. \end{minipage}
  9711. }
  9712. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9713. \label{fig:Rwhile-anf-syntax}
  9714. \end{figure}
  9715. {\if\edition\racketEd
  9716. As usual, when a complex expression appears in a grammar position that
  9717. needs to be atomic, such as the argument of a primitive operator, we
  9718. must introduce a temporary variable and bind it to the complex
  9719. expression. This approach applies, unchanged, to handle the new
  9720. language forms. For example, in the following code there are two
  9721. \code{begin} expressions appearing as arguments to \code{+}. The
  9722. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9723. expressions have been bound to temporary variables. Recall that
  9724. \code{let} expressions in \LangLoopANF{} are allowed to have
  9725. arbitrary expressions in their right-hand-side expression, so it is
  9726. fine to place \code{begin} there.
  9727. \begin{center}
  9728. \begin{minipage}{\textwidth}
  9729. \begin{lstlisting}
  9730. (let ([x0 10])
  9731. (let ([y1 0])
  9732. (+ (+ (begin (set! y1 (read)) x0)
  9733. (begin (set! x0 (read)) y1))
  9734. x0)))
  9735. |$\Rightarrow$|
  9736. (let ([x0 10])
  9737. (let ([y1 0])
  9738. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9739. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9740. (let ([tmp4 (+ tmp2 tmp3)])
  9741. (+ tmp4 x0))))))
  9742. \end{lstlisting}
  9743. \end{minipage}
  9744. \end{center}
  9745. \fi}
  9746. \section{Explicate Control \racket{and \LangCLoop{}}}
  9747. \label{sec:explicate-loop}
  9748. \newcommand{\CloopASTRacket}{
  9749. \begin{array}{lcl}
  9750. \Atm &::=& \VOID \\
  9751. \Stmt &::=& \READ{}\\
  9752. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9753. \end{array}
  9754. }
  9755. {\if\edition\racketEd
  9756. Recall that in the \code{explicate\_control} pass we define one helper
  9757. function for each kind of position in the program. For the \LangVar{}
  9758. language of integers and variables we needed kinds of positions:
  9759. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9760. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9761. yet another kind of position: effect position. Except for the last
  9762. subexpression, the subexpressions inside a \code{begin} are evaluated
  9763. only for their effect. Their result values are discarded. We can
  9764. generate better code by taking this fact into account.
  9765. The output language of \code{explicate\_control} is \LangCLoop{}
  9766. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9767. \LangCIf{}. The only syntactic difference is that \code{read} may also
  9768. appear as a statement. The most significant difference between the
  9769. programs generated by \code{explicate\_control} in
  9770. Chapter~\ref{ch:Lif} versus \code{explicate\_control} in this chapter
  9771. is that the control-flow graphs of the later may contain cycles.
  9772. \begin{figure}[tp]
  9773. \fbox{
  9774. \begin{minipage}{0.96\textwidth}
  9775. \small
  9776. \[
  9777. \begin{array}{l}
  9778. \gray{\CvarASTRacket} \\ \hline
  9779. \gray{\CifASTRacket} \\ \hline
  9780. \CloopASTRacket \\
  9781. \begin{array}{lcl}
  9782. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9783. \end{array}
  9784. \end{array}
  9785. \]
  9786. \end{minipage}
  9787. }
  9788. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9789. \label{fig:c7-syntax}
  9790. \end{figure}
  9791. The new auxiliary function \code{explicate\_effect} takes an
  9792. expression (in an effect position) and a continuation. The function
  9793. returns a $\Tail$ that includes the generated code for the input
  9794. expression followed by the continuation. If the expression is
  9795. obviously pure, that is, never causes side effects, then the
  9796. expression can be removed, so the result is just the continuation.
  9797. %
  9798. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9799. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9800. the loop. Recursively process the \itm{body} (in effect position)
  9801. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9802. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9803. \itm{body'} as the then-branch and the continuation block as the
  9804. else-branch. The result should be added to the control-flow graph with
  9805. the label \itm{loop}. The result for the whole \code{while} loop is a
  9806. \code{goto} to the \itm{loop} label.
  9807. The auxiliary functions for tail, assignment, and predicate positions
  9808. need to be updated. The three new language forms, \code{while},
  9809. \code{set!}, and \code{begin}, can appear in assignment and tail
  9810. positions. Only \code{begin} may appear in predicate positions; the
  9811. other two have result type \code{Void}.
  9812. \fi}
  9813. %
  9814. {\if\edition\pythonEd
  9815. %
  9816. The output of this pass is the language \LangCIf{}. No new language
  9817. features are needed in the output because a \code{while} loop can be
  9818. expressed in terms of \code{goto} and \code{if} statements, which are
  9819. already in \LangCIf{}.
  9820. %
  9821. Add a case for the \code{while} statement to the
  9822. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9823. the condition expression.
  9824. %
  9825. \fi}
  9826. {\if\edition\racketEd
  9827. \section{Select Instructions}
  9828. \label{sec:select-instructions-loop}
  9829. Only three small additions are needed in the
  9830. \code{select\_instructions} pass to handle the changes to
  9831. \LangCLoop{}. That is, a call to
  9832. \racket{\code{read}}\python{\code{input\_int}} may appear as a
  9833. stand-alone statement instead of only appearing on the right-hand side
  9834. of an assignment statement. The code generation is nearly identical;
  9835. just leave off the instruction for moving the result into the
  9836. left-hand side.
  9837. \fi}
  9838. \section{Register Allocation}
  9839. \label{sec:register-allocation-loop}
  9840. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9841. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9842. which complicates the liveness analysis needed for register
  9843. allocation.
  9844. \subsection{Liveness Analysis}
  9845. \label{sec:liveness-analysis-r8}
  9846. We recommend using the generic \code{analyze\_dataflow} function that
  9847. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9848. perform liveness analysis, replacing the code in
  9849. \code{uncover\_live} that processed the basic blocks in topological
  9850. order (Section~\ref{sec:liveness-analysis-Lif}).
  9851. The \code{analyze\_dataflow} function has four parameters.
  9852. \begin{enumerate}
  9853. \item The first parameter \code{G} should be a directed graph from the
  9854. \racket{
  9855. \code{racket/graph} package (see the sidebar in
  9856. Section~\ref{sec:build-interference})}
  9857. \python{\code{graph.py} file in the support code}
  9858. that represents the
  9859. control-flow graph.
  9860. \item The second parameter \code{transfer} is a function that applies
  9861. liveness analysis to a basic block. It takes two parameters: the
  9862. label for the block to analyze and the live-after set for that
  9863. block. The transfer function should return the live-before set for
  9864. the block.
  9865. %
  9866. \racket{Also, as a side-effect, it should update the block's
  9867. $\itm{info}$ with the liveness information for each instruction.}
  9868. %
  9869. \python{Also, as a side-effect, it should update the live-before and
  9870. live-after sets for each instruction.}
  9871. %
  9872. To implement the \code{transfer} function, you should be able to
  9873. reuse the code you already have for analyzing basic blocks.
  9874. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9875. \code{bottom} and \code{join} for the lattice of abstract states,
  9876. i.e. sets of locations. The bottom of the lattice is the empty set
  9877. and the join operator is set union.
  9878. \end{enumerate}
  9879. \begin{figure}[p]
  9880. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9881. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9882. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9883. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9884. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9885. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9886. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9887. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9888. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9889. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9890. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9891. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9892. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9893. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9894. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9895. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9896. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9897. %% \path[->,bend left=15] (Rfun) edge [above] node
  9898. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9899. \path[->,bend left=15] (Rfun) edge [above] node
  9900. {\ttfamily\footnotesize shrink} (Rfun-2);
  9901. \path[->,bend left=15] (Rfun-2) edge [above] node
  9902. {\ttfamily\footnotesize uniquify} (F1-4);
  9903. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9904. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9905. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9906. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9907. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9908. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9909. %% \path[->,bend right=15] (F1-2) edge [above] node
  9910. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9911. %% \path[->,bend right=15] (F1-3) edge [above] node
  9912. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9913. \path[->,bend left=15] (F1-4) edge [above] node
  9914. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9915. \path[->,bend left=15] (F1-5) edge [right] node
  9916. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9917. \path[->,bend left=15] (C3-2) edge [left] node
  9918. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9919. \path[->,bend right=15] (x86-2) edge [left] node
  9920. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9921. \path[->,bend right=15] (x86-2-1) edge [below] node
  9922. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9923. \path[->,bend right=15] (x86-2-2) edge [left] node
  9924. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9925. \path[->,bend left=15] (x86-3) edge [above] node
  9926. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9927. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9928. \end{tikzpicture}
  9929. \caption{Diagram of the passes for \LangLoop{}.}
  9930. \label{fig:Rwhile-passes}
  9931. \end{figure}
  9932. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9933. for the compilation of \LangLoop{}.
  9934. % Further Reading: dataflow analysis
  9935. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9936. \chapter{Tuples and Garbage Collection}
  9937. \label{ch:Lvec}
  9938. \index{subject}{tuple}
  9939. \index{subject}{vector}
  9940. \index{subject}{allocate}
  9941. \index{subject}{heap allocate}
  9942. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9943. %% all the IR grammars are spelled out! \\ --Jeremy}
  9944. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9945. %% the root stack. \\ --Jeremy}
  9946. In this chapter we study the implementation of
  9947. tuples\racket{, called vectors in Racket}.
  9948. %
  9949. This language feature is the first to use the computer's
  9950. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9951. indefinite, that is, a tuple lives forever from the programmer's
  9952. viewpoint. Of course, from an implementer's viewpoint, it is important
  9953. to reclaim the space associated with a tuple when it is no longer
  9954. needed, which is why we also study \emph{garbage collection}
  9955. \index{garbage collection} techniques in this chapter.
  9956. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9957. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9958. language of Chapter~\ref{ch:Lwhile} with tuples.
  9959. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9960. copying live tuples back and forth between two halves of the heap. The
  9961. garbage collector requires coordination with the compiler so that it
  9962. can find all of the live tuples.
  9963. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9964. discuss the necessary changes and additions to the compiler passes,
  9965. including a new compiler pass named \code{expose\_allocation}.
  9966. \section{The \LangVec{} Language}
  9967. \label{sec:r3}
  9968. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9969. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9970. %
  9971. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9972. creating a tuple, \code{vector-ref} for reading an element of a
  9973. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9974. \code{vector-length} for obtaining the number of elements of a
  9975. tuple.}
  9976. %
  9977. \python{The \LangVec{} language adds 1) tuple creation via a
  9978. comma-separated list of expressions, 2) accessing an element of a
  9979. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9980. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  9981. operator, and 4) obtaining the number of elements (the length) of a
  9982. tuple. In this chapter, we restrict access indices to constant
  9983. integers.}
  9984. %
  9985. The program below shows an example use of tuples. It creates a tuple
  9986. \code{t} containing the elements \code{40},
  9987. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  9988. contains just \code{2}. The element at index $1$ of \code{t} is
  9989. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  9990. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  9991. to which we add \code{2}, the element at index $0$ of the tuple. So
  9992. the result of the program is \code{42}.
  9993. %
  9994. {\if\edition\racketEd
  9995. \begin{lstlisting}
  9996. (let ([t (vector 40 #t (vector 2))])
  9997. (if (vector-ref t 1)
  9998. (+ (vector-ref t 0)
  9999. (vector-ref (vector-ref t 2) 0))
  10000. 44))
  10001. \end{lstlisting}
  10002. \fi}
  10003. {\if\edition\pythonEd
  10004. \begin{lstlisting}
  10005. t = 40, True, (2,)
  10006. print( t[0] + t[2][0] if t[1] else 44 )
  10007. \end{lstlisting}
  10008. \fi}
  10009. \newcommand{\LtupGrammarRacket}{
  10010. \begin{array}{lcl}
  10011. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  10012. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  10013. \MID \LP\key{vector-length}\;\Exp\RP \\
  10014. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10015. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10016. \end{array}
  10017. }
  10018. \newcommand{\LtupASTRacket}{
  10019. \begin{array}{lcl}
  10020. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  10021. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10022. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10023. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10024. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10025. \end{array}
  10026. }
  10027. \newcommand{\LtupGrammarPython}{
  10028. \begin{array}{rcl}
  10029. \itm{cmp} &::= & \key{is} \\
  10030. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10031. \end{array}
  10032. }
  10033. \newcommand{\LtupASTPython}{
  10034. \begin{array}{lcl}
  10035. \itm{cmp} &::= & \code{Is()} \\
  10036. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10037. &\MID& \LEN{\Exp}
  10038. \end{array}
  10039. }
  10040. \begin{figure}[tbp]
  10041. \centering
  10042. \fbox{
  10043. \begin{minipage}{0.96\textwidth}
  10044. {\if\edition\racketEd
  10045. \[
  10046. \begin{array}{l}
  10047. \gray{\LintGrammarRacket{}} \\ \hline
  10048. \gray{\LvarGrammarRacket{}} \\ \hline
  10049. \gray{\LifGrammarRacket{}} \\ \hline
  10050. \gray{\LwhileGrammarRacket} \\ \hline
  10051. \LtupGrammarRacket \\
  10052. \begin{array}{lcl}
  10053. \LangVecM{} &::=& \Exp
  10054. \end{array}
  10055. \end{array}
  10056. \]
  10057. \fi}
  10058. {\if\edition\pythonEd
  10059. \[
  10060. \begin{array}{l}
  10061. \gray{\LintGrammarPython{}} \\ \hline
  10062. \gray{\LvarGrammarPython{}} \\ \hline
  10063. \gray{\LifGrammarPython{}} \\ \hline
  10064. \gray{\LwhileGrammarPython} \\ \hline
  10065. \LtupGrammarPython \\
  10066. \begin{array}{rcl}
  10067. \LangVecM{} &::=& \Stmt^{*}
  10068. \end{array}
  10069. \end{array}
  10070. \]
  10071. \fi}
  10072. \end{minipage}
  10073. }
  10074. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10075. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10076. \label{fig:Lvec-concrete-syntax}
  10077. \end{figure}
  10078. \begin{figure}[tp]
  10079. \centering
  10080. \fbox{
  10081. \begin{minipage}{0.96\textwidth}
  10082. {\if\edition\racketEd
  10083. \[
  10084. \begin{array}{l}
  10085. \gray{\LintOpAST} \\ \hline
  10086. \gray{\LvarASTRacket{}} \\ \hline
  10087. \gray{\LifASTRacket{}} \\ \hline
  10088. \gray{\LwhileASTRacket{}} \\ \hline
  10089. \LtupASTRacket{} \\
  10090. \begin{array}{lcl}
  10091. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10092. \end{array}
  10093. \end{array}
  10094. \]
  10095. \fi}
  10096. {\if\edition\pythonEd
  10097. \[
  10098. \begin{array}{l}
  10099. \gray{\LintASTPython} \\ \hline
  10100. \gray{\LvarASTPython} \\ \hline
  10101. \gray{\LifASTPython} \\ \hline
  10102. \gray{\LwhileASTPython} \\ \hline
  10103. \LtupASTPython \\
  10104. \begin{array}{lcl}
  10105. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10106. \end{array}
  10107. \end{array}
  10108. \]
  10109. \fi}
  10110. \end{minipage}
  10111. }
  10112. \caption{The abstract syntax of \LangVec{}.}
  10113. \label{fig:Lvec-syntax}
  10114. \end{figure}
  10115. Tuples raise several interesting new issues. First, variable binding
  10116. performs a shallow-copy when dealing with tuples, which means that
  10117. different variables can refer to the same tuple, that is, two
  10118. variables can be \emph{aliases}\index{subject}{alias} for the same
  10119. entity. Consider the following example in which both \code{t1} and
  10120. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10121. different tuple value but with equal elements. The result of the
  10122. program is \code{42}.
  10123. \begin{center}
  10124. \begin{minipage}{0.96\textwidth}
  10125. {\if\edition\racketEd
  10126. \begin{lstlisting}
  10127. (let ([t1 (vector 3 7)])
  10128. (let ([t2 t1])
  10129. (let ([t3 (vector 3 7)])
  10130. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10131. 42
  10132. 0))))
  10133. \end{lstlisting}
  10134. \fi}
  10135. {\if\edition\pythonEd
  10136. \begin{lstlisting}
  10137. t1 = 3, 7
  10138. t2 = t1
  10139. t3 = 3, 7
  10140. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10141. \end{lstlisting}
  10142. \fi}
  10143. \end{minipage}
  10144. \end{center}
  10145. {\if\edition\racketEd
  10146. Whether two variables are aliased or not affects what happens
  10147. when the underlying tuple is mutated\index{subject}{mutation}.
  10148. Consider the following example in which \code{t1} and \code{t2}
  10149. again refer to the same tuple value.
  10150. \begin{center}
  10151. \begin{minipage}{0.96\textwidth}
  10152. \begin{lstlisting}
  10153. (let ([t1 (vector 3 7)])
  10154. (let ([t2 t1])
  10155. (let ([_ (vector-set! t2 0 42)])
  10156. (vector-ref t1 0))))
  10157. \end{lstlisting}
  10158. \end{minipage}
  10159. \end{center}
  10160. The mutation through \code{t2} is visible when referencing the tuple
  10161. from \code{t1}, so the result of this program is \code{42}.
  10162. \fi}
  10163. The next issue concerns the lifetime of tuples. When does their
  10164. lifetime end? Notice that \LangVec{} does not include an operation
  10165. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10166. to any notion of static scoping.
  10167. %
  10168. {\if\edition\racketEd
  10169. %
  10170. For example, the following program returns \code{42} even though the
  10171. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10172. that reads from the vector it was bound to.
  10173. \begin{center}
  10174. \begin{minipage}{0.96\textwidth}
  10175. \begin{lstlisting}
  10176. (let ([v (vector (vector 44))])
  10177. (let ([x (let ([w (vector 42)])
  10178. (let ([_ (vector-set! v 0 w)])
  10179. 0))])
  10180. (+ x (vector-ref (vector-ref v 0) 0))))
  10181. \end{lstlisting}
  10182. \end{minipage}
  10183. \end{center}
  10184. \fi}
  10185. %
  10186. {\if\edition\pythonEd
  10187. %
  10188. For example, the following program returns \code{42} even though the
  10189. variable \code{x} goes out of scope when the function returns, prior
  10190. to reading the tuple element at index zero. (We study the compilation
  10191. of functions in Chapter~\ref{ch:Lfun}.)
  10192. %
  10193. \begin{center}
  10194. \begin{minipage}{0.96\textwidth}
  10195. \begin{lstlisting}
  10196. def f():
  10197. x = 42, 43
  10198. return x
  10199. t = f()
  10200. print( t[0] )
  10201. \end{lstlisting}
  10202. \end{minipage}
  10203. \end{center}
  10204. \fi}
  10205. %
  10206. From the perspective of programmer-observable behavior, tuples live
  10207. forever. However, if they really lived forever then many long-running
  10208. programs would run out of memory. To solve this problem, the
  10209. language's runtime system performs automatic garbage collection.
  10210. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10211. \LangVec{} language.
  10212. %
  10213. \racket{We define the \code{vector}, \code{vector-ref},
  10214. \code{vector-set!}, and \code{vector-length} operations for
  10215. \LangVec{} in terms of the corresponding operations in Racket. One
  10216. subtle point is that the \code{vector-set!} operation returns the
  10217. \code{\#<void>} value.}
  10218. %
  10219. \python{We represent tuples with Python lists in the interpreter
  10220. because we need to write to them
  10221. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10222. immutable.) We define element access, the \code{is} operator, and
  10223. the \code{len} operator for \LangVec{} in terms of the corresponding
  10224. operations in Python.}
  10225. \begin{figure}[tbp]
  10226. {\if\edition\racketEd
  10227. \begin{lstlisting}
  10228. (define interp-Lvec_class
  10229. (class interp-Lif_class
  10230. (super-new)
  10231. (define/override (interp-op op)
  10232. (match op
  10233. ['eq? (lambda (v1 v2)
  10234. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10235. (and (boolean? v1) (boolean? v2))
  10236. (and (vector? v1) (vector? v2))
  10237. (and (void? v1) (void? v2)))
  10238. (eq? v1 v2)]))]
  10239. ['vector vector]
  10240. ['vector-length vector-length]
  10241. ['vector-ref vector-ref]
  10242. ['vector-set! vector-set!]
  10243. [else (super interp-op op)]
  10244. ))
  10245. (define/override ((interp-exp env) e)
  10246. (define recur (interp-exp env))
  10247. (match e
  10248. [(HasType e t) (recur e)]
  10249. [(Void) (void)]
  10250. [else ((super interp-exp env) e)]
  10251. ))
  10252. ))
  10253. (define (interp-Lvec p)
  10254. (send (new interp-Lvec_class) interp-program p))
  10255. \end{lstlisting}
  10256. \fi}
  10257. %
  10258. {\if\edition\pythonEd
  10259. \begin{lstlisting}
  10260. class InterpLtup(InterpLwhile):
  10261. def interp_cmp(self, cmp):
  10262. match cmp:
  10263. case Is():
  10264. return lambda x, y: x is y
  10265. case _:
  10266. return super().interp_cmp(cmp)
  10267. def interp_exp(self, e, env):
  10268. match e:
  10269. case Tuple(es, Load()):
  10270. return tuple([self.interp_exp(e, env) for e in es])
  10271. case Subscript(tup, index, Load()):
  10272. t = self.interp_exp(tup, env)
  10273. n = self.interp_exp(index, env)
  10274. return t[n]
  10275. case _:
  10276. return super().interp_exp(e, env)
  10277. \end{lstlisting}
  10278. \fi}
  10279. \caption{Interpreter for the \LangVec{} language.}
  10280. \label{fig:interp-Lvec}
  10281. \end{figure}
  10282. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10283. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10284. we need to know which elements of the tuple are themselves tuples for
  10285. the purposes of garbage collection. We can obtain this information
  10286. during type checking. The type checker in
  10287. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10288. expression, it also
  10289. %
  10290. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10291. where $T$ is the vector's type.
  10292. To create the s-expression for the \code{Vector} type in
  10293. Figure~\ref{fig:type-check-Lvec}, we use the
  10294. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10295. operator} \code{,@} to insert the list \code{t*} without its usual
  10296. start and end parentheses. \index{subject}{unquote-slicing}}
  10297. %
  10298. \python{records the type of each tuple expression in a new field
  10299. named \code{has\_type}. Because the type checker has to compute the type
  10300. of each tuple access, the index must be a constant.}
  10301. \begin{figure}[tp]
  10302. {\if\edition\racketEd
  10303. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10304. (define type-check-Lvec_class
  10305. (class type-check-Lif_class
  10306. (super-new)
  10307. (inherit check-type-equal?)
  10308. (define/override (type-check-exp env)
  10309. (lambda (e)
  10310. (define recur (type-check-exp env))
  10311. (match e
  10312. [(Void) (values (Void) 'Void)]
  10313. [(Prim 'vector es)
  10314. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10315. (define t `(Vector ,@t*))
  10316. (values (HasType (Prim 'vector e*) t) t)]
  10317. [(Prim 'vector-ref (list e1 (Int i)))
  10318. (define-values (e1^ t) (recur e1))
  10319. (match t
  10320. [`(Vector ,ts ...)
  10321. (unless (and (0 . <= . i) (i . < . (length ts)))
  10322. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10323. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10324. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10325. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10326. (define-values (e-vec t-vec) (recur e1))
  10327. (define-values (e-arg^ t-arg) (recur arg))
  10328. (match t-vec
  10329. [`(Vector ,ts ...)
  10330. (unless (and (0 . <= . i) (i . < . (length ts)))
  10331. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10332. (check-type-equal? (list-ref ts i) t-arg e)
  10333. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10334. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10335. [(Prim 'vector-length (list e))
  10336. (define-values (e^ t) (recur e))
  10337. (match t
  10338. [`(Vector ,ts ...)
  10339. (values (Prim 'vector-length (list e^)) 'Integer)]
  10340. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10341. [(Prim 'eq? (list arg1 arg2))
  10342. (define-values (e1 t1) (recur arg1))
  10343. (define-values (e2 t2) (recur arg2))
  10344. (match* (t1 t2)
  10345. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10346. [(other wise) (check-type-equal? t1 t2 e)])
  10347. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10348. [(HasType (Prim 'vector es) t)
  10349. ((type-check-exp env) (Prim 'vector es))]
  10350. [(HasType e1 t)
  10351. (define-values (e1^ t^) (recur e1))
  10352. (check-type-equal? t t^ e)
  10353. (values (HasType e1^ t) t)]
  10354. [else ((super type-check-exp env) e)]
  10355. )))
  10356. ))
  10357. (define (type-check-Lvec p)
  10358. (send (new type-check-Lvec_class) type-check-program p))
  10359. \end{lstlisting}
  10360. \fi}
  10361. {\if\edition\pythonEd
  10362. \begin{lstlisting}
  10363. class TypeCheckLtup(TypeCheckLwhile):
  10364. def type_check_exp(self, e, env):
  10365. match e:
  10366. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10367. l = self.type_check_exp(left, env)
  10368. r = self.type_check_exp(right, env)
  10369. check_type_equal(l, r, e)
  10370. return bool
  10371. case Tuple(es, Load()):
  10372. ts = [self.type_check_exp(e, env) for e in es]
  10373. e.has_type = tuple(ts)
  10374. return e.has_type
  10375. case Subscript(tup, Constant(index), Load()):
  10376. tup_ty = self.type_check_exp(tup, env)
  10377. index_ty = self.type_check_exp(Constant(index), env)
  10378. check_type_equal(index_ty, int, index)
  10379. match tup_ty:
  10380. case tuple(ts):
  10381. return ts[index]
  10382. case _:
  10383. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10384. case _:
  10385. return super().type_check_exp(e, env)
  10386. \end{lstlisting}
  10387. \fi}
  10388. \caption{Type checker for the \LangVec{} language.}
  10389. \label{fig:type-check-Lvec}
  10390. \end{figure}
  10391. \section{Garbage Collection}
  10392. \label{sec:GC}
  10393. Garbage collection is a runtime technique for reclaiming space on the
  10394. heap that will not be used in the future of the running program. We
  10395. use the term \emph{object}\index{subject}{object} to refer to any
  10396. value that is stored in the heap, which for now only includes
  10397. tuples.%
  10398. %
  10399. \footnote{The term ``object'' as used in the context of
  10400. object-oriented programming has a more specific meaning than how we
  10401. are using the term here.}
  10402. %
  10403. Unfortunately, it is impossible to know precisely which objects will
  10404. be accessed in the future and which will not. Instead, garbage
  10405. collectors overapproximate the set of objects that will be accessed by
  10406. identifying which objects can possibly be accessed. The running
  10407. program can directly access objects that are in registers and on the
  10408. procedure call stack. It can also transitively access the elements of
  10409. tuples, starting with a tuple whose address is in a register or on the
  10410. procedure call stack. We define the \emph{root
  10411. set}\index{subject}{root set} to be all the tuple addresses that are
  10412. in registers or on the procedure call stack. We define the \emph{live
  10413. objects}\index{subject}{live objects} to be the objects that are
  10414. reachable from the root set. Garbage collectors reclaim the space that
  10415. is allocated to objects that are no longer live. That means that some
  10416. objects may not get reclaimed as soon as they could be, but at least
  10417. garbage collectors do not reclaim the space dedicated to objects that
  10418. will be accessed in the future! The programmer can influence which
  10419. objects get reclaimed by causing them to become unreachable.
  10420. So the goal of the garbage collector is twofold:
  10421. \begin{enumerate}
  10422. \item preserve all the live objects, and
  10423. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10424. \end{enumerate}
  10425. \subsection{Two-Space Copying Collector}
  10426. Here we study a relatively simple algorithm for garbage collection
  10427. that is the basis of many state-of-the-art garbage
  10428. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10429. particular, we describe a two-space copying
  10430. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10431. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10432. collector} \index{subject}{two-space copying collector}
  10433. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10434. what happens in a two-space collector, showing two time steps, prior
  10435. to garbage collection (on the top) and after garbage collection (on
  10436. the bottom). In a two-space collector, the heap is divided into two
  10437. parts named the FromSpace\index{subject}{FromSpace} and the
  10438. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10439. FromSpace until there is not enough room for the next allocation
  10440. request. At that point, the garbage collector goes to work to room for
  10441. the next allocation.
  10442. A copying collector makes more room by copying all of the live objects
  10443. from the FromSpace into the ToSpace and then performs a sleight of
  10444. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10445. as the new ToSpace. In the example of
  10446. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10447. root set, one in a register and two on the stack. All of the live
  10448. objects have been copied to the ToSpace (the right-hand side of
  10449. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10450. pointer relationships. For example, the pointer in the register still
  10451. points to a tuple that in turn points to two other tuples. There are
  10452. four tuples that are not reachable from the root set and therefore do
  10453. not get copied into the ToSpace.
  10454. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10455. created by a well-typed program in \LangVec{} because it contains a
  10456. cycle. However, creating cycles will be possible once we get to
  10457. \LangDyn{}. We design the garbage collector to deal with cycles to
  10458. begin with so we will not need to revisit this issue.
  10459. \begin{figure}[tbp]
  10460. \centering
  10461. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10462. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10463. \\[5ex]
  10464. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10465. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10466. \caption{A copying collector in action.}
  10467. \label{fig:copying-collector}
  10468. \end{figure}
  10469. \subsection{Graph Copying via Cheney's Algorithm}
  10470. \label{sec:cheney}
  10471. \index{subject}{Cheney's algorithm}
  10472. Let us take a closer look at the copying of the live objects. The
  10473. allocated objects and pointers can be viewed as a graph and we need to
  10474. copy the part of the graph that is reachable from the root set. To
  10475. make sure we copy all of the reachable vertices in the graph, we need
  10476. an exhaustive graph traversal algorithm, such as depth-first search or
  10477. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10478. such algorithms take into account the possibility of cycles by marking
  10479. which vertices have already been visited, so as to ensure termination
  10480. of the algorithm. These search algorithms also use a data structure
  10481. such as a stack or queue as a to-do list to keep track of the vertices
  10482. that need to be visited. We use breadth-first search and a trick
  10483. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10484. and copying tuples into the ToSpace.
  10485. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10486. copy progresses. The queue is represented by a chunk of contiguous
  10487. memory at the beginning of the ToSpace, using two pointers to track
  10488. the front and the back of the queue, called the \emph{free pointer}
  10489. and the \emph{scan pointer} respectively. The algorithm starts by
  10490. copying all tuples that are immediately reachable from the root set
  10491. into the ToSpace to form the initial queue. When we copy a tuple, we
  10492. mark the old tuple to indicate that it has been visited. We discuss
  10493. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10494. that any pointers inside the copied tuples in the queue still point
  10495. back to the FromSpace. Once the initial queue has been created, the
  10496. algorithm enters a loop in which it repeatedly processes the tuple at
  10497. the front of the queue and pops it off the queue. To process a tuple,
  10498. the algorithm copies all the tuple that are directly reachable from it
  10499. to the ToSpace, placing them at the back of the queue. The algorithm
  10500. then updates the pointers in the popped tuple so they point to the
  10501. newly copied tuples.
  10502. \begin{figure}[tbp]
  10503. \centering
  10504. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10505. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10506. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10507. \label{fig:cheney}
  10508. \end{figure}
  10509. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10510. tuple whose second element is $42$ to the back of the queue. The other
  10511. pointer goes to a tuple that has already been copied, so we do not
  10512. need to copy it again, but we do need to update the pointer to the new
  10513. location. This can be accomplished by storing a \emph{forwarding
  10514. pointer}\index{subect}{forwarding pointer} to the new location in the
  10515. old tuple, back when we initially copied the tuple into the
  10516. ToSpace. This completes one step of the algorithm. The algorithm
  10517. continues in this way until the queue is empty, that is, when the scan
  10518. pointer catches up with the free pointer.
  10519. \subsection{Data Representation}
  10520. \label{sec:data-rep-gc}
  10521. The garbage collector places some requirements on the data
  10522. representations used by our compiler. First, the garbage collector
  10523. needs to distinguish between pointers and other kinds of data such as
  10524. integers. There are several ways to accomplish this.
  10525. \begin{enumerate}
  10526. \item Attached a tag to each object that identifies what type of
  10527. object it is~\citep{McCarthy:1960dz}.
  10528. \item Store different types of objects in different
  10529. regions~\citep{Steele:1977ab}.
  10530. \item Use type information from the program to either generate
  10531. type-specific code for collecting or to generate tables that can
  10532. guide the
  10533. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10534. \end{enumerate}
  10535. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10536. need to tag objects anyways, so option 1 is a natural choice for those
  10537. languages. However, \LangVec{} is a statically typed language, so it
  10538. would be unfortunate to require tags on every object, especially small
  10539. and pervasive objects like integers and Booleans. Option 3 is the
  10540. best-performing choice for statically typed languages, but comes with
  10541. a relatively high implementation complexity. To keep this chapter
  10542. within a reasonable time budget, we recommend a combination of options
  10543. 1 and 2, using separate strategies for the stack and the heap.
  10544. Regarding the stack, we recommend using a separate stack for pointers,
  10545. which we call the \emph{root stack}\index{subject}{root stack}
  10546. (a.k.a. ``shadow
  10547. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10548. is, when a local variable needs to be spilled and is of type
  10549. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10550. root stack instead of putting it on the procedure call
  10551. stack. Furthermore, we always spill tuple-typed variables if they are
  10552. live during a call to the collector, thereby ensuring that no pointers
  10553. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10554. reproduces the example from Figure~\ref{fig:copying-collector} and
  10555. contrasts it with the data layout using a root stack. The root stack
  10556. contains the two pointers from the regular stack and also the pointer
  10557. in the second register.
  10558. \begin{figure}[tbp]
  10559. \centering
  10560. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10561. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10562. \caption{Maintaining a root stack to facilitate garbage collection.}
  10563. \label{fig:shadow-stack}
  10564. \end{figure}
  10565. The problem of distinguishing between pointers and other kinds of data
  10566. also arises inside of each tuple on the heap. We solve this problem by
  10567. attaching a tag, an extra 64-bits, to each
  10568. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10569. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10570. that we have drawn the bits in a big-endian way, from right-to-left,
  10571. with bit location 0 (the least significant bit) on the far right,
  10572. which corresponds to the direction of the x86 shifting instructions
  10573. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10574. is dedicated to specifying which elements of the tuple are pointers,
  10575. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10576. indicates there is a pointer and a 0 bit indicates some other kind of
  10577. data. The pointer mask starts at bit location 7. We limit tuples to a
  10578. maximum size of 50 elements, so we just need 50 bits for the pointer
  10579. mask.%
  10580. %
  10581. \footnote{A production-quality compiler would handle
  10582. arbitrary-sized tuples and use a more complex approach.}
  10583. %
  10584. The tag also contains two other pieces of information. The length of
  10585. the tuple (number of elements) is stored in bits location 1 through
  10586. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10587. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10588. has not yet been copied. If the bit has value 0 then the entire tag
  10589. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10590. zero anyways because our tuples are 8-byte aligned.)
  10591. \begin{figure}[tbp]
  10592. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10593. \caption{Representation of tuples in the heap.}
  10594. \label{fig:tuple-rep}
  10595. \end{figure}
  10596. \subsection{Implementation of the Garbage Collector}
  10597. \label{sec:organize-gz}
  10598. \index{subject}{prelude}
  10599. An implementation of the copying collector is provided in the
  10600. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10601. interface to the garbage collector that is used by the compiler. The
  10602. \code{initialize} function creates the FromSpace, ToSpace, and root
  10603. stack and should be called in the prelude of the \code{main}
  10604. function. The arguments of \code{initialize} are the root stack size
  10605. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10606. good choice for both. The \code{initialize} function puts the address
  10607. of the beginning of the FromSpace into the global variable
  10608. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10609. the address that is 1-past the last element of the FromSpace. (We use
  10610. half-open intervals to represent chunks of
  10611. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10612. points to the first element of the root stack.
  10613. As long as there is room left in the FromSpace, your generated code
  10614. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10615. %
  10616. The amount of room left in FromSpace is the difference between the
  10617. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10618. function should be called when there is not enough room left in the
  10619. FromSpace for the next allocation. The \code{collect} function takes
  10620. a pointer to the current top of the root stack (one past the last item
  10621. that was pushed) and the number of bytes that need to be
  10622. allocated. The \code{collect} function performs the copying collection
  10623. and leaves the heap in a state such that the next allocation will
  10624. succeed.
  10625. \begin{figure}[tbp]
  10626. \begin{lstlisting}
  10627. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10628. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10629. int64_t* free_ptr;
  10630. int64_t* fromspace_begin;
  10631. int64_t* fromspace_end;
  10632. int64_t** rootstack_begin;
  10633. \end{lstlisting}
  10634. \caption{The compiler's interface to the garbage collector.}
  10635. \label{fig:gc-header}
  10636. \end{figure}
  10637. %% \begin{exercise}
  10638. %% In the file \code{runtime.c} you will find the implementation of
  10639. %% \code{initialize} and a partial implementation of \code{collect}.
  10640. %% The \code{collect} function calls another function, \code{cheney},
  10641. %% to perform the actual copy, and that function is left to the reader
  10642. %% to implement. The following is the prototype for \code{cheney}.
  10643. %% \begin{lstlisting}
  10644. %% static void cheney(int64_t** rootstack_ptr);
  10645. %% \end{lstlisting}
  10646. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10647. %% rootstack (which is an array of pointers). The \code{cheney} function
  10648. %% also communicates with \code{collect} through the global
  10649. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10650. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10651. %% the ToSpace:
  10652. %% \begin{lstlisting}
  10653. %% static int64_t* tospace_begin;
  10654. %% static int64_t* tospace_end;
  10655. %% \end{lstlisting}
  10656. %% The job of the \code{cheney} function is to copy all the live
  10657. %% objects (reachable from the root stack) into the ToSpace, update
  10658. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10659. %% update the root stack so that it points to the objects in the
  10660. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10661. %% and ToSpace.
  10662. %% \end{exercise}
  10663. The introduction of garbage collection has a non-trivial impact on our
  10664. compiler passes. We introduce a new compiler pass named
  10665. \code{expose\_allocation}. We make significant changes to
  10666. \code{select\_instructions}, \code{build\_interference},
  10667. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10668. make minor changes in several more passes. The following program will
  10669. serve as our running example. It creates two tuples, one nested
  10670. inside the other. Both tuples have length one. The program accesses
  10671. the element in the inner tuple.
  10672. % tests/vectors_test_17.rkt
  10673. {\if\edition\racketEd
  10674. \begin{lstlisting}
  10675. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10676. \end{lstlisting}
  10677. \fi}
  10678. {\if\edition\pythonEd
  10679. \begin{lstlisting}
  10680. print( ((42,),)[0][0] )
  10681. \end{lstlisting}
  10682. \fi}
  10683. {\if\edition\racketEd
  10684. \section{Shrink}
  10685. \label{sec:shrink-Lvec}
  10686. Recall that the \code{shrink} pass translates the primitives operators
  10687. into a smaller set of primitives.
  10688. %
  10689. This pass comes after type checking and the type checker adds a
  10690. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10691. need to add a case for \code{HasType} to the \code{shrink} pass.
  10692. \fi}
  10693. \section{Expose Allocation}
  10694. \label{sec:expose-allocation}
  10695. The pass \code{expose\_allocation} lowers tuple creation into a
  10696. conditional call to the collector followed by allocating the
  10697. appropriate amount of memory and initializing it. We choose to place
  10698. the \code{expose\_allocation} pass before
  10699. \code{remove\_complex\_operands} because the code generated by
  10700. \code{expose\_allocation} contains complex operands.
  10701. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10702. that extends \LangVec{} with new forms that we use in the translation
  10703. of tuple creation.
  10704. %
  10705. {\if\edition\racketEd
  10706. \[
  10707. \begin{array}{lcl}
  10708. \Exp &::=& \cdots
  10709. \MID (\key{collect} \,\itm{int})
  10710. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10711. \MID (\key{global-value} \,\itm{name})
  10712. \end{array}
  10713. \]
  10714. \fi}
  10715. {\if\edition\pythonEd
  10716. \[
  10717. \begin{array}{lcl}
  10718. \Exp &::=& \cdots\\
  10719. &\MID& \key{collect}(\itm{int})
  10720. \MID \key{allocate}(\itm{int},\itm{type})
  10721. \MID \key{global\_value}(\itm{name}) \\
  10722. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10723. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10724. \end{array}
  10725. \]
  10726. \fi}
  10727. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10728. make sure that there are $n$ bytes ready to be allocated. During
  10729. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10730. the \code{collect} function in \code{runtime.c}.
  10731. %
  10732. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10733. space at the front for the 64 bit tag), but the elements are not
  10734. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10735. of the tuple:
  10736. %
  10737. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10738. %
  10739. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10740. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10741. as \code{free\_ptr}.
  10742. %
  10743. \python{The \code{begin} form is an expression that executes a
  10744. sequence of statements and then produces the value of the expression
  10745. at the end.}
  10746. The following shows the transformation of tuple creation into 1) a
  10747. sequence of temporary variables bindings for the initializing
  10748. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10749. \code{allocate}, and 4) the initialization of the tuple. The
  10750. \itm{len} placeholder refers to the length of the tuple and
  10751. \itm{bytes} is how many total bytes need to be allocated for the
  10752. tuple, which is 8 for the tag plus \itm{len} times 8.
  10753. %
  10754. \python{The \itm{type} needed for the second argument of the
  10755. \code{allocate} form can be obtained from the \code{has\_type} field
  10756. of the tuple AST node, which is stored there by running the type
  10757. checker for \LangVec{} immediately before this pass.}
  10758. %
  10759. \begin{center}
  10760. \begin{minipage}{\textwidth}
  10761. {\if\edition\racketEd
  10762. \begin{lstlisting}
  10763. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10764. |$\Longrightarrow$|
  10765. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10766. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10767. (global-value fromspace_end))
  10768. (void)
  10769. (collect |\itm{bytes}|))])
  10770. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10771. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10772. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10773. |$v$|) ... )))) ...)
  10774. \end{lstlisting}
  10775. \fi}
  10776. {\if\edition\pythonEd
  10777. \begin{lstlisting}
  10778. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10779. |$\Longrightarrow$|
  10780. begin:
  10781. |$x_0$| = |$e_0$|
  10782. |$\vdots$|
  10783. |$x_{n-1}$| = |$e_{n-1}$|
  10784. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10785. 0
  10786. else:
  10787. collect(|\itm{bytes}|)
  10788. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10789. |$v$|[0] = |$x_0$|
  10790. |$\vdots$|
  10791. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10792. |$v$|
  10793. \end{lstlisting}
  10794. \fi}
  10795. \end{minipage}
  10796. \end{center}
  10797. %
  10798. \noindent The sequencing of the initializing expressions
  10799. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10800. they may trigger garbage collection and we cannot have an allocated
  10801. but uninitialized tuple on the heap during a collection.
  10802. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10803. \code{expose\_allocation} pass on our running example.
  10804. \begin{figure}[tbp]
  10805. % tests/s2_17.rkt
  10806. {\if\edition\racketEd
  10807. \begin{lstlisting}
  10808. (vector-ref
  10809. (vector-ref
  10810. (let ([vecinit7976
  10811. (let ([vecinit7972 42])
  10812. (let ([collectret7974
  10813. (if (< (+ (global-value free_ptr) 16)
  10814. (global-value fromspace_end))
  10815. (void)
  10816. (collect 16)
  10817. )])
  10818. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10819. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10820. alloc7971))))])
  10821. (let ([collectret7978
  10822. (if (< (+ (global-value free_ptr) 16)
  10823. (global-value fromspace_end))
  10824. (void)
  10825. (collect 16)
  10826. )])
  10827. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10828. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10829. alloc7975))))
  10830. 0)
  10831. 0)
  10832. \end{lstlisting}
  10833. \fi}
  10834. {\if\edition\pythonEd
  10835. \begin{lstlisting}
  10836. print( |$T_1$|[0][0] )
  10837. \end{lstlisting}
  10838. where $T_1$ is
  10839. \begin{lstlisting}
  10840. begin:
  10841. tmp.1 = |$T_2$|
  10842. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10843. 0
  10844. else:
  10845. collect(16)
  10846. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10847. tmp.2[0] = tmp.1
  10848. tmp.2
  10849. \end{lstlisting}
  10850. and $T_2$ is
  10851. \begin{lstlisting}
  10852. begin:
  10853. tmp.3 = 42
  10854. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10855. 0
  10856. else:
  10857. collect(16)
  10858. tmp.4 = allocate(1, TupleType([int]))
  10859. tmp.4[0] = tmp.3
  10860. tmp.4
  10861. \end{lstlisting}
  10862. \fi}
  10863. \caption{Output of the \code{expose\_allocation} pass.}
  10864. \label{fig:expose-alloc-output}
  10865. \end{figure}
  10866. \section{Remove Complex Operands}
  10867. \label{sec:remove-complex-opera-Lvec}
  10868. {\if\edition\racketEd
  10869. %
  10870. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10871. should be treated as complex operands.
  10872. %
  10873. \fi}
  10874. %
  10875. {\if\edition\pythonEd
  10876. %
  10877. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10878. and tuple access should be treated as complex operands. The
  10879. sub-expressions of tuple access must be atomic.
  10880. %
  10881. \fi}
  10882. %% A new case for
  10883. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10884. %% handled carefully to prevent the \code{Prim} node from being separated
  10885. %% from its enclosing \code{HasType}.
  10886. Figure~\ref{fig:Lvec-anf-syntax}
  10887. shows the grammar for the output language \LangAllocANF{} of this
  10888. pass, which is \LangAlloc{} in monadic normal form.
  10889. \newcommand{\LtupMonadASTPython}{
  10890. \begin{array}{rcl}
  10891. \Exp &::=& \GET{\Atm}{\Atm} \\
  10892. &\MID& \LEN{\Atm}\\
  10893. &\MID& \ALLOCATE{\Int}{\Type}
  10894. \MID \GLOBALVALUE{\Var} \\
  10895. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  10896. &\MID& \COLLECT{\Int}
  10897. \end{array}
  10898. }
  10899. \begin{figure}[tp]
  10900. \centering
  10901. \fbox{
  10902. \begin{minipage}{0.96\textwidth}
  10903. \small
  10904. {\if\edition\racketEd
  10905. \[
  10906. \begin{array}{rcl}
  10907. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10908. \MID \VOID{} } \\
  10909. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10910. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10911. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10912. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10913. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10914. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10915. \MID \GLOBALVALUE{\Var}\\
  10916. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10917. \LangAllocANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10918. \end{array}
  10919. \]
  10920. \fi}
  10921. {\if\edition\pythonEd
  10922. \[
  10923. \begin{array}{l}
  10924. \gray{\LvarMonadASTPython} \\ \hline
  10925. \gray{\LifMonadASTPython} \\ \hline
  10926. \gray{\LwhileMonadASTPython} \\ \hline
  10927. \LtupMonadASTPython \\
  10928. \begin{array}{rcl}
  10929. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10930. \end{array}
  10931. \end{array}
  10932. %% \begin{array}{lcl}
  10933. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10934. %% \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10935. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10936. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10937. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  10938. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10939. %% \Exp &::=& \Atm \MID \READ{} \MID \\
  10940. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  10941. %% \MID \UNIOP{\itm{unaryop}}{\Atm}\\
  10942. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  10943. %% % \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp} \\ % removed by RCO
  10944. %% &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10945. %% &\MID& \GET{\Atm}{\Atm} \\
  10946. %% &\MID& \LEN{\Exp}\\
  10947. %% &\MID& \ALLOCATE{\Int}{\Type}
  10948. %% \MID \GLOBALVALUE{\Var}\RP\\
  10949. %% &\MID& \BEGIN{\Stmt^{*}}{\Atm} \\ % can use this in place of \LET;
  10950. %% % why have \LET?
  10951. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10952. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10953. %% &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10954. %% &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10955. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10956. %% \MID \COLLECT{\Int} \\
  10957. %% \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10958. %% \end{array}
  10959. \]
  10960. \fi}
  10961. \end{minipage}
  10962. }
  10963. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  10964. \label{fig:Lvec-anf-syntax}
  10965. \end{figure}
  10966. \section{Explicate Control and the \LangCVec{} language}
  10967. \label{sec:explicate-control-r3}
  10968. \newcommand{\CtupASTRacket}{
  10969. \begin{array}{lcl}
  10970. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10971. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  10972. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10973. &\MID& \VECLEN{\Atm} \\
  10974. &\MID& \GLOBALVALUE{\Var} \\
  10975. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10976. &\MID& \LP\key{Collect} \,\itm{int}\RP
  10977. \end{array}
  10978. }
  10979. \newcommand{\CtupASTPython}{
  10980. \begin{array}{lcl}
  10981. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  10982. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  10983. \Stmt &::=& \COLLECT{\Int} \\
  10984. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  10985. \end{array}
  10986. }
  10987. \begin{figure}[tp]
  10988. \fbox{
  10989. \begin{minipage}{0.96\textwidth}
  10990. \small
  10991. {\if\edition\racketEd
  10992. \[
  10993. \begin{array}{l}
  10994. \gray{\CvarASTRacket} \\ \hline
  10995. \gray{\CifASTRacket} \\ \hline
  10996. \gray{\CloopASTRacket} \\ \hline
  10997. \CtupASTRacket \\
  10998. \begin{array}{lcl}
  10999. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11000. \end{array}
  11001. \end{array}
  11002. \]
  11003. \fi}
  11004. {\if\edition\pythonEd
  11005. \[
  11006. \begin{array}{l}
  11007. \gray{\CifASTPython} \\ \hline
  11008. \CtupASTPython \\
  11009. \begin{array}{lcl}
  11010. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11011. \end{array}
  11012. \end{array}
  11013. \]
  11014. \fi}
  11015. \end{minipage}
  11016. }
  11017. \caption{The abstract syntax of \LangCVec{}, extending
  11018. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11019. (Figure~\ref{fig:c1-syntax})}.}
  11020. \label{fig:c2-syntax}
  11021. \end{figure}
  11022. The output of \code{explicate\_control} is a program in the
  11023. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11024. Figure~\ref{fig:c2-syntax}.
  11025. %
  11026. \racket{(The concrete syntax is defined in
  11027. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11028. %
  11029. The new expressions of \LangCVec{} include \key{allocate},
  11030. %
  11031. \racket{\key{vector-ref}, and \key{vector-set!},}
  11032. %
  11033. \python{accessing tuple elements,}
  11034. %
  11035. and \key{global\_value}.
  11036. %
  11037. \python{\LangCVec{} also includes the \code{collect} statement and
  11038. assignment to a tuple element.}
  11039. %
  11040. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11041. %
  11042. The \code{explicate\_control} pass can treat these new forms much like
  11043. the other forms that we've already encoutered.
  11044. \section{Select Instructions and the \LangXGlobal{} Language}
  11045. \label{sec:select-instructions-gc}
  11046. \index{subject}{instruction selection}
  11047. %% void (rep as zero)
  11048. %% allocate
  11049. %% collect (callq collect)
  11050. %% vector-ref
  11051. %% vector-set!
  11052. %% vector-length
  11053. %% global (postpone)
  11054. In this pass we generate x86 code for most of the new operations that
  11055. were needed to compile tuples, including \code{Allocate},
  11056. \code{Collect}, and accessing tuple elements.
  11057. %
  11058. We compile \code{GlobalValue} to \code{Global} because the later has a
  11059. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11060. \ref{fig:x86-2}). \index{subject}{x86}
  11061. The tuple read and write forms translate into \code{movq}
  11062. instructions. (The plus one in the offset is to get past the tag at
  11063. the beginning of the tuple representation.)
  11064. %
  11065. \begin{center}
  11066. \begin{minipage}{\textwidth}
  11067. {\if\edition\racketEd
  11068. \begin{lstlisting}
  11069. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11070. |$\Longrightarrow$|
  11071. movq |$\itm{tup}'$|, %r11
  11072. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11073. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11074. |$\Longrightarrow$|
  11075. movq |$\itm{tup}'$|, %r11
  11076. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11077. movq $0, |$\itm{lhs'}$|
  11078. \end{lstlisting}
  11079. \fi}
  11080. {\if\edition\pythonEd
  11081. \begin{lstlisting}
  11082. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11083. |$\Longrightarrow$|
  11084. movq |$\itm{tup}'$|, %r11
  11085. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11086. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11087. |$\Longrightarrow$|
  11088. movq |$\itm{tup}'$|, %r11
  11089. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11090. \end{lstlisting}
  11091. \fi}
  11092. \end{minipage}
  11093. \end{center}
  11094. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11095. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11096. are obtained by translating from \LangCVec{} to x86.
  11097. %
  11098. The move of $\itm{tup}'$ to
  11099. register \code{r11} ensures that offset expression
  11100. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  11101. removing \code{r11} from consideration by the register allocating.
  11102. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11103. \code{rax}. Then the generated code for tuple assignment would be
  11104. \begin{lstlisting}
  11105. movq |$\itm{tup}'$|, %rax
  11106. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11107. \end{lstlisting}
  11108. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11109. \code{patch\_instructions} would insert a move through \code{rax}
  11110. as follows.
  11111. \begin{lstlisting}
  11112. movq |$\itm{tup}'$|, %rax
  11113. movq |$\itm{rhs}'$|, %rax
  11114. movq %rax, |$8(n+1)$|(%rax)
  11115. \end{lstlisting}
  11116. But the above sequence of instructions does not work because we're
  11117. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11118. $\itm{rhs}'$) at the same time!
  11119. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11120. be translated into a sequence of instructions that read the tag of the
  11121. tuple and extract the six bits that represent the tuple length, which
  11122. are the bits starting at index 1 and going up to and including bit 6.
  11123. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11124. (shift right) can be used to accomplish this.
  11125. We compile the \code{allocate} form to operations on the
  11126. \code{free\_ptr}, as shown below. This approach is called \emph{inline
  11127. allocation} as it implements allocation by bumping the allocation
  11128. pointer. It is much more efficient than calling a function for each
  11129. allocation. The address in the \code{free\_ptr}
  11130. is the next free address in the FromSpace, so we copy it into
  11131. \code{r11} and then move it forward by enough space for the tuple
  11132. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  11133. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  11134. initialize the \itm{tag} and finally copy the address in \code{r11} to
  11135. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  11136. tag is organized.
  11137. %
  11138. \racket{We recommend using the Racket operations
  11139. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11140. during compilation.}
  11141. %
  11142. \python{We recommend using the bitwise-or operator \code{|} and the
  11143. shift-left operator \code{<<} to compute the tag during
  11144. compilation.}
  11145. %
  11146. The type annotation in the \code{allocate} form is used to determine
  11147. the pointer mask region of the tag.
  11148. %
  11149. Do not worry about the addressing mode \verb!free_ptr(%rip)!. It
  11150. essentially stands for the address \code{free\_ptr}, but uses a
  11151. special instruction-pointer relative addressing mode of the x86-64
  11152. processor.
  11153. %
  11154. {\if\edition\racketEd
  11155. \begin{lstlisting}
  11156. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11157. |$\Longrightarrow$|
  11158. movq free_ptr(%rip), %r11
  11159. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11160. movq $|$\itm{tag}$|, 0(%r11)
  11161. movq %r11, |$\itm{lhs}'$|
  11162. \end{lstlisting}
  11163. \fi}
  11164. {\if\edition\pythonEd
  11165. \begin{lstlisting}
  11166. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11167. |$\Longrightarrow$|
  11168. movq free_ptr(%rip), %r11
  11169. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11170. movq $|$\itm{tag}$|, 0(%r11)
  11171. movq %r11, |$\itm{lhs}'$|
  11172. \end{lstlisting}
  11173. \fi}
  11174. The \code{collect} form is compiled to a call to the \code{collect}
  11175. function in the runtime. The arguments to \code{collect} are 1) the
  11176. top of the root stack and 2) the number of bytes that need to be
  11177. allocated. We use another dedicated register, \code{r15}, to
  11178. store the pointer to the top of the root stack. So \code{r15} is not
  11179. available for use by the register allocator.
  11180. {\if\edition\racketEd
  11181. \begin{lstlisting}
  11182. (collect |$\itm{bytes}$|)
  11183. |$\Longrightarrow$|
  11184. movq %r15, %rdi
  11185. movq $|\itm{bytes}|, %rsi
  11186. callq collect
  11187. \end{lstlisting}
  11188. \fi}
  11189. {\if\edition\pythonEd
  11190. \begin{lstlisting}
  11191. collect(|$\itm{bytes}$|)
  11192. |$\Longrightarrow$|
  11193. movq %r15, %rdi
  11194. movq $|\itm{bytes}|, %rsi
  11195. callq collect
  11196. \end{lstlisting}
  11197. \fi}
  11198. \begin{figure}[tp]
  11199. \fbox{
  11200. \begin{minipage}{0.96\textwidth}
  11201. \[
  11202. \begin{array}{lcl}
  11203. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  11204. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  11205. & & \gray{ \key{main:} \; \Instr^{*} }
  11206. \end{array}
  11207. \]
  11208. \end{minipage}
  11209. }
  11210. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11211. \label{fig:x86-2-concrete}
  11212. \end{figure}
  11213. \begin{figure}[tp]
  11214. \fbox{
  11215. \begin{minipage}{0.96\textwidth}
  11216. \small
  11217. \[
  11218. \begin{array}{lcl}
  11219. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11220. \MID \BYTEREG{\Reg}} \\
  11221. &\MID& \GLOBAL{\Var} \\
  11222. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11223. \end{array}
  11224. \]
  11225. \end{minipage}
  11226. }
  11227. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11228. \label{fig:x86-2}
  11229. \end{figure}
  11230. The concrete and abstract syntax of the \LangXGlobal{} language is
  11231. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11232. differs from \LangXIf{} just in the addition of global variables.
  11233. %
  11234. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11235. \code{select\_instructions} pass on the running example.
  11236. \begin{figure}[tbp]
  11237. \centering
  11238. % tests/s2_17.rkt
  11239. \begin{minipage}[t]{0.5\textwidth}
  11240. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11241. block35:
  11242. movq free_ptr(%rip), alloc9024
  11243. addq $16, free_ptr(%rip)
  11244. movq alloc9024, %r11
  11245. movq $131, 0(%r11)
  11246. movq alloc9024, %r11
  11247. movq vecinit9025, 8(%r11)
  11248. movq $0, initret9026
  11249. movq alloc9024, %r11
  11250. movq 8(%r11), tmp9034
  11251. movq tmp9034, %r11
  11252. movq 8(%r11), %rax
  11253. jmp conclusion
  11254. block36:
  11255. movq $0, collectret9027
  11256. jmp block35
  11257. block38:
  11258. movq free_ptr(%rip), alloc9020
  11259. addq $16, free_ptr(%rip)
  11260. movq alloc9020, %r11
  11261. movq $3, 0(%r11)
  11262. movq alloc9020, %r11
  11263. movq vecinit9021, 8(%r11)
  11264. movq $0, initret9022
  11265. movq alloc9020, vecinit9025
  11266. movq free_ptr(%rip), tmp9031
  11267. movq tmp9031, tmp9032
  11268. addq $16, tmp9032
  11269. movq fromspace_end(%rip), tmp9033
  11270. cmpq tmp9033, tmp9032
  11271. jl block36
  11272. jmp block37
  11273. block37:
  11274. movq %r15, %rdi
  11275. movq $16, %rsi
  11276. callq 'collect
  11277. jmp block35
  11278. block39:
  11279. movq $0, collectret9023
  11280. jmp block38
  11281. \end{lstlisting}
  11282. \end{minipage}
  11283. \begin{minipage}[t]{0.45\textwidth}
  11284. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11285. start:
  11286. movq $42, vecinit9021
  11287. movq free_ptr(%rip), tmp9028
  11288. movq tmp9028, tmp9029
  11289. addq $16, tmp9029
  11290. movq fromspace_end(%rip), tmp9030
  11291. cmpq tmp9030, tmp9029
  11292. jl block39
  11293. jmp block40
  11294. block40:
  11295. movq %r15, %rdi
  11296. movq $16, %rsi
  11297. callq 'collect
  11298. jmp block38
  11299. \end{lstlisting}
  11300. \end{minipage}
  11301. \caption{Output of the \code{select\_instructions} pass.}
  11302. \label{fig:select-instr-output-gc}
  11303. \end{figure}
  11304. \clearpage
  11305. \section{Register Allocation}
  11306. \label{sec:reg-alloc-gc}
  11307. \index{subject}{register allocation}
  11308. As discussed earlier in this chapter, the garbage collector needs to
  11309. access all the pointers in the root set, that is, all variables that
  11310. are tuples. It will be the responsibility of the register allocator
  11311. to make sure that:
  11312. \begin{enumerate}
  11313. \item the root stack is used for spilling tuple-typed variables, and
  11314. \item if a tuple-typed variable is live during a call to the
  11315. collector, it must be spilled to ensure it is visible to the
  11316. collector.
  11317. \end{enumerate}
  11318. The later responsibility can be handled during construction of the
  11319. interference graph, by adding interference edges between the call-live
  11320. tuple-typed variables and all the callee-saved registers. (They
  11321. already interfere with the caller-saved registers.)
  11322. %
  11323. \racket{The type information for variables is in the \code{Program}
  11324. form, so we recommend adding another parameter to the
  11325. \code{build\_interference} function to communicate this alist.}
  11326. %
  11327. \python{The type information for variables is generated by the type
  11328. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11329. the \code{CProgram} AST mode. You'll need to propagate that
  11330. information so that it is available in this pass.}
  11331. The spilling of tuple-typed variables to the root stack can be handled
  11332. after graph coloring, when choosing how to assign the colors
  11333. (integers) to registers and stack locations. The
  11334. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11335. changes to also record the number of spills to the root stack.
  11336. % build-interference
  11337. %
  11338. % callq
  11339. % extra parameter for var->type assoc. list
  11340. % update 'program' and 'if'
  11341. % allocate-registers
  11342. % allocate spilled vectors to the rootstack
  11343. % don't change color-graph
  11344. % TODO:
  11345. %\section{Patch Instructions}
  11346. %[mention that global variables are memory references]
  11347. \section{Prelude and Conclusion}
  11348. \label{sec:print-x86-gc}
  11349. \label{sec:prelude-conclusion-x86-gc}
  11350. \index{subject}{prelude}\index{subject}{conclusion}
  11351. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11352. \code{prelude\_and\_conclusion} pass on the running example. In the
  11353. prelude and conclusion of the \code{main} function, we allocate space
  11354. on the root stack to make room for the spills of tuple-typed
  11355. variables. We do so by bumping the root stack
  11356. pointer (\code{r15}) taking care that the root stack grows up instead of down. For the running
  11357. example, there was just one spill so we increment \code{r15} by 8
  11358. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11359. One issue that deserves special care is that there may be a call to
  11360. \code{collect} prior to the initializing assignments for all the
  11361. variables in the root stack. We do not want the garbage collector to
  11362. accidentally think that some uninitialized variable is a pointer that
  11363. needs to be followed. Thus, we zero-out all locations on the root
  11364. stack in the prelude of \code{main}. In
  11365. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11366. %
  11367. \lstinline{movq $0, 0(%r15)}
  11368. %
  11369. is sufficient to accomplish this task because there is only one spill.
  11370. In general, we have to clear as many words as there are spills of
  11371. tuple-typed variables. The garbage collector tests each root to see
  11372. if it is null prior to dereferencing it.
  11373. \begin{figure}[htbp]
  11374. % TODO: Python Version -Jeremy
  11375. \begin{minipage}[t]{0.5\textwidth}
  11376. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11377. block35:
  11378. movq free_ptr(%rip), %rcx
  11379. addq $16, free_ptr(%rip)
  11380. movq %rcx, %r11
  11381. movq $131, 0(%r11)
  11382. movq %rcx, %r11
  11383. movq -8(%r15), %rax
  11384. movq %rax, 8(%r11)
  11385. movq $0, %rdx
  11386. movq %rcx, %r11
  11387. movq 8(%r11), %rcx
  11388. movq %rcx, %r11
  11389. movq 8(%r11), %rax
  11390. jmp conclusion
  11391. block36:
  11392. movq $0, %rcx
  11393. jmp block35
  11394. block38:
  11395. movq free_ptr(%rip), %rcx
  11396. addq $16, free_ptr(%rip)
  11397. movq %rcx, %r11
  11398. movq $3, 0(%r11)
  11399. movq %rcx, %r11
  11400. movq %rbx, 8(%r11)
  11401. movq $0, %rdx
  11402. movq %rcx, -8(%r15)
  11403. movq free_ptr(%rip), %rcx
  11404. addq $16, %rcx
  11405. movq fromspace_end(%rip), %rdx
  11406. cmpq %rdx, %rcx
  11407. jl block36
  11408. movq %r15, %rdi
  11409. movq $16, %rsi
  11410. callq collect
  11411. jmp block35
  11412. block39:
  11413. movq $0, %rcx
  11414. jmp block38
  11415. \end{lstlisting}
  11416. \end{minipage}
  11417. \begin{minipage}[t]{0.45\textwidth}
  11418. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11419. start:
  11420. movq $42, %rbx
  11421. movq free_ptr(%rip), %rdx
  11422. addq $16, %rdx
  11423. movq fromspace_end(%rip), %rcx
  11424. cmpq %rcx, %rdx
  11425. jl block39
  11426. movq %r15, %rdi
  11427. movq $16, %rsi
  11428. callq collect
  11429. jmp block38
  11430. .globl main
  11431. main:
  11432. pushq %rbp
  11433. movq %rsp, %rbp
  11434. pushq %r13
  11435. pushq %r12
  11436. pushq %rbx
  11437. pushq %r14
  11438. subq $0, %rsp
  11439. movq $16384, %rdi
  11440. movq $16384, %rsi
  11441. callq initialize
  11442. movq rootstack_begin(%rip), %r15
  11443. movq $0, 0(%r15)
  11444. addq $8, %r15
  11445. jmp start
  11446. conclusion:
  11447. subq $8, %r15
  11448. addq $0, %rsp
  11449. popq %r14
  11450. popq %rbx
  11451. popq %r12
  11452. popq %r13
  11453. popq %rbp
  11454. retq
  11455. \end{lstlisting}
  11456. \end{minipage}
  11457. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11458. \label{fig:print-x86-output-gc}
  11459. \end{figure}
  11460. \begin{figure}[tbp]
  11461. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11462. \node (Lvec) at (0,2) {\large \LangVec{}};
  11463. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11464. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11465. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11466. \node (Lvec-5) at (9,0) {\large \LangAllocANF{}};
  11467. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11468. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11469. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11470. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11471. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11472. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11473. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11474. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11475. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11476. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11477. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11478. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11479. \path[->,bend left=10] (Lvec-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11480. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11481. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11482. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11483. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11484. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11485. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11486. \end{tikzpicture}
  11487. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11488. \label{fig:Lvec-passes}
  11489. \end{figure}
  11490. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11491. for the compilation of \LangVec{}.
  11492. \clearpage
  11493. {\if\edition\racketEd
  11494. \section{Challenge: Simple Structures}
  11495. \label{sec:simple-structures}
  11496. \index{subject}{struct}
  11497. \index{subject}{structure}
  11498. The language \LangStruct{} extends \LangVec{} with support for simple
  11499. structures. Its concrete syntax is defined in
  11500. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11501. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11502. Racket is a user-defined data type that contains named fields and that
  11503. is heap allocated, similar to a vector. The following is an example of
  11504. a structure definition, in this case the definition of a \code{point}
  11505. type.
  11506. \begin{lstlisting}
  11507. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11508. \end{lstlisting}
  11509. \newcommand{\LstructGrammarRacket}{
  11510. \begin{array}{lcl}
  11511. \Type &::=& \Var \\
  11512. \Exp &::=& (\Var\;\Exp \ldots)\\
  11513. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11514. \end{array}
  11515. }
  11516. \newcommand{\LstructASTRacket}{
  11517. \begin{array}{lcl}
  11518. \Type &::=& \VAR{\Var} \\
  11519. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11520. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11521. \end{array}
  11522. }
  11523. \begin{figure}[tbp]
  11524. \centering
  11525. \fbox{
  11526. \begin{minipage}{0.96\textwidth}
  11527. \[
  11528. \begin{array}{l}
  11529. \gray{\LintGrammarRacket{}} \\ \hline
  11530. \gray{\LvarGrammarRacket{}} \\ \hline
  11531. \gray{\LifGrammarRacket{}} \\ \hline
  11532. \gray{\LwhileGrammarRacket} \\ \hline
  11533. \gray{\LtupGrammarRacket} \\ \hline
  11534. \LstructGrammarRacket \\
  11535. \begin{array}{lcl}
  11536. \LangStruct{} &::=& \Def \ldots \; \Exp
  11537. \end{array}
  11538. \end{array}
  11539. \]
  11540. \end{minipage}
  11541. }
  11542. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11543. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11544. \label{fig:Lstruct-concrete-syntax}
  11545. \end{figure}
  11546. \begin{figure}[tbp]
  11547. \centering
  11548. \fbox{
  11549. \begin{minipage}{0.96\textwidth}
  11550. \[
  11551. \begin{array}{l}
  11552. \gray{\LintASTRacket{}} \\ \hline
  11553. \gray{\LvarASTRacket{}} \\ \hline
  11554. \gray{\LifASTRacket{}} \\ \hline
  11555. \gray{\LwhileASTRacket} \\ \hline
  11556. \gray{\LtupASTRacket} \\ \hline
  11557. \LstructASTRacket \\
  11558. \begin{array}{lcl}
  11559. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11560. \end{array}
  11561. \end{array}
  11562. \]
  11563. \end{minipage}
  11564. }
  11565. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11566. (Figure~\ref{fig:Lvec-syntax}).}
  11567. \label{fig:Lstruct-syntax}
  11568. \end{figure}
  11569. An instance of a structure is created using function call syntax, with
  11570. the name of the structure in the function position:
  11571. \begin{lstlisting}
  11572. (point 7 12)
  11573. \end{lstlisting}
  11574. Function-call syntax is also used to read the value in a field of a
  11575. structure. The function name is formed by the structure name, a dash,
  11576. and the field name. The following example uses \code{point-x} and
  11577. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11578. instances.
  11579. \begin{center}
  11580. \begin{lstlisting}
  11581. (let ([pt1 (point 7 12)])
  11582. (let ([pt2 (point 4 3)])
  11583. (+ (- (point-x pt1) (point-x pt2))
  11584. (- (point-y pt1) (point-y pt2)))))
  11585. \end{lstlisting}
  11586. \end{center}
  11587. Similarly, to write to a field of a structure, use its set function,
  11588. whose name starts with \code{set-}, followed by the structure name,
  11589. then a dash, then the field name, and concluded with an exclamation
  11590. mark. The following example uses \code{set-point-x!} to change the
  11591. \code{x} field from \code{7} to \code{42}.
  11592. \begin{center}
  11593. \begin{lstlisting}
  11594. (let ([pt (point 7 12)])
  11595. (let ([_ (set-point-x! pt 42)])
  11596. (point-x pt)))
  11597. \end{lstlisting}
  11598. \end{center}
  11599. \begin{exercise}\normalfont
  11600. Create a type checker for \LangStruct{} by extending the type
  11601. checker for \LangVec{}. Extend your compiler with support for simple
  11602. structures, compiling \LangStruct{} to x86 assembly code. Create
  11603. five new test cases that use structures and test your compiler.
  11604. \end{exercise}
  11605. % TODO: create an interpreter for L_struct
  11606. \clearpage
  11607. \section{Challenge: Arrays}
  11608. \label{sec:arrays}
  11609. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11610. elements whose length is determined at compile-time and where each
  11611. element of a tuple may have a different type (they are
  11612. heterogeous). This challenge is also about sequences, but this time
  11613. the length is determined at run-time and all the elements have the same
  11614. type (they are homogeneous). We use the term ``array'' for this later
  11615. kind of sequence.
  11616. The Racket language does not distinguish between tuples and arrays,
  11617. they are both represented by vectors. However, Typed Racket
  11618. distinguishes between tuples and arrays: the \code{Vector} type is for
  11619. tuples and the \code{Vectorof} type is for arrays.
  11620. %
  11621. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11622. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11623. and the \code{make-vector} primitive operator for creating an array,
  11624. whose arguments are the length of the array and an initial value for
  11625. all the elements in the array. The \code{vector-length},
  11626. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11627. for tuples become overloaded for use with arrays.
  11628. %
  11629. We also include integer multiplication in \LangArray{}, as it is
  11630. useful in many examples involving arrays such as computing the
  11631. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11632. \begin{figure}[tp]
  11633. \centering
  11634. \fbox{
  11635. \begin{minipage}{0.96\textwidth}
  11636. \small
  11637. {\if\edition\racketEd
  11638. \[
  11639. \begin{array}{lcl}
  11640. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11641. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11642. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11643. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11644. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11645. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11646. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11647. \MID \LP\key{not}\;\Exp\RP } \\
  11648. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11649. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11650. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11651. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11652. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11653. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11654. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11655. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11656. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11657. \MID \CWHILE{\Exp}{\Exp} } \\
  11658. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11659. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11660. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11661. \end{array}
  11662. \]
  11663. \fi}
  11664. {\if\edition\pythonEd
  11665. UNDER CONSTRUCTION
  11666. \fi}
  11667. \end{minipage}
  11668. }
  11669. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11670. \label{fig:Lvecof-concrete-syntax}
  11671. \end{figure}
  11672. \begin{figure}[tp]
  11673. \begin{lstlisting}
  11674. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11675. [n : Integer]) : Integer
  11676. (let ([i 0])
  11677. (let ([prod 0])
  11678. (begin
  11679. (while (< i n)
  11680. (begin
  11681. (set! prod (+ prod (* (vector-ref A i)
  11682. (vector-ref B i))))
  11683. (set! i (+ i 1))
  11684. ))
  11685. prod))))
  11686. (let ([A (make-vector 2 2)])
  11687. (let ([B (make-vector 2 3)])
  11688. (+ (inner-product A B 2)
  11689. 30)))
  11690. \end{lstlisting}
  11691. \caption{Example program that computes the inner-product.}
  11692. \label{fig:inner-product}
  11693. \end{figure}
  11694. The type checker for \LangArray{} is define in
  11695. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11696. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11697. of the intializing expression. The length expression is required to
  11698. have type \code{Integer}. The type checking of the operators
  11699. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11700. updated to handle the situation where the vector has type
  11701. \code{Vectorof}. In these cases we translate the operators to their
  11702. \code{vectorof} form so that later passes can easily distinguish
  11703. between operations on tuples versus arrays. We override the
  11704. \code{operator-types} method to provide the type signature for
  11705. multiplication: it takes two integers and returns an integer. To
  11706. support injection and projection of arrays to the \code{Any} type
  11707. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11708. predicate.
  11709. \begin{figure}[tbp]
  11710. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11711. (define type-check-Lvecof_class
  11712. (class type-check-Rwhile_class
  11713. (super-new)
  11714. (inherit check-type-equal?)
  11715. (define/override (flat-ty? ty)
  11716. (match ty
  11717. ['(Vectorof Any) #t]
  11718. [else (super flat-ty? ty)]))
  11719. (define/override (operator-types)
  11720. (append '((* . ((Integer Integer) . Integer)))
  11721. (super operator-types)))
  11722. (define/override (type-check-exp env)
  11723. (lambda (e)
  11724. (define recur (type-check-exp env))
  11725. (match e
  11726. [(Prim 'make-vector (list e1 e2))
  11727. (define-values (e1^ t1) (recur e1))
  11728. (define-values (e2^ elt-type) (recur e2))
  11729. (define vec-type `(Vectorof ,elt-type))
  11730. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11731. vec-type)]
  11732. [(Prim 'vector-ref (list e1 e2))
  11733. (define-values (e1^ t1) (recur e1))
  11734. (define-values (e2^ t2) (recur e2))
  11735. (match* (t1 t2)
  11736. [(`(Vectorof ,elt-type) 'Integer)
  11737. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11738. [(other wise) ((super type-check-exp env) e)])]
  11739. [(Prim 'vector-set! (list e1 e2 e3) )
  11740. (define-values (e-vec t-vec) (recur e1))
  11741. (define-values (e2^ t2) (recur e2))
  11742. (define-values (e-arg^ t-arg) (recur e3))
  11743. (match t-vec
  11744. [`(Vectorof ,elt-type)
  11745. (check-type-equal? elt-type t-arg e)
  11746. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11747. [else ((super type-check-exp env) e)])]
  11748. [(Prim 'vector-length (list e1))
  11749. (define-values (e1^ t1) (recur e1))
  11750. (match t1
  11751. [`(Vectorof ,t)
  11752. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11753. [else ((super type-check-exp env) e)])]
  11754. [else ((super type-check-exp env) e)])))
  11755. ))
  11756. (define (type-check-Lvecof p)
  11757. (send (new type-check-Lvecof_class) type-check-program p))
  11758. \end{lstlisting}
  11759. \caption{Type checker for the \LangArray{} language.}
  11760. \label{fig:type-check-Lvecof}
  11761. \end{figure}
  11762. The interpreter for \LangArray{} is defined in
  11763. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11764. implemented with Racket's \code{make-vector} function and
  11765. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11766. integers.
  11767. \begin{figure}[tbp]
  11768. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11769. (define interp-Lvecof_class
  11770. (class interp-Rwhile_class
  11771. (super-new)
  11772. (define/override (interp-op op)
  11773. (verbose "Lvecof/interp-op" op)
  11774. (match op
  11775. ['make-vector make-vector]
  11776. ['* fx*]
  11777. [else (super interp-op op)]))
  11778. ))
  11779. (define (interp-Lvecof p)
  11780. (send (new interp-Lvecof_class) interp-program p))
  11781. \end{lstlisting}
  11782. \caption{Interpreter for \LangArray{}.}
  11783. \label{fig:interp-Lvecof}
  11784. \end{figure}
  11785. \subsection{Data Representation}
  11786. \label{sec:array-rep}
  11787. Just like tuples, we store arrays on the heap which means that the
  11788. garbage collector will need to inspect arrays. An immediate thought is
  11789. to use the same representation for arrays that we use for tuples.
  11790. However, we limit tuples to a length of $50$ so that their length and
  11791. pointer mask can fit into the 64-bit tag at the beginning of each
  11792. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11793. millions of elements, so we need more bits to store the length.
  11794. However, because arrays are homogeneous, we only need $1$ bit for the
  11795. pointer mask instead of one bit per array elements. Finally, the
  11796. garbage collector will need to be able to distinguish between tuples
  11797. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11798. arrive at the following layout for the 64-bit tag at the beginning of
  11799. an array:
  11800. \begin{itemize}
  11801. \item The right-most bit is the forwarding bit, just like in a tuple.
  11802. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11803. it is not.
  11804. \item The next bit to the left is the pointer mask. A $0$ indicates
  11805. that none of the elements are pointers to the heap and a $1$
  11806. indicates that all of the elements are pointers.
  11807. \item The next $61$ bits store the length of the array.
  11808. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11809. array ($1$).
  11810. \end{itemize}
  11811. Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  11812. differentiate the kinds of values that have been injected into the
  11813. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11814. to indicate that the value is an array.
  11815. In the following subsections we provide hints regarding how to update
  11816. the passes to handle arrays.
  11817. \subsection{Reveal Casts}
  11818. The array-access operators \code{vectorof-ref} and
  11819. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11820. \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  11821. that the type checker cannot tell whether the index will be in bounds,
  11822. so the bounds check must be performed at run time. Recall that the
  11823. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11824. an \code{If} arround a vector reference for update to check whether
  11825. the index is less than the length. You should do the same for
  11826. \code{vectorof-ref} and \code{vectorof-set!} .
  11827. In addition, the handling of the \code{any-vector} operators in
  11828. \code{reveal-casts} needs to be updated to account for arrays that are
  11829. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11830. generated code should test whether the tag is for tuples (\code{010})
  11831. or arrays (\code{110}) and then dispatch to either
  11832. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11833. we add a case in \code{select\_instructions} to generate the
  11834. appropriate instructions for accessing the array length from the
  11835. header of an array.
  11836. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11837. the generated code needs to check that the index is less than the
  11838. vector length, so like the code for \code{any-vector-length}, check
  11839. the tag to determine whether to use \code{any-vector-length} or
  11840. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11841. is complete, the generated code can use \code{any-vector-ref} and
  11842. \code{any-vector-set!} for both tuples and arrays because the
  11843. instructions used for those operators do not look at the tag at the
  11844. front of the tuple or array.
  11845. \subsection{Expose Allocation}
  11846. This pass should translate the \code{make-vector} operator into
  11847. lower-level operations. In particular, the new AST node
  11848. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11849. length specified by the $\Exp$, but does not initialize the elements
  11850. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11851. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11852. element type for the array. Regarding the initialization of the array,
  11853. we recommend generated a \code{while} loop that uses
  11854. \code{vector-set!} to put the initializing value into every element of
  11855. the array.
  11856. \subsection{Remove Complex Operands}
  11857. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11858. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11859. complex and its subexpression must be atomic.
  11860. \subsection{Explicate Control}
  11861. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11862. \code{explicate\_assign}.
  11863. \subsection{Select Instructions}
  11864. Generate instructions for \code{AllocateArray} similar to those for
  11865. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11866. that the tag at the front of the array should instead use the
  11867. representation discussed in Section~\ref{sec:array-rep}.
  11868. Regarding \code{vectorof-length}, extract the length from the tag
  11869. according to the representation discussed in
  11870. Section~\ref{sec:array-rep}.
  11871. The instructions generated for \code{vectorof-ref} differ from those
  11872. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11873. that the index is not a constant so the offset must be computed at
  11874. runtime, similar to the instructions generated for
  11875. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11876. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11877. appear in an assignment and as a stand-alone statement, so make sure
  11878. to handle both situations in this pass.
  11879. Finally, the instructions for \code{any-vectorof-length} should be
  11880. similar to those for \code{vectorof-length}, except that one must
  11881. first project the array by writing zeroes into the $3$-bit tag
  11882. \begin{exercise}\normalfont
  11883. Implement a compiler for the \LangArray{} language by extending your
  11884. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11885. programs, including the one in Figure~\ref{fig:inner-product} and also
  11886. a program that multiplies two matrices. Note that matrices are
  11887. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11888. arrays by laying out each row in the array, one after the next.
  11889. \end{exercise}
  11890. \section{Challenge: Generational Collection}
  11891. The copying collector described in Section~\ref{sec:GC} can incur
  11892. significant runtime overhead because the call to \code{collect} takes
  11893. time proportional to all of the live data. One way to reduce this
  11894. overhead is to reduce how much data is inspected in each call to
  11895. \code{collect}. In particular, researchers have observed that recently
  11896. allocated data is more likely to become garbage then data that has
  11897. survived one or more previous calls to \code{collect}. This insight
  11898. motivated the creation of \emph{generational garbage collectors}
  11899. \index{subject}{generational garbage collector} that
  11900. 1) segregates data according to its age into two or more generations,
  11901. 2) allocates less space for younger generations, so collecting them is
  11902. faster, and more space for the older generations, and 3) performs
  11903. collection on the younger generations more frequently then for older
  11904. generations~\citep{Wilson:1992fk}.
  11905. For this challenge assignment, the goal is to adapt the copying
  11906. collector implemented in \code{runtime.c} to use two generations, one
  11907. for young data and one for old data. Each generation consists of a
  11908. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11909. \code{collect} function to use the two generations.
  11910. \begin{enumerate}
  11911. \item Copy the young generation's FromSpace to its ToSpace then switch
  11912. the role of the ToSpace and FromSpace
  11913. \item If there is enough space for the requested number of bytes in
  11914. the young FromSpace, then return from \code{collect}.
  11915. \item If there is not enough space in the young FromSpace for the
  11916. requested bytes, then move the data from the young generation to the
  11917. old one with the following steps:
  11918. \begin{enumerate}
  11919. \item If there is enough room in the old FromSpace, copy the young
  11920. FromSpace to the old FromSpace and then return.
  11921. \item If there is not enough room in the old FromSpace, then collect
  11922. the old generation by copying the old FromSpace to the old ToSpace
  11923. and swap the roles of the old FromSpace and ToSpace.
  11924. \item If there is enough room now, copy the young FromSpace to the
  11925. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11926. and ToSpace for the old generation. Copy the young FromSpace and
  11927. the old FromSpace into the larger FromSpace for the old
  11928. generation and then return.
  11929. \end{enumerate}
  11930. \end{enumerate}
  11931. We recommend that you generalize the \code{cheney} function so that it
  11932. can be used for all the copies mentioned above: between the young
  11933. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11934. between the young FromSpace and old FromSpace. This can be
  11935. accomplished by adding parameters to \code{cheney} that replace its
  11936. use of the global variables \code{fromspace\_begin},
  11937. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11938. Note that the collection of the young generation does not traverse the
  11939. old generation. This introduces a potential problem: there may be
  11940. young data that is only reachable through pointers in the old
  11941. generation. If these pointers are not taken into account, the
  11942. collector could throw away young data that is live! One solution,
  11943. called \emph{pointer recording}, is to maintain a set of all the
  11944. pointers from the old generation into the new generation and consider
  11945. this set as part of the root set. To maintain this set, the compiler
  11946. must insert extra instructions around every \code{vector-set!}. If the
  11947. vector being modified is in the old generation, and if the value being
  11948. written is a pointer into the new generation, than that pointer must
  11949. be added to the set. Also, if the value being overwritten was a
  11950. pointer into the new generation, then that pointer should be removed
  11951. from the set.
  11952. \begin{exercise}\normalfont
  11953. Adapt the \code{collect} function in \code{runtime.c} to implement
  11954. generational garbage collection, as outlined in this section.
  11955. Update the code generation for \code{vector-set!} to implement
  11956. pointer recording. Make sure that your new compiler and runtime
  11957. passes your test suite.
  11958. \end{exercise}
  11959. \fi}
  11960. \section{Further Reading}
  11961. There are many alternatives to copying collectors (and their bigger
  11962. siblings, the generational collectors) when its comes to garbage
  11963. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  11964. reference counting~\citep{Collins:1960aa}. The strengths of copying
  11965. collectors are that allocation is fast (just a comparison and pointer
  11966. increment), there is no fragmentation, cyclic garbage is collected,
  11967. and the time complexity of collection only depends on the amount of
  11968. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  11969. main disadvantages of a two-space copying collector is that it uses a
  11970. lot of extra space and takes a long time to perform the copy, though
  11971. these problems are ameliorated in generational collectors.
  11972. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  11973. small objects and generate a lot of garbage, so copying and
  11974. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  11975. Garbage collection is an active research topic, especially concurrent
  11976. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  11977. developing new techniques and revisiting old
  11978. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  11979. meet every year at the International Symposium on Memory Management to
  11980. present these findings.
  11981. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11982. \chapter{Functions}
  11983. \label{ch:Lfun}
  11984. \index{subject}{function}
  11985. This chapter studies the compilation of a subset of \racket{Typed
  11986. Racket}\python{Python} in which only top-level function definitions
  11987. are allowed..
  11988. This kind of function is a realistic example as the C language imposes
  11989. similar restrictions. It is also an important stepping stone to
  11990. implementing lexically-scoped functions in the form of \key{lambda}
  11991. abstractions, which is the topic of Chapter~\ref{ch:Llambda}.
  11992. \section{The \LangFun{} Language}
  11993. The concrete and abstract syntax for function definitions and function
  11994. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11995. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11996. \LangFun{} begin with zero or more function definitions. The function
  11997. names from these definitions are in-scope for the entire program,
  11998. including all other function definitions (so the ordering of function
  11999. definitions does not matter).
  12000. %
  12001. \python{The abstract syntax for function parameters in
  12002. Figure~\ref{fig:Rfun-syntax} is a list of pairs, where each pair
  12003. consists of a parameter name and its type. This design differs from
  12004. Python's \code{ast} module, which has a more complex structure for
  12005. function parameters to handle keyword parameters,
  12006. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12007. complex Python abstract syntax into the simpler syntax of
  12008. Figure~\ref{fig:Rfun-syntax}. The fourth and sixth parameters of the
  12009. \code{FunctionDef} constructor are for decorators and a type
  12010. comment, neither of which are used by our compiler. We recommend
  12011. replacing them with \code{None} in the \code{shrink} pass.
  12012. }
  12013. %
  12014. The concrete syntax for function application\index{subject}{function
  12015. application} is
  12016. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12017. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12018. where the first expression
  12019. must evaluate to a function and the remaining expressions are the arguments. The
  12020. abstract syntax for function application is
  12021. $\APPLY{\Exp}{\Exp^*}$.
  12022. %% The syntax for function application does not include an explicit
  12023. %% keyword, which is error prone when using \code{match}. To alleviate
  12024. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12025. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12026. Functions are first-class in the sense that a function pointer
  12027. \index{subject}{function pointer} is data and can be stored in memory or passed
  12028. as a parameter to another function. Thus, there is a function
  12029. type, written
  12030. {\if\edition\racketEd
  12031. \begin{lstlisting}
  12032. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12033. \end{lstlisting}
  12034. \fi}
  12035. {\if\edition\pythonEd
  12036. \begin{lstlisting}
  12037. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12038. \end{lstlisting}
  12039. \fi}
  12040. %
  12041. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12042. through $\Type_n$ and whose return type is $\Type_R$. The main
  12043. limitation of these functions (with respect to
  12044. \racket{Racket}\python{Python} functions) is that they are not
  12045. lexically scoped. That is, the only external entities that can be
  12046. referenced from inside a function body are other globally-defined
  12047. functions. The syntax of \LangFun{} prevents function definitions from being
  12048. nested inside each other.
  12049. \newcommand{\LfunGrammarRacket}{
  12050. \begin{array}{lcl}
  12051. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12052. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12053. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12054. \end{array}
  12055. }
  12056. \newcommand{\LfunASTRacket}{
  12057. \begin{array}{lcl}
  12058. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12059. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12060. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12061. \end{array}
  12062. }
  12063. \newcommand{\LfunGrammarPython}{
  12064. \begin{array}{lcl}
  12065. \Type &::=& \key{int}
  12066. \MID \key{bool}
  12067. \MID \key{tuple}\LS \Type^+ \RS
  12068. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12069. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12070. \Stmt &::=& \CRETURN{\Exp} \\
  12071. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12072. \end{array}
  12073. }
  12074. \newcommand{\LfunASTPython}{
  12075. \begin{array}{lcl}
  12076. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  12077. \MID \key{TupleType}\LS\Type^+\RS\\
  12078. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12079. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12080. \Stmt &::=& \RETURN{\Exp} \\
  12081. \Params &::=& \LP\Var\key{,}\Type\RP^*
  12082. \\
  12083. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12084. \end{array}
  12085. }
  12086. \begin{figure}[tp]
  12087. \centering
  12088. \fbox{
  12089. \begin{minipage}{0.96\textwidth}
  12090. \small
  12091. {\if\edition\racketEd
  12092. \[
  12093. \begin{array}{l}
  12094. \gray{\LintGrammarRacket{}} \\ \hline
  12095. \gray{\LvarGrammarRacket{}} \\ \hline
  12096. \gray{\LifGrammarRacket{}} \\ \hline
  12097. \gray{\LwhileGrammarRacket} \\ \hline
  12098. \gray{\LtupGrammarRacket} \\ \hline
  12099. \LfunGrammarRacket \\
  12100. \begin{array}{lcl}
  12101. \LangFunM{} &::=& \Def \ldots \; \Exp
  12102. \end{array}
  12103. \end{array}
  12104. \]
  12105. \fi}
  12106. {\if\edition\pythonEd
  12107. \[
  12108. \begin{array}{l}
  12109. \gray{\LintGrammarPython{}} \\ \hline
  12110. \gray{\LvarGrammarPython{}} \\ \hline
  12111. \gray{\LifGrammarPython{}} \\ \hline
  12112. \gray{\LwhileGrammarPython} \\ \hline
  12113. \gray{\LtupGrammarPython} \\ \hline
  12114. \LfunGrammarPython \\
  12115. \begin{array}{rcl}
  12116. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12117. \end{array}
  12118. \end{array}
  12119. \]
  12120. \fi}
  12121. \end{minipage}
  12122. }
  12123. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12124. \label{fig:Rfun-concrete-syntax}
  12125. \end{figure}
  12126. \begin{figure}[tp]
  12127. \centering
  12128. \fbox{
  12129. \begin{minipage}{0.96\textwidth}
  12130. \small
  12131. {\if\edition\racketEd
  12132. \[
  12133. \begin{array}{l}
  12134. \gray{\LintOpAST} \\ \hline
  12135. \gray{\LvarASTRacket{}} \\ \hline
  12136. \gray{\LifASTRacket{}} \\ \hline
  12137. \gray{\LwhileASTRacket{}} \\ \hline
  12138. \gray{\LtupASTRacket{}} \\ \hline
  12139. \LfunASTRacket \\
  12140. \begin{array}{lcl}
  12141. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12142. \end{array}
  12143. \end{array}
  12144. \]
  12145. \fi}
  12146. {\if\edition\pythonEd
  12147. \[
  12148. \begin{array}{l}
  12149. \gray{\LintASTPython{}} \\ \hline
  12150. \gray{\LvarASTPython{}} \\ \hline
  12151. \gray{\LifASTPython{}} \\ \hline
  12152. \gray{\LwhileASTPython} \\ \hline
  12153. \gray{\LtupASTPython} \\ \hline
  12154. \LfunASTPython \\
  12155. \begin{array}{rcl}
  12156. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12157. \end{array}
  12158. \end{array}
  12159. \]
  12160. \fi}
  12161. \end{minipage}
  12162. }
  12163. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12164. \label{fig:Rfun-syntax}
  12165. \end{figure}
  12166. The program in Figure~\ref{fig:Rfun-function-example} is a
  12167. representative example of defining and using functions in \LangFun{}.
  12168. We define a function \code{map} that applies some other function
  12169. \code{f} to both elements of a tuple and returns a new tuple
  12170. containing the results. We also define a function \code{inc}. The
  12171. program applies \code{map} to \code{inc} and
  12172. %
  12173. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12174. %
  12175. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12176. %
  12177. from which we return the \code{42}.
  12178. \begin{figure}[tbp]
  12179. {\if\edition\racketEd
  12180. \begin{lstlisting}
  12181. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12182. : (Vector Integer Integer)
  12183. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12184. (define (inc [x : Integer]) : Integer
  12185. (+ x 1))
  12186. (vector-ref (map inc (vector 0 41)) 1)
  12187. \end{lstlisting}
  12188. \fi}
  12189. {\if\edition\pythonEd
  12190. \begin{lstlisting}
  12191. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12192. return f(v[0]), f(v[1])
  12193. def inc(x : int) -> int:
  12194. return x + 1
  12195. print( map(inc, (0, 41))[1] )
  12196. \end{lstlisting}
  12197. \fi}
  12198. \caption{Example of using functions in \LangFun{}.}
  12199. \label{fig:Rfun-function-example}
  12200. \end{figure}
  12201. The definitional interpreter for \LangFun{} is in
  12202. Figure~\ref{fig:interp-Rfun}. The case for the
  12203. %
  12204. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12205. %
  12206. AST is responsible for setting up the mutual recursion between the
  12207. top-level function definitions.
  12208. %
  12209. \racket{We use the classic back-patching
  12210. \index{subject}{back-patching} approach that uses mutable variables
  12211. and makes two passes over the function
  12212. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12213. top-level environment using a mutable cons cell for each function
  12214. definition. Note that the \code{lambda} value for each function is
  12215. incomplete; it does not yet include the environment. Once the
  12216. top-level environment is constructed, we then iterate over it and
  12217. update the \code{lambda} values to use the top-level environment.}
  12218. %
  12219. \python{We create a dictionary named \code{env} and fill it in
  12220. by mapping each function name to a new \code{Function} value,
  12221. each of which stores a reference to the \code{env}.
  12222. (We define the class \code{Function} for this purpose.)}
  12223. %
  12224. To interpret a function \racket{application}\python{call}, we match
  12225. the result of the function expression to obtain a function value. We
  12226. then extend the function's environment with mapping of parameters to
  12227. argument values. Finally, we interpret the body of the function in
  12228. this extended environment.
  12229. \begin{figure}[tp]
  12230. {\if\edition\racketEd
  12231. \begin{lstlisting}
  12232. (define interp-Rfun_class
  12233. (class interp-Lvec_class
  12234. (super-new)
  12235. (define/override ((interp-exp env) e)
  12236. (define recur (interp-exp env))
  12237. (match e
  12238. [(Var x) (unbox (dict-ref env x))]
  12239. [(Let x e body)
  12240. (define new-env (dict-set env x (box (recur e))))
  12241. ((interp-exp new-env) body)]
  12242. [(Apply fun args)
  12243. (define fun-val (recur fun))
  12244. (define arg-vals (for/list ([e args]) (recur e)))
  12245. (match fun-val
  12246. [`(function (,xs ...) ,body ,fun-env)
  12247. (define params-args (for/list ([x xs] [arg arg-vals])
  12248. (cons x (box arg))))
  12249. (define new-env (append params-args fun-env))
  12250. ((interp-exp new-env) body)]
  12251. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12252. [else ((super interp-exp env) e)]
  12253. ))
  12254. (define/public (interp-def d)
  12255. (match d
  12256. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12257. (cons f (box `(function ,xs ,body ())))]))
  12258. (define/override (interp-program p)
  12259. (match p
  12260. [(ProgramDefsExp info ds body)
  12261. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12262. (for/list ([f (in-dict-values top-level)])
  12263. (set-box! f (match (unbox f)
  12264. [`(function ,xs ,body ())
  12265. `(function ,xs ,body ,top-level)])))
  12266. ((interp-exp top-level) body))]))
  12267. ))
  12268. (define (interp-Rfun p)
  12269. (send (new interp-Rfun_class) interp-program p))
  12270. \end{lstlisting}
  12271. \fi}
  12272. {\if\edition\pythonEd
  12273. \begin{lstlisting}
  12274. class InterpLfun(InterpLtup):
  12275. def apply_fun(self, fun, args, e):
  12276. match fun:
  12277. case Function(name, xs, body, env):
  12278. new_env = env.copy().update(zip(xs, args))
  12279. return self.interp_stmts(body, new_env)
  12280. case _:
  12281. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12282. def interp_exp(self, e, env):
  12283. match e:
  12284. case Call(Name('input_int'), []):
  12285. return super().interp_exp(e, env)
  12286. case Call(func, args):
  12287. f = self.interp_exp(func, env)
  12288. vs = [self.interp_exp(arg, env) for arg in args]
  12289. return self.apply_fun(f, vs, e)
  12290. case _:
  12291. return super().interp_exp(e, env)
  12292. def interp_stmts(self, ss, env):
  12293. if len(ss) == 0:
  12294. return
  12295. match ss[0]:
  12296. case Return(value):
  12297. return self.interp_exp(value, env)
  12298. case FunctionDef(name, params, bod, dl, returns, comment):
  12299. ps = [x for (x,t) in params]
  12300. env[name] = Function(name, ps, bod, env)
  12301. return self.interp_stmts(ss[1:], env)
  12302. case _:
  12303. return super().interp_stmts(ss, env)
  12304. def interp(self, p):
  12305. match p:
  12306. case Module(ss):
  12307. env = {}
  12308. self.interp_stmts(ss, env)
  12309. if 'main' in env.keys():
  12310. self.apply_fun(env['main'], [], None)
  12311. case _:
  12312. raise Exception('interp: unexpected ' + repr(p))
  12313. \end{lstlisting}
  12314. \fi}
  12315. \caption{Interpreter for the \LangFun{} language.}
  12316. \label{fig:interp-Rfun}
  12317. \end{figure}
  12318. %\margincomment{TODO: explain type checker}
  12319. The type checker for \LangFun{} is in
  12320. Figure~\ref{fig:type-check-Rfun}. (We omit the code that parses
  12321. function parameters into the simpler abstract syntax.) Similar to the
  12322. interpreter, the case for the
  12323. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12324. %
  12325. AST is responsible for setting up the mutual recursion between the
  12326. top-level function definitions. We begin by create a mapping
  12327. \code{env} from every function name to its type. We then type check
  12328. the program using this mapping.
  12329. %
  12330. In the case for function \racket{application}\python{call}, we match
  12331. the type of the function expression to a function type and check that
  12332. the types of the argument expressions are equal to the function's
  12333. parameter types. The type of the \racket{application}\python{call} as
  12334. a whole is the return type from the function type.
  12335. \begin{figure}[tp]
  12336. {\if\edition\racketEd
  12337. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12338. (define type-check-Rfun_class
  12339. (class type-check-Lvec_class
  12340. (super-new)
  12341. (inherit check-type-equal?)
  12342. (define/public (type-check-apply env e es)
  12343. (define-values (e^ ty) ((type-check-exp env) e))
  12344. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12345. ((type-check-exp env) e)))
  12346. (match ty
  12347. [`(,ty^* ... -> ,rt)
  12348. (for ([arg-ty ty*] [param-ty ty^*])
  12349. (check-type-equal? arg-ty param-ty (Apply e es)))
  12350. (values e^ e* rt)]))
  12351. (define/override (type-check-exp env)
  12352. (lambda (e)
  12353. (match e
  12354. [(FunRef f n)
  12355. (values (FunRef f n) (dict-ref env f))]
  12356. [(Apply e es)
  12357. (define-values (e^ es^ rt) (type-check-apply env e es))
  12358. (values (Apply e^ es^) rt)]
  12359. [(Call e es)
  12360. (define-values (e^ es^ rt) (type-check-apply env e es))
  12361. (values (Call e^ es^) rt)]
  12362. [else ((super type-check-exp env) e)])))
  12363. (define/public (type-check-def env)
  12364. (lambda (e)
  12365. (match e
  12366. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12367. (define new-env (append (map cons xs ps) env))
  12368. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12369. (check-type-equal? ty^ rt body)
  12370. (Def f p:t* rt info body^)])))
  12371. (define/public (fun-def-type d)
  12372. (match d
  12373. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12374. (define/override (type-check-program e)
  12375. (match e
  12376. [(ProgramDefsExp info ds body)
  12377. (define env (for/list ([d ds])
  12378. (cons (Def-name d) (fun-def-type d))))
  12379. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12380. (define-values (body^ ty) ((type-check-exp env) body))
  12381. (check-type-equal? ty 'Integer body)
  12382. (ProgramDefsExp info ds^ body^)]))))
  12383. (define (type-check-Rfun p)
  12384. (send (new type-check-Rfun_class) type-check-program p))
  12385. \end{lstlisting}
  12386. \fi}
  12387. {\if\edition\pythonEd
  12388. \begin{lstlisting}
  12389. class TypeCheckLfun(TypeCheckLtup):
  12390. def type_check_exp(self, e, env):
  12391. match e:
  12392. case Call(Name('input_int'), []):
  12393. return super().type_check_exp(e, env)
  12394. case Call(func, args):
  12395. func_t = self.type_check_exp(func, env)
  12396. args_t = [self.type_check_exp(arg, env) for arg in args]
  12397. match func_t:
  12398. case FunctionType(params_t, return_t):
  12399. for (arg_t, param_t) in zip(args_t, params_t):
  12400. check_type_equal(param_t, arg_t, e)
  12401. return return_t
  12402. case _:
  12403. raise Exception('type_check_exp: in call, unexpected ' +
  12404. repr(func_t))
  12405. case _:
  12406. return super().type_check_exp(e, env)
  12407. def type_check_stmts(self, ss, env):
  12408. if len(ss) == 0:
  12409. return
  12410. match ss[0]:
  12411. case FunctionDef(name, params, body, dl, returns, comment):
  12412. new_env = env.copy().update(params)
  12413. rt = self.type_check_stmts(body, new_env)
  12414. check_type_equal(returns, rt, ss[0])
  12415. return self.type_check_stmts(ss[1:], env)
  12416. case Return(value):
  12417. return self.type_check_exp(value, env)
  12418. case _:
  12419. return super().type_check_stmts(ss, env)
  12420. def type_check(self, p):
  12421. match p:
  12422. case Module(body):
  12423. env = {}
  12424. for s in body:
  12425. match s:
  12426. case FunctionDef(name, params, bod, dl, returns, comment):
  12427. if name in env:
  12428. raise Exception('type_check: function ' +
  12429. repr(name) + ' defined twice')
  12430. params_t = [t for (x,t) in params]
  12431. env[name] = FunctionType(params_t, returns)
  12432. self.type_check_stmts(body, env)
  12433. case _:
  12434. raise Exception('type_check: unexpected ' + repr(p))
  12435. \end{lstlisting}
  12436. \fi}
  12437. \caption{Type checker for the \LangFun{} language.}
  12438. \label{fig:type-check-Rfun}
  12439. \end{figure}
  12440. \clearpage
  12441. \section{Functions in x86}
  12442. \label{sec:fun-x86}
  12443. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12444. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12445. %% \margincomment{\tiny Talk about the return address on the
  12446. %% stack and what callq and retq does.\\ --Jeremy }
  12447. The x86 architecture provides a few features to support the
  12448. implementation of functions. We have already seen that there are
  12449. labels in x86 so that one can refer to the location of an instruction, as is
  12450. needed for jump instructions. Labels can also be used to mark the
  12451. beginning of the instructions for a function. Going further, we can
  12452. obtain the address of a label by using the \key{leaq} instruction and
  12453. PC-relative addressing. For example, the following puts the
  12454. address of the \code{inc} label into the \code{rbx} register.
  12455. \begin{lstlisting}
  12456. leaq inc(%rip), %rbx
  12457. \end{lstlisting}
  12458. The instruction pointer register \key{rip} (aka. the program counter
  12459. \index{subject}{program counter}) always points to the next
  12460. instruction to be executed. When combined with a label, as in
  12461. \code{inc(\%rip)}, the assembler computes the distance $d$ between the
  12462. address of \code{inc} and where the \code{rip} would be at that moment
  12463. and then changes the \code{inc(\%rip)} argument to \code{$d$(\%rip)},
  12464. which at runtime will compute the address of \code{inc}.
  12465. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12466. to functions whose locations were given by a label, such as
  12467. \code{read\_int}. To support function calls in this chapter we instead
  12468. will be jumping to functions whose location are given by an address in
  12469. a register, that is, we need to make an \emph{indirect function
  12470. call}. The x86 syntax for this is a \code{callq} instruction but with
  12471. an asterisk before the register name.\index{subject}{indirect function
  12472. call}
  12473. \begin{lstlisting}
  12474. callq *%rbx
  12475. \end{lstlisting}
  12476. \subsection{Calling Conventions}
  12477. \index{subject}{calling conventions}
  12478. The \code{callq} instruction provides partial support for implementing
  12479. functions: it pushes the return address on the stack and it jumps to
  12480. the target. However, \code{callq} does not handle
  12481. \begin{enumerate}
  12482. \item parameter passing,
  12483. \item pushing frames on the procedure call stack and popping them off,
  12484. or
  12485. \item determining how registers are shared by different functions.
  12486. \end{enumerate}
  12487. Regarding (1) parameter passing, recall that the x86-64 calling convention
  12488. for Unix-based system uses the following six
  12489. registers to pass arguments to a function, in this order.
  12490. \begin{lstlisting}
  12491. rdi rsi rdx rcx r8 r9
  12492. \end{lstlisting}
  12493. If there are
  12494. more than six arguments, then the calling convention mandates to use space on the
  12495. frame of the caller for the rest of the arguments. However, to ease
  12496. the implementation of efficient tail calls
  12497. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12498. arguments.
  12499. %
  12500. Also recall that the register \code{rax} is for the return value of
  12501. the function.
  12502. \index{subject}{prelude}\index{subject}{conclusion}
  12503. Regarding (2) frames \index{subject}{frame} and the procedure call
  12504. stack, \index{subject}{procedure call stack} recall from
  12505. Section~\ref{sec:x86} that the stack grows down and each function call
  12506. uses a chunk of space on the stack called a frame. The caller sets the
  12507. stack pointer, register \code{rsp}, to the last data item in its
  12508. frame. The callee must not change anything in the caller's frame, that
  12509. is, anything that is at or above the stack pointer. The callee is free
  12510. to use locations that are below the stack pointer.
  12511. Recall that we are storing variables of tuple type on the root stack.
  12512. So the prelude needs to move the root stack pointer \code{r15} up
  12513. according to the number of variables of tuple type and
  12514. the conclusion needs to move the root stack pointer back down. Also,
  12515. the prelude must initialize to \code{0} this frame's slots in the root
  12516. stack to signal to the garbage collector that those slots do not yet
  12517. contain a pointer to a vector. Otherwise the garbage collector will
  12518. interpret the garbage bits in those slots as memory addresses and try
  12519. to traverse them, causing serious mayhem!
  12520. Regarding (3) the sharing of registers between different functions,
  12521. recall from Section~\ref{sec:calling-conventions} that the registers
  12522. are divided into two groups, the caller-saved registers and the
  12523. callee-saved registers. The caller should assume that all the
  12524. caller-saved registers get overwritten with arbitrary values by the
  12525. callee. For that reason we recommend in
  12526. Section~\ref{sec:calling-conventions} that variables that are live
  12527. during a function call should not be assigned to caller-saved
  12528. registers.
  12529. On the flip side, if the callee wants to use a callee-saved register,
  12530. the callee must save the contents of those registers on their stack
  12531. frame and then put them back prior to returning to the caller. For
  12532. that reason we recommend in Section~\ref{sec:calling-conventions} that if
  12533. the register allocator assigns a variable to a callee-saved register,
  12534. then the prelude of the \code{main} function must save that register
  12535. to the stack and the conclusion of \code{main} must restore it. This
  12536. recommendation now generalizes to all functions.
  12537. Recall that the base pointer, register \code{rbp}, is used as a
  12538. point-of-reference within a frame, so that each local variable can be
  12539. accessed at a fixed offset from the base pointer
  12540. (Section~\ref{sec:x86}).
  12541. %
  12542. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12543. and callee frames.
  12544. \begin{figure}[tbp]
  12545. \centering
  12546. \begin{tabular}{r|r|l|l} \hline
  12547. Caller View & Callee View & Contents & Frame \\ \hline
  12548. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12549. 0(\key{\%rbp}) & & old \key{rbp} \\
  12550. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12551. \ldots & & \ldots \\
  12552. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12553. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12554. \ldots & & \ldots \\
  12555. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12556. %% & & \\
  12557. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12558. %% & \ldots & \ldots \\
  12559. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12560. \hline
  12561. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12562. & 0(\key{\%rbp}) & old \key{rbp} \\
  12563. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12564. & \ldots & \ldots \\
  12565. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12566. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12567. & \ldots & \ldots \\
  12568. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12569. \end{tabular}
  12570. \caption{Memory layout of caller and callee frames.}
  12571. \label{fig:call-frames}
  12572. \end{figure}
  12573. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12574. %% local variables and for storing the values of callee-saved registers
  12575. %% (we shall refer to all of these collectively as ``locals''), and that
  12576. %% at the beginning of a function we move the stack pointer \code{rsp}
  12577. %% down to make room for them.
  12578. %% We recommend storing the local variables
  12579. %% first and then the callee-saved registers, so that the local variables
  12580. %% can be accessed using \code{rbp} the same as before the addition of
  12581. %% functions.
  12582. %% To make additional room for passing arguments, we shall
  12583. %% move the stack pointer even further down. We count how many stack
  12584. %% arguments are needed for each function call that occurs inside the
  12585. %% body of the function and find their maximum. Adding this number to the
  12586. %% number of locals gives us how much the \code{rsp} should be moved at
  12587. %% the beginning of the function. In preparation for a function call, we
  12588. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12589. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12590. %% so on.
  12591. %% Upon calling the function, the stack arguments are retrieved by the
  12592. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12593. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12594. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12595. %% the layout of the caller and callee frames. Notice how important it is
  12596. %% that we correctly compute the maximum number of arguments needed for
  12597. %% function calls; if that number is too small then the arguments and
  12598. %% local variables will smash into each other!
  12599. \subsection{Efficient Tail Calls}
  12600. \label{sec:tail-call}
  12601. In general, the amount of stack space used by a program is determined
  12602. by the longest chain of nested function calls. That is, if function
  12603. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, $f_n$, then the amount
  12604. of stack space is linear in $n$. The depth $n$ can grow quite large
  12605. if functions are (mutually) recursive. However, in
  12606. some cases we can arrange to use only a constant amount of space for a
  12607. long chain of nested function calls.
  12608. A \emph{tail call}\index{subject}{tail call} is a function call that
  12609. happens as the last action in a function body.
  12610. For example, in the following
  12611. program, the recursive call to \code{tail\_sum} is a tail call.
  12612. \begin{center}
  12613. {\if\edition\racketEd
  12614. \begin{lstlisting}
  12615. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12616. (if (eq? n 0)
  12617. r
  12618. (tail_sum (- n 1) (+ n r))))
  12619. (+ (tail_sum 3 0) 36)
  12620. \end{lstlisting}
  12621. \fi}
  12622. {\if\edition\pythonEd
  12623. \begin{lstlisting}
  12624. def tail_sum(n : int, r : int) -> int:
  12625. if n == 0:
  12626. return r
  12627. else:
  12628. return tail_sum(n - 1, n + r)
  12629. print( tail_sum(3, 0) + 36)
  12630. \end{lstlisting}
  12631. \fi}
  12632. \end{center}
  12633. At a tail call, the frame of the caller is no longer needed, so we can
  12634. pop the caller's frame before making the tail call. With this
  12635. approach, a recursive function that only makes tail calls ends up
  12636. using a constant amount of stack space. Functional languages like
  12637. Racket rely heavily on recursive functions, so the definition of
  12638. Racket \emph{requires} that all tail calls be optimized in this way.
  12639. \index{subject}{frame}
  12640. Some care is needed with regards to argument passing in tail calls.
  12641. As mentioned above, for arguments beyond the sixth, the convention is
  12642. to use space in the caller's frame for passing arguments. But for a
  12643. tail call we pop the caller's frame and can no longer use it. An
  12644. alternative is to use space in the callee's frame for passing
  12645. arguments. However, this option is also problematic because the caller
  12646. and callee's frames overlap in memory. As we begin to copy the
  12647. arguments from their sources in the caller's frame, the target
  12648. locations in the callee's frame might collide with the sources for
  12649. later arguments! We solve this problem by using the heap instead of
  12650. the stack for passing more than six arguments, which we describe in
  12651. the Section~\ref{sec:limit-functions-r4}.
  12652. As mentioned above, for a tail call we pop the caller's frame prior to
  12653. making the tail call. The instructions for popping a frame are the
  12654. instructions that we usually place in the conclusion of a
  12655. function. Thus, we also need to place such code immediately before
  12656. each tail call. These instructions include restoring the callee-saved
  12657. registers, so it is fortunate that the argument passing registers are
  12658. all caller-saved registers!
  12659. One last note regarding which instruction to use to make the tail
  12660. call. When the callee is finished, it should not return to the current
  12661. function, but it should return to the function that called the current
  12662. one. Thus, the return address that is already on the stack is the
  12663. right one, and we should not use \key{callq} to make the tail call, as
  12664. that would unnecessarily overwrite the return address. Instead we can
  12665. simply use the \key{jmp} instruction. Like the indirect function call,
  12666. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12667. register prefixed with an asterisk. We recommend using \code{rax} to
  12668. hold the jump target because the preceding conclusion can overwrite
  12669. just about everything else.
  12670. \begin{lstlisting}
  12671. jmp *%rax
  12672. \end{lstlisting}
  12673. \section{Shrink \LangFun{}}
  12674. \label{sec:shrink-r4}
  12675. The \code{shrink} pass performs a minor modification to ease the
  12676. later passes. This pass introduces an explicit \code{main} function
  12677. that gobbles up all the top-level statements of the module.
  12678. %
  12679. \racket{It also changes the top \code{ProgramDefsExp} form to
  12680. \code{ProgramDefs}.}
  12681. {\if\edition\racketEd
  12682. \begin{lstlisting}
  12683. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12684. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12685. \end{lstlisting}
  12686. where $\itm{mainDef}$ is
  12687. \begin{lstlisting}
  12688. (Def 'main '() 'Integer '() |$\Exp'$|)
  12689. \end{lstlisting}
  12690. \fi}
  12691. {\if\edition\pythonEd
  12692. \begin{lstlisting}
  12693. Module(|$\Def\ldots\Stmt\ldots$|)
  12694. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12695. \end{lstlisting}
  12696. where $\itm{mainDef}$ is
  12697. \begin{lstlisting}
  12698. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  12699. \end{lstlisting}
  12700. \fi}
  12701. \section{Reveal Functions and the \LangFunRef{} language}
  12702. \label{sec:reveal-functions-r4}
  12703. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12704. in that it conflates the use of function names and local
  12705. variables. This is a problem because we need to compile the use of a
  12706. function name differently than the use of a local variable; we need to
  12707. use \code{leaq} to convert the function name (a label in x86) to an
  12708. address in a register. Thus, we create a new pass that changes
  12709. function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where $n$ is the
  12710. arity of the function.\python{\footnote{The arity is not needed in this
  12711. chapter but is used in Chapter~\ref{ch:Ldyn}.}} This pass is
  12712. named \code{reveal\_functions} and the output language, \LangFunRef{},
  12713. is defined in Figure~\ref{fig:f1-syntax}.
  12714. %% The concrete syntax for a
  12715. %% function reference is $\CFUNREF{f}$.
  12716. \begin{figure}[tp]
  12717. \centering
  12718. \fbox{
  12719. \begin{minipage}{0.96\textwidth}
  12720. {\if\edition\racketEd
  12721. \[
  12722. \begin{array}{lcl}
  12723. \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  12724. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12725. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12726. \end{array}
  12727. \]
  12728. \fi}
  12729. {\if\edition\pythonEd
  12730. \[
  12731. \begin{array}{lcl}
  12732. \Exp &::=& \FUNREF{\Var}{\Int}\\
  12733. \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12734. \end{array}
  12735. \]
  12736. \fi}
  12737. \end{minipage}
  12738. }
  12739. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12740. (Figure~\ref{fig:Rfun-syntax}).}
  12741. \label{fig:f1-syntax}
  12742. \end{figure}
  12743. %% Distinguishing between calls in tail position and non-tail position
  12744. %% requires the pass to have some notion of context. We recommend using
  12745. %% two mutually recursive functions, one for processing expressions in
  12746. %% tail position and another for the rest.
  12747. \racket{Placing this pass after \code{uniquify} will make sure that
  12748. there are no local variables and functions that share the same
  12749. name.}
  12750. %
  12751. The \code{reveal\_functions} pass should come before the
  12752. \code{remove\_complex\_operands} pass because function references
  12753. should be categorized as complex expressions.
  12754. \section{Limit Functions}
  12755. \label{sec:limit-functions-r4}
  12756. Recall that we wish to limit the number of function parameters to six
  12757. so that we do not need to use the stack for argument passing, which
  12758. makes it easier to implement efficient tail calls. However, because
  12759. the input language \LangFun{} supports arbitrary numbers of function
  12760. arguments, we have some work to do!
  12761. This pass transforms functions and function calls that involve more
  12762. than six arguments to pass the first five arguments as usual, but it
  12763. packs the rest of the arguments into a vector and passes it as the
  12764. sixth argument.
  12765. Each function definition with seven or more parameters is transformed as
  12766. follows.
  12767. {\if\edition\racketEd
  12768. \begin{lstlisting}
  12769. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12770. |$\Rightarrow$|
  12771. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12772. \end{lstlisting}
  12773. \fi}
  12774. {\if\edition\pythonEd
  12775. \begin{lstlisting}
  12776. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12777. |$\Rightarrow$|
  12778. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12779. |$T_r$|, None, |$\itm{body}'$|, None)
  12780. \end{lstlisting}
  12781. \fi}
  12782. %
  12783. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12784. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12785. the $k$th element of the tuple, where $k = i - 6$.
  12786. %
  12787. {\if\edition\racketEd
  12788. \begin{lstlisting}
  12789. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12790. \end{lstlisting}
  12791. \fi}
  12792. {\if\edition\pythonEd
  12793. \begin{lstlisting}
  12794. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  12795. \end{lstlisting}
  12796. \fi}
  12797. For function calls with too many arguments, the \code{limit\_functions}
  12798. pass transforms them in the following way.
  12799. \begin{tabular}{lll}
  12800. \begin{minipage}{0.3\textwidth}
  12801. {\if\edition\racketEd
  12802. \begin{lstlisting}
  12803. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12804. \end{lstlisting}
  12805. \fi}
  12806. {\if\edition\pythonEd
  12807. \begin{lstlisting}
  12808. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12809. \end{lstlisting}
  12810. \fi}
  12811. \end{minipage}
  12812. &
  12813. $\Rightarrow$
  12814. &
  12815. \begin{minipage}{0.5\textwidth}
  12816. {\if\edition\racketEd
  12817. \begin{lstlisting}
  12818. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12819. \end{lstlisting}
  12820. \fi}
  12821. {\if\edition\pythonEd
  12822. \begin{lstlisting}
  12823. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12824. \end{lstlisting}
  12825. \fi}
  12826. \end{minipage}
  12827. \end{tabular}
  12828. \section{Remove Complex Operands}
  12829. \label{sec:rco-r4}
  12830. The primary decisions to make for this pass is whether to classify
  12831. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12832. atomic or complex expressions. Recall that a simple expression will
  12833. eventually end up as just an immediate argument of an x86
  12834. instruction. Function application will be translated to a sequence of
  12835. instructions, so \racket{\code{Apply}}\python{\code{Call}} must be
  12836. classified as complex expression. On the other hand, the arguments of
  12837. \racket{\code{Apply}}\python{\code{Call}} should be atomic expressions.
  12838. %
  12839. Regarding \code{FunRef}, as discussed above, the function label needs
  12840. to be converted to an address using the \code{leaq} instruction. Thus,
  12841. even though \code{FunRef} seems rather simple, it needs to be
  12842. classified as a complex expression so that we generate an assignment
  12843. statement with a left-hand side that can serve as the target of the
  12844. \code{leaq}.
  12845. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12846. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12847. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12848. %
  12849. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12850. % TODO: Return?
  12851. %% Figure~\ref{fig:Rfun-anf-syntax} defines the output language
  12852. %% \LangFunANF{} of this pass.
  12853. %% \begin{figure}[tp]
  12854. %% \centering
  12855. %% \fbox{
  12856. %% \begin{minipage}{0.96\textwidth}
  12857. %% \small
  12858. %% \[
  12859. %% \begin{array}{rcl}
  12860. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12861. %% \MID \VOID{} } \\
  12862. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12863. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12864. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12865. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12866. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12867. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12868. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12869. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12870. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12871. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12872. %% \end{array}
  12873. %% \]
  12874. %% \end{minipage}
  12875. %% }
  12876. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12877. %% \label{fig:Rfun-anf-syntax}
  12878. %% \end{figure}
  12879. \section{Explicate Control and the \LangCFun{} language}
  12880. \label{sec:explicate-control-r4}
  12881. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12882. output of \code{explicate\_control}.
  12883. %
  12884. \racket{(The concrete syntax is given in
  12885. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  12886. %
  12887. The auxiliary functions for assignment\racket{and tail contexts} should
  12888. be updated with cases for
  12889. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  12890. function for predicate context should be updated for
  12891. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  12892. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  12893. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  12894. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  12895. auxiliary function for processing function definitions. This code is
  12896. similar to the case for \code{Program} in \LangVec{}. The top-level
  12897. \code{explicate\_control} function that handles the \code{ProgramDefs}
  12898. form of \LangFun{} can then apply this new function to all the
  12899. function definitions.
  12900. {\if\edition\pythonEd
  12901. The translation of \code{Return} statements requires a new auxiliary
  12902. function to handle expressions in tail context, called
  12903. \code{explicate\_tail}. The function should take an expression and the
  12904. dictionary of basic blocks and produce a list of statements in the
  12905. \LangCFun{} language. The \code{explicate\_tail} function should
  12906. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  12907. and a default case for other kinds of expressions. The default case
  12908. should produce a \code{Return} statement. The case for \code{Call}
  12909. should change it into \code{TailCall}. The other cases should
  12910. recursively process their subexpressions and statements, choosing the
  12911. appropriate explicate functions for the various contexts.
  12912. \fi}
  12913. \newcommand{\CfunASTRacket}{
  12914. \begin{array}{lcl}
  12915. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12916. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  12917. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12918. \end{array}
  12919. }
  12920. \newcommand{\CfunASTPython}{
  12921. \begin{array}{lcl}
  12922. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  12923. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  12924. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  12925. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  12926. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  12927. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  12928. \end{array}
  12929. }
  12930. \begin{figure}[tp]
  12931. \fbox{
  12932. \begin{minipage}{0.96\textwidth}
  12933. \small
  12934. {\if\edition\racketEd
  12935. \[
  12936. \begin{array}{l}
  12937. \gray{\CvarASTRacket} \\ \hline
  12938. \gray{\CifASTRacket} \\ \hline
  12939. \gray{\CloopASTRacket} \\ \hline
  12940. \gray{\CtupASTRacket} \\ \hline
  12941. \CfunASTRacket \\
  12942. \begin{array}{lcl}
  12943. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12944. \end{array}
  12945. \end{array}
  12946. \]
  12947. \fi}
  12948. {\if\edition\pythonEd
  12949. \[
  12950. \begin{array}{l}
  12951. \gray{\CifASTPython} \\ \hline
  12952. \gray{\CtupASTPython} \\ \hline
  12953. \CfunASTPython \\
  12954. \begin{array}{lcl}
  12955. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12956. \end{array}
  12957. \end{array}
  12958. \]
  12959. \fi}
  12960. \end{minipage}
  12961. }
  12962. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12963. \label{fig:c3-syntax}
  12964. \end{figure}
  12965. \section{Select Instructions and the \LangXIndCall{} Language}
  12966. \label{sec:select-r4}
  12967. \index{subject}{instruction selection}
  12968. The output of select instructions is a program in the \LangXIndCall{}
  12969. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12970. \index{subject}{x86}
  12971. \begin{figure}[tp]
  12972. \fbox{
  12973. \begin{minipage}{0.96\textwidth}
  12974. \small
  12975. \[
  12976. \begin{array}{lcl}
  12977. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  12978. \itm{cc} & ::= & \gray{ \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12979. \Instr &::=& \ldots
  12980. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12981. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12982. \Block &::= & \itm{label}\key{:}\, \Instr^{*} \\
  12983. \Def &::= & \key{.globl}\,\itm{label}\; \Block^{*} \\
  12984. \LangXIndCallM{} &::= & \Def\ldots
  12985. \end{array}
  12986. \]
  12987. \end{minipage}
  12988. }
  12989. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12990. \label{fig:x86-3-concrete}
  12991. \end{figure}
  12992. \begin{figure}[tp]
  12993. \fbox{
  12994. \begin{minipage}{0.96\textwidth}
  12995. \small
  12996. {\if\edition\racketEd
  12997. \[
  12998. \begin{array}{lcl}
  12999. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13000. \MID \BYTEREG{\Reg} } \\
  13001. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}}{\Int} \\
  13002. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13003. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13004. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13005. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13006. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  13007. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13008. \end{array}
  13009. \]
  13010. \fi}
  13011. {\if\edition\pythonEd
  13012. \[
  13013. \begin{array}{lcl}
  13014. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13015. \MID \BYTEREG{\Reg} } \\
  13016. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}}{\Int} \\
  13017. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13018. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13019. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13020. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13021. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13022. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13023. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13024. \end{array}
  13025. \]
  13026. \fi}
  13027. \end{minipage}
  13028. }
  13029. \caption{The abstract syntax of \LangXIndCall{} (extends
  13030. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  13031. \label{fig:x86-3}
  13032. \end{figure}
  13033. An assignment of a function reference to a variable becomes a
  13034. load-effective-address instruction as follows, where $\itm{lhs}'$
  13035. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  13036. to \Arg{} in \LangXIndCallVar{}. \\
  13037. \begin{tabular}{lcl}
  13038. \begin{minipage}{0.35\textwidth}
  13039. {\if\edition\racketEd
  13040. \begin{lstlisting}
  13041. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13042. \end{lstlisting}
  13043. \fi}
  13044. {\if\edition\pythonEd
  13045. \begin{lstlisting}
  13046. |$\itm{lhs}$| = FunRef(|$f$|, |$n$|);
  13047. \end{lstlisting}
  13048. \fi}
  13049. \end{minipage}
  13050. &
  13051. $\Rightarrow$\qquad\qquad
  13052. &
  13053. \begin{minipage}{0.3\textwidth}
  13054. {\if\edition\racketEd
  13055. \begin{lstlisting}
  13056. leaq (fun-ref |$f$| |$n$|), |$\itm{lhs}'$|
  13057. \end{lstlisting}
  13058. \fi}
  13059. {\if\edition\pythonEd
  13060. \begin{lstlisting}
  13061. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13062. \end{lstlisting}
  13063. \fi}
  13064. \end{minipage}
  13065. \end{tabular} \\
  13066. Regarding function definitions, we need to remove the parameters and
  13067. instead perform parameter passing using the conventions discussed in
  13068. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13069. registers. We recommend turning the parameters into local variables
  13070. and generating instructions at the beginning of the function to move
  13071. from the argument passing registers to these local variables.
  13072. {\if\edition\racketEd
  13073. \begin{lstlisting}
  13074. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13075. |$\Rightarrow$|
  13076. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13077. \end{lstlisting}
  13078. \fi}
  13079. {\if\edition\pythonEd
  13080. \begin{lstlisting}
  13081. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13082. |$\Rightarrow$|
  13083. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13084. \end{lstlisting}
  13085. \fi}
  13086. The basic blocks $B'$ are the same as $B$ except that the
  13087. \code{start} block is modified to add the instructions for moving from
  13088. the argument registers to the parameter variables. So the \code{start}
  13089. block of $B$ shown on the left is changed to the code on the right.
  13090. \begin{center}
  13091. \begin{minipage}{0.3\textwidth}
  13092. \begin{lstlisting}
  13093. start:
  13094. |$\itm{instr}_1$|
  13095. |$\cdots$|
  13096. |$\itm{instr}_n$|
  13097. \end{lstlisting}
  13098. \end{minipage}
  13099. $\Rightarrow$
  13100. \begin{minipage}{0.3\textwidth}
  13101. \begin{lstlisting}
  13102. start:
  13103. movq %rdi, |$x_1$|
  13104. |$\cdots$|
  13105. |$\itm{instr}_1$|
  13106. |$\cdots$|
  13107. |$\itm{instr}_n$|
  13108. \end{lstlisting}
  13109. \end{minipage}
  13110. \end{center}
  13111. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13112. parameters the function expects, but the parameters are no longer in
  13113. the syntax of function definitions. Instead, add an entry to
  13114. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13115. to construct $\itm{info}'$.}
  13116. By changing the parameters to local variables, we are giving the
  13117. register allocator control over which registers or stack locations to
  13118. use for them. If you implemented the move-biasing challenge
  13119. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13120. assign the parameter variables to the corresponding argument register,
  13121. in which case the \code{patch\_instructions} pass will remove the
  13122. \code{movq} instruction. This happens in the example translation in
  13123. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13124. the \code{add} function.
  13125. %
  13126. Also, note that the register allocator will perform liveness analysis
  13127. on this sequence of move instructions and build the interference
  13128. graph. So, for example, $x_1$ will be marked as interfering with
  13129. \code{rsi} and that will prevent the assignment of $x_1$ to
  13130. \code{rsi}, which is good, because that would overwrite the argument
  13131. that needs to move into $x_2$.
  13132. Next, consider the compilation of function calls. In the mirror image
  13133. of handling the parameters of function definitions, the arguments need
  13134. to be moved to the argument passing registers. The function call
  13135. itself is performed with an indirect function call. The return value
  13136. from the function is stored in \code{rax}, so it needs to be moved
  13137. into the \itm{lhs}.
  13138. \begin{lstlisting}
  13139. |\itm{lhs}| = |$\CALL{\itm{fun}}{\itm{arg}_1\ldots}$|
  13140. |$\Rightarrow$|
  13141. movq |$\itm{arg}_1$|, %rdi
  13142. movq |$\itm{arg}_2$|, %rsi
  13143. |$\vdots$|
  13144. callq *|\itm{fun}|
  13145. movq %rax, |\itm{lhs}|
  13146. \end{lstlisting}
  13147. The \code{IndirectCallq} AST node includes an integer for the arity of
  13148. the function, i.e., the number of parameters. That information is
  13149. useful in the \code{uncover\_live} pass for determining which
  13150. argument-passing registers are potentially read during the call.
  13151. For tail calls, the parameter passing is the same as non-tail calls:
  13152. generate instructions to move the arguments into the argument
  13153. passing registers. After that we need to pop the frame from the
  13154. procedure call stack. However, we do not yet know how big the frame
  13155. is; that gets determined during register allocation. So instead of
  13156. generating those instructions here, we invent a new instruction that
  13157. means ``pop the frame and then do an indirect jump'', which we name
  13158. \code{TailJmp}. The abstract syntax for this instruction includes an
  13159. argument that specifies where to jump and an integer that represents
  13160. the arity of the function being called.
  13161. Recall that we use the label \code{start} for the initial block of a
  13162. program, and in Section~\ref{sec:select-Lvar} we recommend labeling
  13163. the conclusion of the program with \code{conclusion}, so that
  13164. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13165. by a jump to \code{conclusion}. With the addition of function
  13166. definitions, there is a start block and conclusion for each function,
  13167. but their labels need to be unique. We recommend prepending the
  13168. function's name to \code{start} and \code{conclusion}, respectively,
  13169. to obtain unique labels.
  13170. \section{Register Allocation}
  13171. \label{sec:register-allocation-r4}
  13172. \subsection{Liveness Analysis}
  13173. \label{sec:liveness-analysis-r4}
  13174. \index{subject}{liveness analysis}
  13175. %% The rest of the passes need only minor modifications to handle the new
  13176. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13177. %% \code{leaq}.
  13178. The \code{IndirectCallq} instruction should be treated like
  13179. \code{Callq} regarding its written locations $W$, in that they should
  13180. include all the caller-saved registers. Recall that the reason for
  13181. that is to force variables that are live across a function call to be assigned to callee-saved
  13182. registers or to be spilled to the stack.
  13183. Regarding the set of read locations $R$, the arity field of
  13184. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13185. argument-passing registers should be considered as read by those
  13186. instructions. Also, the target field of \code{TailJmp} and
  13187. \code{IndirectCallq} should be included in the set of read locations
  13188. $R$.
  13189. \subsection{Build Interference Graph}
  13190. \label{sec:build-interference-r4}
  13191. With the addition of function definitions, we compute a separate interference
  13192. graph for each function (not just one for the whole program).
  13193. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13194. spill vector-typed variables that are live during a call to
  13195. \code{collect}, the garbage collector. With the addition of functions to our language, we
  13196. need to revisit this issue. Functions that perform allocation contain
  13197. calls to the collector. Thus, we should
  13198. not only spill a vector-typed variable when it is live during a call
  13199. to \code{collect}, but we should spill the variable if it is live
  13200. during call to a user-defined function. Thus, in the \code{build\_interference} pass,
  13201. we recommend adding interference edges between call-live vector-typed
  13202. variables and the callee-saved registers (in addition to the usual
  13203. addition of edges between call-live variables and the caller-saved
  13204. registers).
  13205. \subsection{Allocate Registers}
  13206. The primary change to the \code{allocate\_registers} pass is adding an
  13207. auxiliary function for handling definitions (the \Def{} non-terminal
  13208. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13209. logic is the same as described in
  13210. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13211. allocation is performed many times, once for each function definition,
  13212. instead of just once for the whole program.
  13213. \section{Patch Instructions}
  13214. In \code{patch\_instructions}, you should deal with the x86
  13215. idiosyncrasy that the destination argument of \code{leaq} must be a
  13216. register. Additionally, you should ensure that the argument of
  13217. \code{TailJmp} is \itm{rax}, our reserved register---mostly to make
  13218. code generation more convenient, because we trample many registers
  13219. before the tail call (as explained in the next section).
  13220. \section{Prelude and Conclusion}
  13221. %% For the \code{print\_x86} pass, the cases for \code{FunRef} and
  13222. %% \code{IndirectCallq} are straightforward: output their concrete
  13223. %% syntax.
  13224. %% \begin{lstlisting}
  13225. %% (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  13226. %% (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  13227. %% \end{lstlisting}
  13228. Now that register allocation is complete, we can translate the
  13229. \code{TailJmp} into a sequence of instructions. A straightforward
  13230. translation of \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}.
  13231. However, before the jump we need to pop the current frame. This
  13232. sequence of instructions is the same as the code for the conclusion of
  13233. a function, except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  13234. Regarding function definitions, you need to generate a prelude
  13235. and conclusion for each one. This code is similar to the prelude and
  13236. conclusion generated for the \code{main} function in
  13237. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  13238. should carry out the following steps.
  13239. % TODO: .align the functions!
  13240. \begin{enumerate}
  13241. %% \item Start with \code{.global} and \code{.align} directives followed
  13242. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13243. %% example.)
  13244. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13245. pointer.
  13246. \item Push to the stack all of the callee-saved registers that were
  13247. used for register allocation.
  13248. \item Move the stack pointer \code{rsp} down by the size of the stack
  13249. frame for this function, which depends on the number of regular
  13250. spills. (Aligned to 16 bytes.)
  13251. \item Move the root stack pointer \code{r15} up by the size of the
  13252. root-stack frame for this function, which depends on the number of
  13253. spilled vectors. \label{root-stack-init}
  13254. \item Initialize to zero all new entries in the root-stack frame.
  13255. \item Jump to the start block.
  13256. \end{enumerate}
  13257. The prelude of the \code{main} function has one additional task: call
  13258. the \code{initialize} function to set up the garbage collector and
  13259. move the value of the global \code{rootstack\_begin} in
  13260. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13261. above, which depends on \code{r15}.
  13262. The conclusion of every function should do the following.
  13263. \begin{enumerate}
  13264. \item Move the stack pointer back up by the size of the stack frame
  13265. for this function.
  13266. \item Restore the callee-saved registers by popping them from the
  13267. stack.
  13268. \item Move the root stack pointer back down by the size of the
  13269. root-stack frame for this function.
  13270. \item Restore \code{rbp} by popping it from the stack.
  13271. \item Return to the caller with the \code{retq} instruction.
  13272. \end{enumerate}
  13273. \begin{exercise}\normalfont
  13274. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13275. Create 5 new programs that use functions, including examples that pass
  13276. functions and return functions from other functions, recursive
  13277. functions, functions that create vectors, and functions that make tail
  13278. calls. Test your compiler on these new programs and all of your
  13279. previously created test programs.
  13280. \end{exercise}
  13281. \begin{figure}[tbp]
  13282. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13283. \node (Rfun) at (0,2) {\large \LangFun{}};
  13284. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  13285. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  13286. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13287. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13288. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13289. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  13290. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13291. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13292. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13293. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13294. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13295. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13296. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13297. \path[->,bend left=15] (Rfun) edge [above] node
  13298. {\ttfamily\footnotesize shrink} (Rfun-1);
  13299. \path[->,bend left=15] (Rfun-1) edge [above] node
  13300. {\ttfamily\footnotesize uniquify} (Rfun-2);
  13301. \path[->,bend left=15] (Rfun-2) edge [above] node
  13302. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13303. \path[->,bend left=15] (F1-1) edge [right] node
  13304. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13305. \path[->,bend right=15] (F1-2) edge [above] node
  13306. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13307. \path[->,bend right=15] (F1-3) edge [above] node
  13308. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  13309. \path[->,bend left=15] (F1-4) edge [right] node
  13310. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13311. \path[->,bend right=15] (C3-2) edge [left] node
  13312. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13313. \path[->,bend left=15] (x86-2) edge [left] node
  13314. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13315. \path[->,bend right=15] (x86-2-1) edge [below] node
  13316. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13317. \path[->,bend right=15] (x86-2-2) edge [left] node
  13318. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13319. \path[->,bend left=15] (x86-3) edge [above] node
  13320. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13321. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  13322. \end{tikzpicture}
  13323. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13324. \label{fig:Rfun-passes}
  13325. \end{figure}
  13326. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  13327. compiling \LangFun{} to x86.
  13328. \section{An Example Translation}
  13329. \label{sec:functions-example}
  13330. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13331. function in \LangFun{} to x86. The figure also includes the results of the
  13332. \code{explicate\_control} and \code{select\_instructions} passes.
  13333. \begin{figure}[htbp]
  13334. \begin{tabular}{ll}
  13335. \begin{minipage}{0.4\textwidth}
  13336. % s3_2.rkt
  13337. {\if\edition\racketEd
  13338. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13339. (define (add [x : Integer] [y : Integer])
  13340. : Integer
  13341. (+ x y))
  13342. (add 40 2)
  13343. \end{lstlisting}
  13344. \fi}
  13345. {\if\edition\pythonEd
  13346. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13347. def add(x:int, y:int) -> int:
  13348. return x + y
  13349. print(add(40, 2))
  13350. \end{lstlisting}
  13351. \fi}
  13352. $\Downarrow$
  13353. {\if\edition\racketEd
  13354. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13355. (define (add86 [x87 : Integer]
  13356. [y88 : Integer]) : Integer
  13357. add86start:
  13358. return (+ x87 y88);
  13359. )
  13360. (define (main) : Integer ()
  13361. mainstart:
  13362. tmp89 = (fun-ref add86 2);
  13363. (tail-call tmp89 40 2)
  13364. )
  13365. \end{lstlisting}
  13366. \fi}
  13367. {\if\edition\pythonEd
  13368. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13369. def add(x:int, y:int) -> int:
  13370. addstart:
  13371. return x + y
  13372. def main() -> int:
  13373. mainstart:
  13374. fun.0 = add
  13375. tmp.1 = fun.0(40, 2)
  13376. print(tmp.1)
  13377. return 0
  13378. \end{lstlisting}
  13379. \fi}
  13380. \end{minipage}
  13381. &
  13382. $\Rightarrow$
  13383. \begin{minipage}{0.5\textwidth}
  13384. {\if\edition\racketEd
  13385. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13386. (define (add86) : Integer
  13387. add86start:
  13388. movq %rdi, x87
  13389. movq %rsi, y88
  13390. movq x87, %rax
  13391. addq y88, %rax
  13392. jmp inc1389conclusion
  13393. )
  13394. (define (main) : Integer
  13395. mainstart:
  13396. leaq (fun-ref add86 2), tmp89
  13397. movq $40, %rdi
  13398. movq $2, %rsi
  13399. tail-jmp tmp89
  13400. )
  13401. \end{lstlisting}
  13402. \fi}
  13403. {\if\edition\pythonEd
  13404. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13405. def add() -> int:
  13406. addstart:
  13407. movq %rdi, x
  13408. movq %rsi, y
  13409. movq x, %rax
  13410. addq y, %rax
  13411. jmp addconclusion
  13412. def main() -> int:
  13413. mainstart:
  13414. leaq add, fun.0
  13415. movq $40, %rdi
  13416. movq $2, %rsi
  13417. callq *fun.0
  13418. movq %rax, tmp.1
  13419. movq tmp.1, %rdi
  13420. callq print_int
  13421. movq $0, %rax
  13422. jmp mainconclusion
  13423. \end{lstlisting}
  13424. \fi}
  13425. $\Downarrow$
  13426. \end{minipage}
  13427. \end{tabular}
  13428. \begin{tabular}{ll}
  13429. \begin{minipage}{0.3\textwidth}
  13430. {\if\edition\racketEd
  13431. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13432. .globl add86
  13433. .align 16
  13434. add86:
  13435. pushq %rbp
  13436. movq %rsp, %rbp
  13437. jmp add86start
  13438. add86start:
  13439. movq %rdi, %rax
  13440. addq %rsi, %rax
  13441. jmp add86conclusion
  13442. add86conclusion:
  13443. popq %rbp
  13444. retq
  13445. \end{lstlisting}
  13446. \fi}
  13447. {\if\edition\pythonEd
  13448. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13449. .align 16
  13450. add:
  13451. pushq %rbp
  13452. movq %rsp, %rbp
  13453. subq $0, %rsp
  13454. jmp addstart
  13455. addstart:
  13456. movq %rdi, %rdx
  13457. movq %rsi, %rcx
  13458. movq %rdx, %rax
  13459. addq %rcx, %rax
  13460. jmp addconclusion
  13461. addconclusion:
  13462. subq $0, %r15
  13463. addq $0, %rsp
  13464. popq %rbp
  13465. retq
  13466. \end{lstlisting}
  13467. \fi}
  13468. \end{minipage}
  13469. &
  13470. \begin{minipage}{0.5\textwidth}
  13471. {\if\edition\racketEd
  13472. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13473. .globl main
  13474. .align 16
  13475. main:
  13476. pushq %rbp
  13477. movq %rsp, %rbp
  13478. movq $16384, %rdi
  13479. movq $16384, %rsi
  13480. callq initialize
  13481. movq rootstack_begin(%rip), %r15
  13482. jmp mainstart
  13483. mainstart:
  13484. leaq add86(%rip), %rcx
  13485. movq $40, %rdi
  13486. movq $2, %rsi
  13487. movq %rcx, %rax
  13488. popq %rbp
  13489. jmp *%rax
  13490. mainconclusion:
  13491. popq %rbp
  13492. retq
  13493. \end{lstlisting}
  13494. \fi}
  13495. {\if\edition\pythonEd
  13496. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13497. .globl main
  13498. .align 16
  13499. main:
  13500. pushq %rbp
  13501. movq %rsp, %rbp
  13502. subq $0, %rsp
  13503. movq $65536, %rdi
  13504. movq $65536, %rsi
  13505. callq initialize
  13506. movq rootstack_begin(%rip), %r15
  13507. jmp mainstart
  13508. mainstart:
  13509. leaq add(%rip), %rcx
  13510. movq $40, %rdi
  13511. movq $2, %rsi
  13512. callq *%rcx
  13513. movq %rax, %rcx
  13514. movq %rcx, %rdi
  13515. callq print_int
  13516. movq $0, %rax
  13517. jmp mainconclusion
  13518. mainconclusion:
  13519. subq $0, %r15
  13520. addq $0, %rsp
  13521. popq %rbp
  13522. retq
  13523. \end{lstlisting}
  13524. \fi}
  13525. \end{minipage}
  13526. \end{tabular}
  13527. \caption{Example compilation of a simple function to x86.}
  13528. \label{fig:add-fun}
  13529. \end{figure}
  13530. % Challenge idea: inlining! (simple version)
  13531. % Further Reading
  13532. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13533. \chapter{Lexically Scoped Functions}
  13534. \label{ch:Llambda}
  13535. \index{subject}{lambda}
  13536. \index{subject}{lexical scoping}
  13537. This chapter studies lexically scoped functions. Lexical scoping means
  13538. that a function's body may refer to variables whose binding site is
  13539. outside of the function, in an enclosing scope.
  13540. %
  13541. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13542. \LangLam{}, which extends \LangFun{} with lexically scoped functions
  13543. using the \key{lambda} form. The body of the \key{lambda} refers to
  13544. three variables: \code{x}, \code{y}, and \code{z}. The binding sites
  13545. for \code{x} and \code{y} are outside of the \key{lambda}. Variable
  13546. \code{y} is \racket{bound by the enclosing \key{let}}\python{a local
  13547. variable of function \code{f}} and \code{x} is a parameter of
  13548. function \code{f}. The \key{lambda} is returned from the function
  13549. \code{f}. The main expression of the program includes two calls to
  13550. \code{f} with different arguments for \code{x}, first \code{5} then
  13551. \code{3}. The functions returned from \code{f} are bound to variables
  13552. \code{g} and \code{h}. Even though these two functions were created by
  13553. the same \code{lambda}, they are really different functions because
  13554. they use different values for \code{x}. Applying \code{g} to \code{11}
  13555. produces \code{20} whereas applying \code{h} to \code{15} produces
  13556. \code{22}. The result of this program is \code{42}.
  13557. \begin{figure}[btp]
  13558. {\if\edition\racketEd
  13559. % lambda_test_21.rkt
  13560. \begin{lstlisting}
  13561. (define (f [x : Integer]) : (Integer -> Integer)
  13562. (let ([y 4])
  13563. (lambda: ([z : Integer]) : Integer
  13564. (+ x (+ y z)))))
  13565. (let ([g (f 5)])
  13566. (let ([h (f 3)])
  13567. (+ (g 11) (h 15))))
  13568. \end{lstlisting}
  13569. \fi}
  13570. {\if\edition\pythonEd
  13571. \begin{lstlisting}
  13572. def f(x : int) -> Callable[[int], int]:
  13573. y = 4
  13574. return lambda z: x + y + z
  13575. g = f(5)
  13576. h = f(3)
  13577. print( g(11) + h(15) )
  13578. \end{lstlisting}
  13579. \fi}
  13580. \caption{Example of a lexically scoped function.}
  13581. \label{fig:lexical-scoping}
  13582. \end{figure}
  13583. The approach that we take for implementing lexically scoped functions
  13584. is to compile them into top-level function definitions, translating
  13585. from \LangLam{} into \LangFun{}. However, the compiler must give
  13586. special treatment to variable occurrences such as \code{x} and
  13587. \code{y} in the body of the \code{lambda} of
  13588. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13589. may not refer to variables defined outside of it. To identify such
  13590. variable occurrences, we review the standard notion of free variable.
  13591. \begin{definition}
  13592. A variable is \textbf{free in expression} $e$ if the variable occurs
  13593. inside $e$ but does not have an enclosing definition that is also in
  13594. $e$.\index{subject}{free variable}
  13595. \end{definition}
  13596. For example, in the expression
  13597. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13598. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13599. only \code{x} and \code{y} are free in the following expression
  13600. because \code{z} is defined by the \code{lambda}.
  13601. {\if\edition\racketEd
  13602. \begin{lstlisting}
  13603. (lambda: ([z : Integer]) : Integer
  13604. (+ x (+ y z)))
  13605. \end{lstlisting}
  13606. \fi}
  13607. {\if\edition\pythonEd
  13608. \begin{lstlisting}
  13609. lambda z: x + y + z
  13610. \end{lstlisting}
  13611. \fi}
  13612. %
  13613. So the free variables of a \code{lambda} are the ones that need
  13614. special treatment. We need to transport, at runtime, the values of
  13615. those variables from the point where the \code{lambda} was created to
  13616. the point where the \code{lambda} is applied. An efficient solution to
  13617. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13618. of the free variables together with a function pointer into a tuple,
  13619. an arrangement called a \emph{flat closure} (which we shorten to just
  13620. ``closure''). \index{subject}{closure}\index{subject}{flat closure}
  13621. Fortunately, we have all the ingredients to make closures:
  13622. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  13623. function pointers. The function pointer resides at index $0$ and the
  13624. values for the free variables fill in the rest of the tuple.
  13625. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13626. how closures work. It's a three-step dance. The program calls function
  13627. \code{f}, which creates a closure for the \code{lambda}. The closure
  13628. is a tuple whose first element is a pointer to the top-level function
  13629. that we will generate for the \code{lambda}, the second element is the
  13630. value of \code{x}, which is \code{5}, and the third element is
  13631. \code{4}, the value of \code{y}. The closure does not contain an
  13632. element for \code{z} because \code{z} is not a free variable of the
  13633. \code{lambda}. Creating the closure is step 1 of the dance. The
  13634. closure is returned from \code{f} and bound to \code{g}, as shown in
  13635. Figure~\ref{fig:closures}.
  13636. %
  13637. The second call to \code{f} creates another closure, this time with
  13638. \code{3} in the second slot (for \code{x}). This closure is also
  13639. returned from \code{f} but bound to \code{h}, which is also shown in
  13640. Figure~\ref{fig:closures}.
  13641. \begin{figure}[tbp]
  13642. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13643. \caption{Flat closure representations for the two functions
  13644. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13645. \label{fig:closures}
  13646. \end{figure}
  13647. Continuing with the example, consider the application of \code{g} to
  13648. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13649. obtain the function pointer in the first element of the closure and
  13650. call it, passing in the closure itself and then the regular arguments,
  13651. in this case \code{11}. This technique for applying a closure is step
  13652. 2 of the dance.
  13653. %
  13654. But doesn't this \code{lambda} only take 1 argument, for parameter
  13655. \code{z}? The third and final step of the dance is generating a
  13656. top-level function for a \code{lambda}. We add an additional
  13657. parameter for the closure and we insert an initialization at the beginning
  13658. of the function for each free variable, to bind those variables to the
  13659. appropriate elements from the closure parameter.
  13660. %
  13661. This three-step dance is known as \emph{closure conversion}. We
  13662. discuss the details of closure conversion in
  13663. Section~\ref{sec:closure-conversion} and the code generated from the
  13664. example in Section~\ref{sec:example-lambda}. But first we define the
  13665. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13666. \section{The \LangLam{} Language}
  13667. \label{sec:r5}
  13668. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13669. functions and lexical scoping, is defined in
  13670. Figures~\ref{fig:Rlam-concrete-syntax} and \ref{fig:Rlam-syntax}. It adds
  13671. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13672. syntax for function application.
  13673. %
  13674. \python{The syntax also includes an assignment statement that includes
  13675. a type annotation for the variable on the left-hand side, which
  13676. facilitates the type checking of \code{lambda} expressions that we
  13677. discuss later in this section.}
  13678. %
  13679. \python{The \code{arity} operation returns the number of parameters of
  13680. a given function, an operation that we need for the translation
  13681. of dynamic typing in Chapter~\ref{ch:Ldyn}.
  13682. The \code{arity} operation is not in Python, but the same functionality
  13683. is available in a more complex form. We include \code{arity} in the
  13684. \LangLam{} source language to enable testing.}
  13685. \newcommand{\LlambdaGrammarRacket}{
  13686. \begin{array}{lcl}
  13687. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  13688. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  13689. \end{array}
  13690. }
  13691. \newcommand{\LlambdaASTRacket}{
  13692. \begin{array}{lcl}
  13693. \itm{op} &::=& \code{procedure-arity} \\
  13694. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  13695. \end{array}
  13696. }
  13697. \newcommand{\LlambdaGrammarPython}{
  13698. \begin{array}{lcl}
  13699. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  13700. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13701. \end{array}
  13702. }
  13703. \newcommand{\LlambdaASTPython}{
  13704. \begin{array}{lcl}
  13705. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  13706. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13707. \end{array}
  13708. }
  13709. % include AnnAssign in ASTPython
  13710. \begin{figure}[tp]
  13711. \centering
  13712. \fbox{
  13713. \begin{minipage}{0.96\textwidth}
  13714. \small
  13715. {\if\edition\racketEd
  13716. \[
  13717. \begin{array}{l}
  13718. \gray{\LintGrammarRacket{}} \\ \hline
  13719. \gray{\LvarGrammarRacket{}} \\ \hline
  13720. \gray{\LifGrammarRacket{}} \\ \hline
  13721. \gray{\LwhileGrammarRacket} \\ \hline
  13722. \gray{\LtupGrammarRacket} \\ \hline
  13723. \gray{\LfunGrammarRacket} \\ \hline
  13724. \LlambdaGrammarRacket \\
  13725. \begin{array}{lcl}
  13726. \LangLamM{} &::=& \Def\ldots \; \Exp
  13727. \end{array}
  13728. \end{array}
  13729. \]
  13730. \fi}
  13731. {\if\edition\pythonEd
  13732. \[
  13733. \begin{array}{l}
  13734. \gray{\LintGrammarPython{}} \\ \hline
  13735. \gray{\LvarGrammarPython{}} \\ \hline
  13736. \gray{\LifGrammarPython{}} \\ \hline
  13737. \gray{\LwhileGrammarPython} \\ \hline
  13738. \gray{\LtupGrammarPython} \\ \hline
  13739. \gray{\LfunGrammarPython} \\ \hline
  13740. \LlambdaGrammarPython \\
  13741. \begin{array}{lcl}
  13742. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13743. \end{array}
  13744. \end{array}
  13745. \]
  13746. \fi}
  13747. \end{minipage}
  13748. }
  13749. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  13750. with \key{lambda}.}
  13751. \label{fig:Rlam-concrete-syntax}
  13752. \end{figure}
  13753. \begin{figure}[tp]
  13754. \centering
  13755. \fbox{
  13756. \begin{minipage}{0.96\textwidth}
  13757. \small
  13758. {\if\edition\racketEd
  13759. \[
  13760. \begin{array}{l}
  13761. \gray{\LintOpAST} \\ \hline
  13762. \gray{\LvarASTRacket{}} \\ \hline
  13763. \gray{\LifASTRacket{}} \\ \hline
  13764. \gray{\LwhileASTRacket{}} \\ \hline
  13765. \gray{\LtupASTRacket{}} \\ \hline
  13766. \gray{\LfunASTRacket} \\ \hline
  13767. \LlambdaASTRacket \\
  13768. \begin{array}{lcl}
  13769. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13770. \end{array}
  13771. \end{array}
  13772. \]
  13773. \fi}
  13774. {\if\edition\pythonEd
  13775. \[
  13776. \begin{array}{l}
  13777. \gray{\LintASTPython} \\ \hline
  13778. \gray{\LvarASTPython{}} \\ \hline
  13779. \gray{\LifASTPython{}} \\ \hline
  13780. \gray{\LwhileASTPython{}} \\ \hline
  13781. \gray{\LtupASTPython{}} \\ \hline
  13782. \gray{\LfunASTPython} \\ \hline
  13783. \LlambdaASTPython \\
  13784. \begin{array}{lcl}
  13785. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13786. \end{array}
  13787. \end{array}
  13788. \]
  13789. \fi}
  13790. \end{minipage}
  13791. }
  13792. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  13793. \label{fig:Rlam-syntax}
  13794. \end{figure}
  13795. \index{subject}{interpreter}
  13796. \label{sec:interp-Rlambda}
  13797. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  13798. \LangLam{}. The case for \key{Lambda} saves the current environment
  13799. inside the returned function value. Recall that during function
  13800. application, the environment stored in the function value, extended
  13801. with the mapping of parameters to argument values, is used to
  13802. interpret the body of the function.
  13803. \begin{figure}[tbp]
  13804. {\if\edition\racketEd
  13805. \begin{lstlisting}
  13806. (define interp-Rlambda_class
  13807. (class interp-Rfun_class
  13808. (super-new)
  13809. (define/override (interp-op op)
  13810. (match op
  13811. ['procedure-arity
  13812. (lambda (v)
  13813. (match v
  13814. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13815. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13816. [else (super interp-op op)]))
  13817. (define/override ((interp-exp env) e)
  13818. (define recur (interp-exp env))
  13819. (match e
  13820. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13821. `(function ,xs ,body ,env)]
  13822. [else ((super interp-exp env) e)]))
  13823. ))
  13824. (define (interp-Rlambda p)
  13825. (send (new interp-Rlambda_class) interp-program p))
  13826. \end{lstlisting}
  13827. \fi}
  13828. {\if\edition\pythonEd
  13829. \begin{lstlisting}
  13830. class InterpLlambda(InterpLfun):
  13831. def arity(self, v):
  13832. match v:
  13833. case Function(name, params, body, env):
  13834. return len(params)
  13835. case _:
  13836. raise Exception('Llambda arity unexpected ' + repr(v))
  13837. def interp_exp(self, e, env):
  13838. match e:
  13839. case Call(Name('arity'), [fun]):
  13840. f = self.interp_exp(fun, env)
  13841. return self.arity(f)
  13842. case Lambda(params, body):
  13843. return Function('lambda', params, [Return(body)], env)
  13844. case _:
  13845. return super().interp_exp(e, env)
  13846. def interp_stmts(self, ss, env):
  13847. if len(ss) == 0:
  13848. return
  13849. match ss[0]:
  13850. case AnnAssign(lhs, typ, value, simple):
  13851. env[lhs.id] = self.interp_exp(value, env)
  13852. return self.interp_stmts(ss[1:], env)
  13853. case _:
  13854. return super().interp_stmts(ss, env)
  13855. \end{lstlisting}
  13856. \fi}
  13857. \caption{Interpreter for \LangLam{}.}
  13858. \label{fig:interp-Rlambda}
  13859. \end{figure}
  13860. \label{sec:type-check-r5}
  13861. \index{subject}{type checking}
  13862. {\if\edition\racketEd
  13863. %
  13864. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  13865. \key{lambda} form. The body of the \key{lambda} is checked in an
  13866. environment that includes the current environment (because it is
  13867. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13868. require the body's type to match the declared return type.
  13869. %
  13870. \fi}
  13871. {\if\edition\pythonEd
  13872. %
  13873. Figures~\ref{fig:type-check-Llambda} and
  13874. \ref{fig:type-check-Llambda-part2} define the type checker for
  13875. \LangLam{}, which is more complex than one might expect. The reason
  13876. for the added complexity is that the syntax of \key{lambda} does not
  13877. include type annotations for the parameters or return type. Instead
  13878. they must be inferred. There are many approaches of type inference to
  13879. choose from of varying degrees of complexity. We choose one of the
  13880. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  13881. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  13882. this book is compilation, not type inference.
  13883. The main idea of bidirectional type inference is to add an auxilliary
  13884. function, here named \code{check\_exp}, that takes an expected type
  13885. and checks whether the given expression is of that type. Thus, in
  13886. \code{check\_exp}, type information flows in a top-down manner with
  13887. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  13888. function, where type information flows in a primarily bottom-up
  13889. manner.
  13890. %
  13891. The idea then is to use \code{check\_exp} in all the places where we
  13892. already know what the type of an expression should be, such as in the
  13893. \code{return} statement of a top-level function definition, or on the
  13894. right-hand side of an annotated assignment statement.
  13895. Getting back to \code{lambda}, it is straightforward to check a
  13896. \code{lambda} inside \code{check\_exp} because the expected type
  13897. provides the parameter types and the return type. On the other hand,
  13898. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  13899. that we do not allow \code{lambda} in contexts where we don't already
  13900. know its type. This restriction does not incur a loss of
  13901. expressiveness for \LangLam{} because it is straightforward to modify
  13902. a program to sidestep the restriction, for example, by using an
  13903. annotated assignment statement to assign the \code{lambda} to a
  13904. temporary variable.
  13905. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  13906. checker records their type in a \code{has\_type} field. This type
  13907. information is used later in this chapter.
  13908. %
  13909. \fi}
  13910. \begin{figure}[tbp]
  13911. {\if\edition\racketEd
  13912. \begin{lstlisting}
  13913. (define (type-check-Rlambda env)
  13914. (lambda (e)
  13915. (match e
  13916. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13917. (define-values (new-body bodyT)
  13918. ((type-check-exp (append (map cons xs Ts) env)) body))
  13919. (define ty `(,@Ts -> ,rT))
  13920. (cond
  13921. [(equal? rT bodyT)
  13922. (values (HasType (Lambda params rT new-body) ty) ty)]
  13923. [else
  13924. (error "mismatch in return type" bodyT rT)])]
  13925. ...
  13926. )))
  13927. \end{lstlisting}
  13928. \fi}
  13929. {\if\edition\pythonEd
  13930. \begin{lstlisting}
  13931. class TypeCheckLlambda(TypeCheckLfun):
  13932. def type_check_exp(self, e, env):
  13933. match e:
  13934. case Name(id):
  13935. e.has_type = env[id]
  13936. return env[id]
  13937. case Lambda(params, body):
  13938. raise Exception('cannot synthesize a type for a lambda')
  13939. case Call(Name('arity'), [func]):
  13940. func_t = self.type_check_exp(func, env)
  13941. match func_t:
  13942. case FunctionType(params_t, return_t):
  13943. return IntType()
  13944. case _:
  13945. raise Exception('in arity, unexpected ' + repr(func_t))
  13946. case _:
  13947. return super().type_check_exp(e, env)
  13948. def check_exp(self, e, ty, env):
  13949. match e:
  13950. case Lambda(params, body):
  13951. e.has_type = ty
  13952. match ty:
  13953. case FunctionType(params_t, return_t):
  13954. new_env = env.copy().update(zip(params, params_t))
  13955. self.check_exp(body, return_t, new_env)
  13956. case _:
  13957. raise Exception('lambda does not have type ' + str(ty))
  13958. case Call(func, args):
  13959. func_t = self.type_check_exp(func, env)
  13960. match func_t:
  13961. case FunctionType(params_t, return_t):
  13962. for (arg, param_t) in zip(args, params_t):
  13963. self.check_exp(arg, param_t, env)
  13964. self.check_type_equal(return_t, ty, e)
  13965. case _:
  13966. raise Exception('type_check_exp: in call, unexpected ' + \
  13967. repr(func_t))
  13968. case _:
  13969. t = self.type_check_exp(e, env)
  13970. self.check_type_equal(t, ty, e)
  13971. \end{lstlisting}
  13972. \fi}
  13973. \caption{Type checking \LangLam{}\python{, part 1}.}
  13974. \label{fig:type-check-Llambda}
  13975. \end{figure}
  13976. {\if\edition\pythonEd
  13977. \begin{figure}[tbp]
  13978. \begin{lstlisting}
  13979. def check_stmts(self, ss, return_ty, env):
  13980. if len(ss) == 0:
  13981. return
  13982. match ss[0]:
  13983. case FunctionDef(name, params, body, dl, returns, comment):
  13984. new_env = env.copy().update(params)
  13985. rt = self.check_stmts(body, returns, new_env)
  13986. self.check_stmts(ss[1:], return_ty, env)
  13987. case Return(value):
  13988. self.check_exp(value, return_ty, env)
  13989. case Assign([Name(id)], value):
  13990. if id in env:
  13991. self.check_exp(value, env[id], env)
  13992. else:
  13993. env[id] = self.type_check_exp(value, env)
  13994. self.check_stmts(ss[1:], return_ty, env)
  13995. case Assign([Subscript(tup, Constant(index), Store())], value):
  13996. tup_t = self.type_check_exp(tup, env)
  13997. match tup_t:
  13998. case TupleType(ts):
  13999. self.check_exp(value, ts[index], env)
  14000. case _:
  14001. raise Exception('expected a tuple, not ' + repr(tup_t))
  14002. self.check_stmts(ss[1:], return_ty, env)
  14003. case AnnAssign(Name(id), ty, value, simple):
  14004. ss[0].annotation = ty_annot
  14005. if id in env:
  14006. self.check_type_equal(env[id], ty)
  14007. else:
  14008. env[id] = ty_annot
  14009. self.check_exp(value, ty_annot, env)
  14010. case _:
  14011. self.type_check_stmts(ss, env)
  14012. def type_check(self, p):
  14013. match p:
  14014. case Module(body):
  14015. env = {}
  14016. for s in body:
  14017. match s:
  14018. case FunctionDef(name, params, bod, dl, returns, comment):
  14019. params_t = [t for (x,t) in params]
  14020. env[name] = FunctionType(params_t, returns)
  14021. self.check_stmts(body, int, env)
  14022. \end{lstlisting}
  14023. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14024. \label{fig:type-check-Llambda-part2}
  14025. \end{figure}
  14026. \fi}
  14027. \clearpage
  14028. \section{Assignment and Lexically Scoped Functions}
  14029. \label{sec:assignment-scoping}
  14030. The combination of lexically-scoped functions and assignment to
  14031. variables raises a challenge with our approach to implementing
  14032. lexically-scoped functions. Consider the following example in which
  14033. function \code{f} has a free variable \code{x} that is changed after
  14034. \code{f} is created but before the call to \code{f}.
  14035. % loop_test_11.rkt
  14036. {\if\edition\racketEd
  14037. \begin{lstlisting}
  14038. (let ([x 0])
  14039. (let ([y 0])
  14040. (let ([z 20])
  14041. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14042. (begin
  14043. (set! x 10)
  14044. (set! y 12)
  14045. (f y))))))
  14046. \end{lstlisting}
  14047. \fi}
  14048. {\if\edition\pythonEd
  14049. % box_free_assign.py
  14050. \begin{lstlisting}
  14051. def g(z : int) -> int:
  14052. x = 0
  14053. y = 0
  14054. f : Callable[[int],int] = lambda a: a + x + z
  14055. x = 10
  14056. y = 12
  14057. return f(y)
  14058. print( g(20) )
  14059. \end{lstlisting}
  14060. \fi}
  14061. The correct output for this example is \code{42} because the call to
  14062. \code{f} is required to use the current value of \code{x} (which is
  14063. \code{10}). Unfortunately, the closure conversion pass
  14064. (Section~\ref{sec:closure-conversion}) generates code for the
  14065. \code{lambda} that copies the old value of \code{x} into a
  14066. closure. Thus, if we naively add support for assignment to our current
  14067. compiler, the output of this program would be \code{32}.
  14068. A first attempt at solving this problem would be to save a pointer to
  14069. \code{x} in the closure and change the occurrences of \code{x} inside
  14070. the lambda to dereference the pointer. Of course, this would require
  14071. assigning \code{x} to the stack and not to a register. However, the
  14072. problem goes a bit deeper.
  14073. %% Consider the following example in which we
  14074. %% create a counter abstraction by creating a pair of functions that
  14075. %% share the free variable \code{x}.
  14076. Consider the following example that returns a function that refers to
  14077. a local variable of the enclosing function.
  14078. \begin{center}
  14079. \begin{minipage}{\textwidth}
  14080. {\if\edition\racketEd
  14081. % similar to loop_test_10.rkt
  14082. %% \begin{lstlisting}
  14083. %% (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  14084. %% (vector
  14085. %% (lambda: () : Integer x)
  14086. %% (lambda: () : Void (set! x (+ 1 x)))))
  14087. %% (let ([counter (f 0)])
  14088. %% (let ([get (vector-ref counter 0)])
  14089. %% (let ([inc (vector-ref counter 1)])
  14090. %% (begin
  14091. %% (inc)
  14092. %% (get)))))
  14093. %% \end{lstlisting}
  14094. \begin{lstlisting}
  14095. (define (f []) : Integer
  14096. (let ([x 0])
  14097. (let ([g (lambda: () : Integer x)])
  14098. (begin
  14099. (set! x 42)
  14100. g))))
  14101. ((f))
  14102. \end{lstlisting}
  14103. \fi}
  14104. {\if\edition\pythonEd
  14105. % counter.py
  14106. \begin{lstlisting}
  14107. def f():
  14108. x = 0
  14109. g = lambda: x
  14110. x = 42
  14111. return g
  14112. print( f()() )
  14113. \end{lstlisting}
  14114. \fi}
  14115. \end{minipage}
  14116. \end{center}
  14117. In this example, the lifetime of \code{x} extends beyond the lifetime
  14118. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14119. stack frame for the call to \code{f}, it would be gone by the time we
  14120. call \code{g}, leaving us with dangling pointers for
  14121. \code{x}. This example demonstrates that when a variable occurs free
  14122. inside a function, its lifetime becomes indefinite. Thus, the value of
  14123. the variable needs to live on the heap. The verb
  14124. \emph{box}\index{subject}{box} is often used for allocating a single
  14125. value on the heap, producing a pointer, and
  14126. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14127. %% {\if\edition\racketEd
  14128. %% We recommend solving these problems by boxing the local variables that
  14129. %% are in the intersection of 1) variables that appear on the
  14130. %% left-hand-side of a \code{set!} and 2) variables that occur free
  14131. %% inside a \code{lambda}.
  14132. %% \fi}
  14133. %% {\if\edition\pythonEd
  14134. %% We recommend solving these problems by boxing the local variables that
  14135. %% are in the intersection of 1) variables whose values may change and 2)
  14136. %% variables that occur free inside a \code{lambda}.
  14137. %% \fi}
  14138. We shall introduce a new pass named
  14139. \code{convert\_assignments} in Section~\ref{sec:convert-assignments}
  14140. to address this challenge.
  14141. %
  14142. \racket{But before diving into the compiler passes, we have one more
  14143. problem to discuss.}
  14144. \if\edition\pythonEd
  14145. \section{Uniquify Variables}
  14146. \label{sec:uniquify-lambda}
  14147. With the addition of \code{lambda} we have a complication to deal
  14148. with: name shadowing. Consider the following program with a function
  14149. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14150. \code{lambda} expressions. The first \code{lambda} has a parameter
  14151. that is also named \code{x}.
  14152. \begin{lstlisting}
  14153. def f(x:int, y:int) -> Callable[[int], int]:
  14154. g : Callable[[int],int] = (lambda x: x + y)
  14155. h : Callable[[int],int] = (lambda y: x + y)
  14156. x = input_int()
  14157. return g
  14158. print(f(0, 10)(32))
  14159. \end{lstlisting}
  14160. Many of our compiler passes rely on being able to connect variable
  14161. uses with their definitions using just the name of the variable,
  14162. including new passes in this chapter. However, in the above example
  14163. the name of the variable does not uniquely determine its
  14164. definition. To solve this problem we recommend implementing a pass
  14165. named \code{uniquify} that renames every variable in the program to
  14166. make sure they are all unique.
  14167. The following shows the result of \code{uniquify} for the above
  14168. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14169. and the \code{x} parameter of the \code{lambda} is renamed to
  14170. \code{x\_4}.
  14171. \begin{lstlisting}
  14172. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14173. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14174. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14175. x_0 = input_int()
  14176. return g_2
  14177. def main() -> int :
  14178. print(f(0, 10)(32))
  14179. return 0
  14180. \end{lstlisting}
  14181. \fi
  14182. %% \section{Reveal Functions}
  14183. %% \label{sec:reveal-functions-r5}
  14184. %% \racket{To support the \code{procedure-arity} operator we need to
  14185. %% communicate the arity of a function to the point of closure
  14186. %% creation.}
  14187. %% %
  14188. %% \python{In Chapter~\ref{ch:Ldyn} we need to access the arity of a
  14189. %% function at runtime. Thus, we need to communicate the arity of a
  14190. %% function to the point of closure creation.}
  14191. %% %
  14192. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14193. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14194. %% \[
  14195. %% \begin{array}{lcl}
  14196. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14197. %% \end{array}
  14198. %% \]
  14199. \section{Assignment Conversion}
  14200. \label{sec:convert-assignments}
  14201. The purpose of the \code{convert\_assignments} pass is to address the
  14202. challenge posed in Section~\ref{sec:assignment-scoping} regarding the
  14203. interaction between variable assignments and closure conversion.
  14204. First we identify which variables need to be boxed, then we transform
  14205. the program to box those variables. In general, boxing introduces
  14206. runtime overhead that we would like to avoid, so we should box as few
  14207. variables as possible. We recommend boxing the variables in the
  14208. intersection of the following two sets of variables:
  14209. \begin{enumerate}
  14210. \item The variables that are free in a \code{lambda}.
  14211. \item The variables that appear on the left-hand side of an
  14212. assignment.
  14213. \end{enumerate}
  14214. The first condition is a must, but the second condition is quite conservative and it is possible to
  14215. develop a more liberal condition.
  14216. Consider again the first example from
  14217. Section~\ref{sec:assignment-scoping}:
  14218. %
  14219. {\if\edition\racketEd
  14220. \begin{lstlisting}
  14221. (let ([x 0])
  14222. (let ([y 0])
  14223. (let ([z 20])
  14224. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14225. (begin
  14226. (set! x 10)
  14227. (set! y 12)
  14228. (f y))))))
  14229. \end{lstlisting}
  14230. \fi}
  14231. {\if\edition\pythonEd
  14232. \begin{lstlisting}
  14233. def g(z : int) -> int:
  14234. x = 0
  14235. y = 0
  14236. f : Callable[[int],int] = lambda a: a + x + z
  14237. x = 10
  14238. y = 12
  14239. return f(y)
  14240. print( g(20) )
  14241. \end{lstlisting}
  14242. \fi}
  14243. %
  14244. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14245. variables \code{x} and \code{z} occur free inside the
  14246. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14247. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14248. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14249. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14250. with a tuple write. The output of \code{convert\_assignments} for
  14251. this example is as follows.
  14252. %
  14253. {\if\edition\racketEd
  14254. \begin{lstlisting}
  14255. (define (main) : Integer
  14256. (let ([x0 (vector 0)])
  14257. (let ([y1 0])
  14258. (let ([z2 20])
  14259. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14260. (+ a3 (+ (vector-ref x0 0) z2)))])
  14261. (begin
  14262. (vector-set! x0 0 10)
  14263. (set! y1 12)
  14264. (f4 y1)))))))
  14265. \end{lstlisting}
  14266. \fi}
  14267. %
  14268. {\if\edition\pythonEd
  14269. \begin{lstlisting}
  14270. def g(z : int)-> int:
  14271. x = (uninitialized(int),)
  14272. x[0] = 0
  14273. y = 0
  14274. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14275. x[0] = 10
  14276. y = 12
  14277. return f(y)
  14278. def main() -> int:
  14279. print(g(20))
  14280. return 0
  14281. \end{lstlisting}
  14282. \fi}
  14283. To compute the free variables of all the \code{lambda} expressions, we
  14284. recommend defining two auxiliary functions:
  14285. \begin{enumerate}
  14286. \item \code{free\_variables} computes the free variables of an expression, and
  14287. \item \code{free\_in\_lambda} collects all of the variables that are
  14288. free in any of the \code{lambda} expressions, using
  14289. \code{free\_variables} in the case for each \code{lambda}.
  14290. \end{enumerate}
  14291. {\if\edition\racketEd
  14292. %
  14293. To compute the variables that are assigned-to, we recommend using the
  14294. \code{collect-set!} function that we introduced in
  14295. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14296. forms such as \code{Lambda}.
  14297. %
  14298. \fi}
  14299. {\if\edition\pythonEd
  14300. %
  14301. To compute the variables that are assigned-to, we recommend defining
  14302. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14303. the set of variables that occur in the left-hand side of an assignment
  14304. statement, and otherwise returns the empty set.
  14305. %
  14306. \fi}
  14307. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14308. free in a \code{lambda} and that are assigned-to in the enclosing
  14309. function definition.
  14310. Next we discuss the \code{convert\_assignments} pass. In the case for
  14311. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14312. $\VAR{x}$ to a tuple read.
  14313. %
  14314. {\if\edition\racketEd
  14315. \begin{lstlisting}
  14316. (Var |$x$|)
  14317. |$\Rightarrow$|
  14318. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14319. \end{lstlisting}
  14320. \fi}
  14321. %
  14322. {\if\edition\pythonEd
  14323. \begin{lstlisting}
  14324. Name(|$x$|)
  14325. |$\Rightarrow$|
  14326. Subscript(Name(|$x$|), Constant(0), Load())
  14327. \end{lstlisting}
  14328. \fi}
  14329. %
  14330. %
  14331. In the case for assignment, recursively process the right-hand side
  14332. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in $\mathit{AF}$, translate
  14333. the assignment into a tuple-write as follows.
  14334. %
  14335. {\if\edition\racketEd
  14336. \begin{lstlisting}
  14337. (SetBang |$x$| |$\itm{rhs}$|)
  14338. |$\Rightarrow$|
  14339. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14340. \end{lstlisting}
  14341. \fi}
  14342. {\if\edition\pythonEd
  14343. \begin{lstlisting}
  14344. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14345. |$\Rightarrow$|
  14346. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14347. \end{lstlisting}
  14348. \fi}
  14349. %
  14350. {\if\edition\racketEd
  14351. The case for \code{Lambda} is non-trivial, but it is similar to the
  14352. case for function definitions, which we discuss next.
  14353. \fi}
  14354. To translate a function definition, we first compute $\mathit{AF}$,
  14355. the intersection of the variables that are free in a \code{lambda} and
  14356. that are assigned-to. We then apply assignment conversion to the body
  14357. of the function definition. Finally, we box the parameters of this
  14358. function definition that are in $\mathit{AF}$. For example,
  14359. the parameter \code{x} of the following function \code{g}
  14360. needs to be boxed.
  14361. {\if\edition\racketEd
  14362. \begin{lstlisting}
  14363. (define (g [x : Integer]) : Integer
  14364. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14365. (begin
  14366. (set! x 10)
  14367. (f 32))))
  14368. \end{lstlisting}
  14369. \fi}
  14370. %
  14371. {\if\edition\pythonEd
  14372. \begin{lstlisting}
  14373. def g(x : int) -> int:
  14374. f : Callable[[int],int] = lambda a: a + x
  14375. x = 10
  14376. return f(32)
  14377. \end{lstlisting}
  14378. \fi}
  14379. %
  14380. \noindent We box parameter \code{x} by creating a local variable named
  14381. \code{x} that is initialized to a tuple whose contents is the value of
  14382. the parameter, which we has been renamed.
  14383. %
  14384. {\if\edition\racketEd
  14385. \begin{lstlisting}
  14386. (define (g [x_0 : Integer]) : Integer
  14387. (let ([x (vector x_0)])
  14388. (let ([f (lambda: ([a : Integer]) : Integer
  14389. (+ a (vector-ref x 0)))])
  14390. (begin
  14391. (vector-set! x 0 10)
  14392. (f 32)))))
  14393. \end{lstlisting}
  14394. \fi}
  14395. %
  14396. {\if\edition\pythonEd
  14397. \begin{lstlisting}
  14398. def g(x_0 : int)-> int:
  14399. x = (x_0,)
  14400. f : Callable[[int], int] = (lambda a: a + x[0])
  14401. x[0] = 10
  14402. return f(32)
  14403. \end{lstlisting}
  14404. \fi}
  14405. %% Recall the second example in Section~\ref{sec:assignment-scoping}
  14406. %% involving a counter abstraction. The following is the output of
  14407. %% assignment version for function \code{f}.
  14408. %% \begin{lstlisting}
  14409. %% (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  14410. %% (vector
  14411. %% (lambda: () : Integer x1)
  14412. %% (lambda: () : Void (set! x1 (+ 1 x1)))))
  14413. %% |$\Rightarrow$|
  14414. %% (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  14415. %% (let ([x1 (vector param_x1)])
  14416. %% (vector (lambda: () : Integer (vector-ref x1 0))
  14417. %% (lambda: () : Void
  14418. %% (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  14419. %% \end{lstlisting}
  14420. \section{Closure Conversion}
  14421. \label{sec:closure-conversion}
  14422. \index{subject}{closure conversion}
  14423. The compiling of lexically-scoped functions into top-level function
  14424. definitions is accomplished in the pass \code{convert\_to\_closures}
  14425. that comes after \code{reveal\_functions} and before
  14426. \code{limit\_functions}.
  14427. As usual, we implement the pass as a recursive function over the
  14428. AST. The interesting cases are the ones for \key{lambda} and function
  14429. application. We transform a \key{lambda} expression into an expression
  14430. that creates a closure, that is, a tuple whose first element is a
  14431. function pointer and the rest of the elements are the values of the
  14432. free variables of the \key{lambda}.
  14433. %
  14434. However, we use the \code{Closure} AST node instead of using a tuple
  14435. so that we can record the arity.
  14436. %
  14437. In the generated code below, \itm{fvs} is the free variables of the
  14438. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14439. %
  14440. \racket{The \itm{arity} is the number of parameters (the length of
  14441. \itm{ps}).}
  14442. %
  14443. {\if\edition\racketEd
  14444. \begin{lstlisting}
  14445. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14446. |$\Rightarrow$|
  14447. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  14448. \end{lstlisting}
  14449. \fi}
  14450. %
  14451. {\if\edition\pythonEd
  14452. \begin{lstlisting}
  14453. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  14454. |$\Rightarrow$|
  14455. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  14456. \end{lstlisting}
  14457. \fi}
  14458. %
  14459. In addition to transforming each \key{Lambda} AST node into a
  14460. tuple, we create a top-level function definition for each
  14461. \key{Lambda}, as shown below.\\
  14462. \begin{minipage}{0.8\textwidth}
  14463. {\if\edition\racketEd
  14464. \begin{lstlisting}
  14465. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14466. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14467. ...
  14468. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14469. |\itm{body'}|)...))
  14470. \end{lstlisting}
  14471. \fi}
  14472. {\if\edition\pythonEd
  14473. \begin{lstlisting}
  14474. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14475. |$\itm{fvs}_1$| = clos[1]
  14476. |$\ldots$|
  14477. |$\itm{fvs}_n$| = clos[|$n$|]
  14478. |\itm{body'}|
  14479. \end{lstlisting}
  14480. \fi}
  14481. \end{minipage}\\
  14482. The \code{clos} parameter refers to the closure. Translate the type
  14483. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14484. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14485. \itm{closTy} is a tuple type whose first element type is
  14486. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14487. the element types are the types of the free variables in the
  14488. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14489. is non-trivial to give a type to the function in the closure's type.%
  14490. %
  14491. \footnote{To give an accurate type to a closure, we would need to add
  14492. existential types to the type checker~\citep{Minamide:1996ys}.}
  14493. %
  14494. %% The dummy type is considered to be equal to any other type during type
  14495. %% checking.
  14496. The free variables become local variables that are initialized with
  14497. their values in the closure.
  14498. Closure conversion turns every function into a tuple, so the type
  14499. annotations in the program must also be translated. We recommend
  14500. defining an auxiliary recursive function for this purpose. Function
  14501. types should be translated as follows.
  14502. %
  14503. {\if\edition\racketEd
  14504. \begin{lstlisting}
  14505. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14506. |$\Rightarrow$|
  14507. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14508. \end{lstlisting}
  14509. \fi}
  14510. {\if\edition\pythonEd
  14511. \begin{lstlisting}
  14512. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14513. |$\Rightarrow$|
  14514. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14515. \end{lstlisting}
  14516. \fi}
  14517. %
  14518. The above type says that the first thing in the tuple is a
  14519. function. The first parameter of the function is a tuple (a closure)
  14520. and the rest of the parameters are the ones from the original
  14521. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14522. omits the types of the free variables because 1) those types are not
  14523. available in this context and 2) we do not need them in the code that
  14524. is generated for function application. So this type only describes the
  14525. first component of the closure tuple. At runtime the tuple may have
  14526. more components, but we ignore them at this point.
  14527. We transform function application into code that retrieves the
  14528. function from the closure and then calls the function, passing the
  14529. closure as the first argument. We place $e'$ in a temporary variable
  14530. to avoid code duplication.
  14531. \begin{center}
  14532. \begin{minipage}{\textwidth}
  14533. {\if\edition\racketEd
  14534. \begin{lstlisting}
  14535. (Apply |$e$| |$\itm{es}$|)
  14536. |$\Rightarrow$|
  14537. (Let |$\itm{tmp}$| |$e'$|
  14538. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons |$\itm{tmp}$| |$\itm{es'}$|)))
  14539. \end{lstlisting}
  14540. \fi}
  14541. %
  14542. {\if\edition\pythonEd
  14543. \begin{lstlisting}
  14544. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14545. |$\Rightarrow$|
  14546. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  14547. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14548. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14549. \end{lstlisting}
  14550. \fi}
  14551. \end{minipage}
  14552. \end{center}
  14553. There is also the question of what to do with references to top-level
  14554. function definitions. To maintain a uniform translation of function
  14555. application, we turn function references into closures.
  14556. \begin{tabular}{lll}
  14557. \begin{minipage}{0.3\textwidth}
  14558. {\if\edition\racketEd
  14559. \begin{lstlisting}
  14560. (FunRefArity |$f$| |$n$|)
  14561. \end{lstlisting}
  14562. \fi}
  14563. {\if\edition\pythonEd
  14564. \begin{lstlisting}
  14565. FunRefArity(|$f$|, |$n$|)
  14566. \end{lstlisting}
  14567. \fi}
  14568. \end{minipage}
  14569. &
  14570. $\Rightarrow$
  14571. &
  14572. \begin{minipage}{0.5\textwidth}
  14573. {\if\edition\racketEd
  14574. \begin{lstlisting}
  14575. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  14576. \end{lstlisting}
  14577. \fi}
  14578. {\if\edition\pythonEd
  14579. \begin{lstlisting}
  14580. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  14581. \end{lstlisting}
  14582. \fi}
  14583. \end{minipage}
  14584. \end{tabular} \\
  14585. We no longer need the annotated assignment statement \code{AnnAssign}
  14586. to support the type checking of \code{lambda} expressions, so we
  14587. translate it to a regular \code{Assign} statement.
  14588. The top-level function definitions need to be updated to take an extra
  14589. closure parameter.
  14590. \section{An Example Translation}
  14591. \label{sec:example-lambda}
  14592. Figure~\ref{fig:lexical-functions-example} shows the result of
  14593. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14594. program demonstrating lexical scoping that we discussed at the
  14595. beginning of this chapter.
  14596. \begin{figure}[tbp]
  14597. \begin{minipage}{0.8\textwidth}
  14598. {\if\edition\racketEd
  14599. % tests/lambda_test_6.rkt
  14600. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14601. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14602. (let ([y8 4])
  14603. (lambda: ([z9 : Integer]) : Integer
  14604. (+ x7 (+ y8 z9)))))
  14605. (define (main) : Integer
  14606. (let ([g0 ((fun-ref f6 1) 5)])
  14607. (let ([h1 ((fun-ref f6 1) 3)])
  14608. (+ (g0 11) (h1 15)))))
  14609. \end{lstlisting}
  14610. $\Rightarrow$
  14611. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14612. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14613. (let ([y8 4])
  14614. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  14615. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14616. (let ([x7 (vector-ref fvs3 1)])
  14617. (let ([y8 (vector-ref fvs3 2)])
  14618. (+ x7 (+ y8 z9)))))
  14619. (define (main) : Integer
  14620. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  14621. ((vector-ref clos5 0) clos5 5))])
  14622. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  14623. ((vector-ref clos6 0) clos6 3))])
  14624. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14625. \end{lstlisting}
  14626. \fi}
  14627. %
  14628. {\if\edition\pythonEd
  14629. % free_var.py
  14630. \begin{lstlisting}
  14631. def f(x : int) -> Callable[[int], int]:
  14632. y = 4
  14633. return lambda z: x + y + z
  14634. g = f(5)
  14635. h = f(3)
  14636. print( g(11) + h(15) )
  14637. \end{lstlisting}
  14638. $\Rightarrow$
  14639. \begin{lstlisting}
  14640. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14641. x = fvs_1[1]
  14642. y = fvs_1[2]
  14643. return x + y[0] + z
  14644. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14645. y = (777,)
  14646. y[0] = 4
  14647. return (lambda_0, x, y)
  14648. def main() -> int:
  14649. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14650. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14651. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14652. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14653. return 0
  14654. \end{lstlisting}
  14655. \fi}
  14656. \end{minipage}
  14657. \caption{Example of closure conversion.}
  14658. \label{fig:lexical-functions-example}
  14659. \end{figure}
  14660. \begin{exercise}\normalfont
  14661. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14662. Create 5 new programs that use \key{lambda} functions and make use of
  14663. lexical scoping. Test your compiler on these new programs and all of
  14664. your previously created test programs.
  14665. \end{exercise}
  14666. \section{Expose Allocation}
  14667. \label{sec:expose-allocation-r5}
  14668. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  14669. that allocates and initializes a tuple, similar to the translation of
  14670. the tuple creation in Section~\ref{sec:expose-allocation}.
  14671. The only difference is replacing the use of
  14672. \ALLOC{\itm{len}}{\itm{type}} with
  14673. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14674. \section{Explicate Control and \LangCLam{}}
  14675. \label{sec:explicate-r5}
  14676. The output language of \code{explicate\_control} is \LangCLam{} whose
  14677. abstract syntax is defined in Figure~\ref{fig:Clam-syntax}.
  14678. %
  14679. \racket{The only difference with respect to \LangCFun{} is the
  14680. addition of the \code{AllocateClosure} form to the grammar for
  14681. $\Exp$. The handling of \code{AllocateClosure} in the
  14682. \code{explicate\_control} pass is similar to the handling of other
  14683. expressions such as primitive operators.}
  14684. %
  14685. \python{The differences with respect to \LangCFun{} are the
  14686. additions of \code{Uninitialized}, \code{AllocateClosure},
  14687. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  14688. \code{explicate\_control} pass is similar to the handling of other
  14689. expressions such as primitive operators.}
  14690. \newcommand{\ClambdaASTPython}{
  14691. \begin{array}{lcl}
  14692. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  14693. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  14694. &\MID& \ARITY{\Atm}
  14695. \end{array}
  14696. }
  14697. \begin{figure}[tp]
  14698. \fbox{
  14699. \begin{minipage}{0.96\textwidth}
  14700. \small
  14701. {\if\edition\racketEd
  14702. \[
  14703. \begin{array}{lcl}
  14704. \Exp &::= & \ldots
  14705. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14706. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14707. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  14708. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14709. \MID \GOTO{\itm{label}} } \\
  14710. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14711. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  14712. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14713. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14714. \end{array}
  14715. \]
  14716. \fi}
  14717. {\if\edition\pythonEd
  14718. \[
  14719. \begin{array}{l}
  14720. \gray{\CifASTPython} \\ \hline
  14721. \gray{\CtupASTPython} \\ \hline
  14722. \gray{\CfunASTPython} \\ \hline
  14723. \ClambdaASTPython \\
  14724. \begin{array}{lcl}
  14725. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14726. \end{array}
  14727. \end{array}
  14728. \]
  14729. \fi}
  14730. \end{minipage}
  14731. }
  14732. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14733. \label{fig:Clam-syntax}
  14734. \end{figure}
  14735. \section{Select Instructions}
  14736. \label{sec:select-instructions-Rlambda}
  14737. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14738. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14739. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14740. that you should place the \itm{arity} in the tag that is stored at
  14741. position $0$ of the vector. Recall that in
  14742. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14743. was not used. We store the arity in the $5$ bits starting at position
  14744. $58$.
  14745. \racket{Compile the \code{procedure-arity} operator into a sequence of
  14746. instructions that access the tag from position $0$ of the vector and
  14747. extract the $5$-bits starting at position $58$ from the tag.}
  14748. %
  14749. \python{Compile a call to the \code{arity} operator to a sequence of
  14750. instructions that access the tag from position $0$ of the tuple
  14751. (representing a closure) and extract the $5$-bits starting at position
  14752. $58$ from the tag.}
  14753. \begin{figure}[p]
  14754. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14755. \node (Rfun) at (0,2) {\large \LangLam{}};
  14756. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  14757. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  14758. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14759. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  14760. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  14761. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  14762. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  14763. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14764. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14765. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14766. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14767. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14768. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14769. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14770. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14771. \path[->,bend left=15] (Rfun) edge [above] node
  14772. {\ttfamily\footnotesize shrink} (Rfun-2);
  14773. \path[->,bend left=15] (Rfun-2) edge [above] node
  14774. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14775. \path[->,bend left=15] (Rfun-3) edge [above] node
  14776. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14777. \path[->,bend left=15] (F1-0) edge [right] node
  14778. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  14779. \path[->,bend left=15] (F1-1) edge [below] node
  14780. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14781. \path[->,bend right=15] (F1-2) edge [above] node
  14782. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14783. \path[->,bend right=15] (F1-3) edge [above] node
  14784. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14785. \path[->,bend right=15] (F1-4) edge [above] node
  14786. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14787. \path[->,bend right=15] (F1-5) edge [right] node
  14788. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14789. \path[->,bend left=15] (C3-2) edge [left] node
  14790. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14791. \path[->,bend right=15] (x86-2) edge [left] node
  14792. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14793. \path[->,bend right=15] (x86-2-1) edge [below] node
  14794. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14795. \path[->,bend right=15] (x86-2-2) edge [left] node
  14796. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14797. \path[->,bend left=15] (x86-3) edge [above] node
  14798. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14799. \path[->,bend left=15] (x86-4) edge [right] node
  14800. {\ttfamily\footnotesize print\_x86} (x86-5);
  14801. \end{tikzpicture}
  14802. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14803. functions.}
  14804. \label{fig:Rlambda-passes}
  14805. \end{figure}
  14806. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  14807. for the compilation of \LangLam{}.
  14808. \clearpage
  14809. \section{Challenge: Optimize Closures}
  14810. \label{sec:optimize-closures}
  14811. In this chapter we compiled lexically-scoped functions into a
  14812. relatively efficient representation: flat closures. However, even this
  14813. representation comes with some overhead. For example, consider the
  14814. following program with a function \code{tail\_sum} that does not have
  14815. any free variables and where all the uses of \code{tail\_sum} are in
  14816. applications where we know that only \code{tail\_sum} is being applied
  14817. (and not any other functions).
  14818. \begin{center}
  14819. \begin{minipage}{0.95\textwidth}
  14820. {\if\edition\racketEd
  14821. \begin{lstlisting}
  14822. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  14823. (if (eq? n 0)
  14824. s
  14825. (tail_sum (- n 1) (+ n s))))
  14826. (+ (tail_sum 3 0) 36)
  14827. \end{lstlisting}
  14828. \fi}
  14829. {\if\edition\pythonEd
  14830. \begin{lstlisting}
  14831. def tail_sum(n : int, s : int) -> int:
  14832. if n == 0:
  14833. return s
  14834. else:
  14835. return tail_sum(n - 1, n + s)
  14836. print( tail_sum(3, 0) + 36)
  14837. \end{lstlisting}
  14838. \fi}
  14839. \end{minipage}
  14840. \end{center}
  14841. As described in this chapter, we uniformly apply closure conversion to
  14842. all functions, obtaining the following output for this program.
  14843. \begin{center}
  14844. \begin{minipage}{0.95\textwidth}
  14845. {\if\edition\racketEd
  14846. \begin{lstlisting}
  14847. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  14848. (if (eq? n2 0)
  14849. s3
  14850. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  14851. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  14852. (define (main) : Integer
  14853. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  14854. ((vector-ref clos6 0) clos6 3 0)) 27))
  14855. \end{lstlisting}
  14856. \fi}
  14857. {\if\edition\pythonEd
  14858. \begin{lstlisting}
  14859. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  14860. if n_0 == 0:
  14861. return s_1
  14862. else:
  14863. return (let clos_2 = (tail_sum,)
  14864. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  14865. def main() -> int :
  14866. print((let clos_4 = (tail_sum,)
  14867. in clos_4[0](clos_4, 3, 0)) + 36)
  14868. return 0
  14869. \end{lstlisting}
  14870. \fi}
  14871. \end{minipage}
  14872. \end{center}
  14873. In the previous chapter, there would be no allocation in the program
  14874. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14875. the above program allocates memory for each closure and the calls to
  14876. \code{tail\_sum} are indirect. These two differences incur
  14877. considerable overhead in a program such as this one, where the
  14878. allocations and indirect calls occur inside a tight loop.
  14879. One might think that this problem is trivial to solve: can't we just
  14880. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  14881. and compile them to direct calls instead of treating it like a call to
  14882. a closure? We would also drop the new \code{fvs} parameter of
  14883. \code{tail\_sum}.
  14884. %
  14885. However, this problem is not so trivial because a global function may
  14886. ``escape'' and become involved in applications that also involve
  14887. closures. Consider the following example in which the application
  14888. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  14889. application, because the \code{lambda} may flow into \code{f}, but the
  14890. \code{inc} function might also flow into \code{f}.
  14891. \begin{center}
  14892. \begin{minipage}{\textwidth}
  14893. % lambda_test_30.rkt
  14894. {\if\edition\racketEd
  14895. \begin{lstlisting}
  14896. (define (inc [x : Integer]) : Integer
  14897. (+ x 1))
  14898. (let ([y (read)])
  14899. (let ([f (if (eq? (read) 0)
  14900. inc
  14901. (lambda: ([x : Integer]) : Integer (- x y)))])
  14902. (f 41)))
  14903. \end{lstlisting}
  14904. \fi}
  14905. {\if\edition\pythonEd
  14906. \begin{lstlisting}
  14907. def add1(x : int) -> int:
  14908. return x + 1
  14909. y = input_int()
  14910. g : Callable[[int], int] = lambda x: x - y
  14911. f = add1 if input_int() == 0 else g
  14912. print( f(41) )
  14913. \end{lstlisting}
  14914. \fi}
  14915. \end{minipage}
  14916. \end{center}
  14917. If a global function name is used in any way other than as the
  14918. operator in a direct call, then we say that the function
  14919. \emph{escapes}. If a global function does not escape, then we do not
  14920. need to perform closure conversion on the function.
  14921. \begin{exercise}\normalfont
  14922. Implement an auxiliary function for detecting which global
  14923. functions escape. Using that function, implement an improved version
  14924. of closure conversion that does not apply closure conversion to
  14925. global functions that do not escape but instead compiles them as
  14926. regular functions. Create several new test cases that check whether
  14927. you properly detect whether global functions escape or not.
  14928. \end{exercise}
  14929. So far we have reduced the overhead of calling global functions, but
  14930. it would also be nice to reduce the overhead of calling a
  14931. \code{lambda} when we can determine at compile time which
  14932. \code{lambda} will be called. We refer to such calls as \emph{known
  14933. calls}. Consider the following example in which a \code{lambda} is
  14934. bound to \code{f} and then applied.
  14935. {\if\edition\racketEd
  14936. % lambda_test_9.rkt
  14937. \begin{lstlisting}
  14938. (let ([y (read)])
  14939. (let ([f (lambda: ([x : Integer]) : Integer
  14940. (+ x y))])
  14941. (f 21)))
  14942. \end{lstlisting}
  14943. \fi}
  14944. {\if\edition\pythonEd
  14945. \begin{lstlisting}
  14946. y = input_int()
  14947. f : Callable[[int],int] = lambda x: x + y
  14948. print( f(21) )
  14949. \end{lstlisting}
  14950. \fi}
  14951. %
  14952. \noindent Closure conversion compiles the application
  14953. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  14954. %
  14955. {\if\edition\racketEd
  14956. \begin{lstlisting}
  14957. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  14958. (let ([y2 (vector-ref fvs6 1)])
  14959. (+ x3 y2)))
  14960. (define (main) : Integer
  14961. (let ([y2 (read)])
  14962. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  14963. ((vector-ref f4 0) f4 21))))
  14964. \end{lstlisting}
  14965. \fi}
  14966. {\if\edition\pythonEd
  14967. \begin{lstlisting}
  14968. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  14969. y_1 = fvs_4[1]
  14970. return x_2 + y_1[0]
  14971. def main() -> int:
  14972. y_1 = (777,)
  14973. y_1[0] = input_int()
  14974. f_0 = (lambda_3, y_1)
  14975. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  14976. return 0
  14977. \end{lstlisting}
  14978. \fi}
  14979. %
  14980. \noindent but we can instead compile the application
  14981. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  14982. %
  14983. {\if\edition\racketEd
  14984. \begin{lstlisting}
  14985. (define (main) : Integer
  14986. (let ([y2 (read)])
  14987. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  14988. ((fun-ref lambda5 1) f4 21))))
  14989. \end{lstlisting}
  14990. \fi}
  14991. {\if\edition\pythonEd
  14992. \begin{lstlisting}
  14993. def main() -> int:
  14994. y_1 = (777,)
  14995. y_1[0] = input_int()
  14996. f_0 = (lambda_3, y_1)
  14997. print(lambda_3(f_0, 21))
  14998. return 0
  14999. \end{lstlisting}
  15000. \fi}
  15001. The problem of determining which \code{lambda} will be called from a
  15002. particular application is quite challenging in general and the topic
  15003. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15004. following exercise we recommend that you compile an application to a
  15005. direct call when the operator is a variable and \racket{the variable
  15006. is \code{let}-bound to a closure} \python{the previous assignment to
  15007. the variable is a closure}. This can be accomplished by maintaining
  15008. an environment mapping variables to function names. Extend the
  15009. environment whenever you encounter a closure on the right-hand side of
  15010. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15011. name of the global function for the closure. This pass should come
  15012. after closure conversion.
  15013. \begin{exercise}\normalfont
  15014. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15015. compiles known calls into direct calls. Verify that your compiler is
  15016. successful in this regard on several example programs.
  15017. \end{exercise}
  15018. These exercises only scratches the surface of optimizing of
  15019. closures. A good next step for the interested reader is to look at the
  15020. work of \citet{Keep:2012ab}.
  15021. \section{Further Reading}
  15022. The notion of lexically scoped functions predates modern computers by
  15023. about a decade. They were invented by \citet{Church:1932aa}, who
  15024. proposed the lambda calculus as a foundation for logic. Anonymous
  15025. functions were included in the LISP~\citep{McCarthy:1960dz}
  15026. programming language but were initially dynamically scoped. The Scheme
  15027. dialect of LISP adopted lexical scoping and
  15028. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15029. Scheme programs. However, environments were represented as linked
  15030. lists, so variable lookup was linear in the size of the
  15031. environment. In this chapter we represent environments using flat
  15032. closures, which were invented by
  15033. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15034. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15035. closures, variable lookup is constant time but the time to create a
  15036. closure is proportional to the number of its free variables. Flat
  15037. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15038. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15039. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15040. \chapter{Dynamic Typing}
  15041. \label{ch:Ldyn}
  15042. \index{subject}{dynamic typing}
  15043. In this chapter we discuss the compilation of \LangDyn{}, a
  15044. dynamically typed language that is a subset of
  15045. \racket{Racket}\python{Python}. The dynamic typing is in contrast to
  15046. the previous chapters, which have studied the compilation of
  15047. statically typed languages. In dynamically typed languages such as
  15048. \LangDyn{}, a particular expression may produce a value of a different
  15049. type each time it is executed. Consider the following example with a
  15050. conditional \code{if} expression that may return a Boolean or an
  15051. integer depending on the input to the program.
  15052. % part of dynamic_test_25.rkt
  15053. {\if\edition\racketEd
  15054. \begin{lstlisting}
  15055. (not (if (eq? (read) 1) #f 0))
  15056. \end{lstlisting}
  15057. \fi}
  15058. {\if\edition\pythonEd
  15059. \begin{lstlisting}
  15060. not (False if input_int() == 1 else 0)
  15061. \end{lstlisting}
  15062. \fi}
  15063. Languages that allow expressions to produce different kinds of values
  15064. are called \emph{polymorphic}, a word composed of the Greek roots
  15065. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  15066. are several kinds of polymorphism in programming languages, such as
  15067. subtype polymorphism and parametric
  15068. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15069. study in this chapter does not have a special name but it is the kind
  15070. that arises in dynamically typed languages.
  15071. Another characteristic of dynamically typed languages is that
  15072. primitive operations, such as \code{not}, are often defined to operate
  15073. on many different types of values. In fact, in
  15074. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15075. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15076. given anything else it returns \FALSE{}.
  15077. Furthermore, even when primitive operations restrict their inputs to
  15078. values of a certain type, this restriction is enforced at runtime
  15079. instead of during compilation. For example, the tuple read
  15080. operation
  15081. \racket{\code{(vector-ref \#t 0)}}
  15082. \python{\code{True[0]}}
  15083. results in a run-time error because the first argument must
  15084. be a tuple, not a Boolean.
  15085. \begin{figure}[tp]
  15086. \centering
  15087. \fbox{
  15088. \begin{minipage}{0.97\textwidth}
  15089. {\if\edition\racketEd
  15090. \[
  15091. \begin{array}{rcl}
  15092. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  15093. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  15094. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  15095. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  15096. &\MID& \key{\#t} \MID \key{\#f}
  15097. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  15098. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  15099. \MID \CUNIOP{\key{not}}{\Exp} \\
  15100. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15101. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  15102. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  15103. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  15104. &\MID& \LP\Exp \; \Exp\ldots\RP
  15105. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15106. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15107. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15108. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  15109. \LangDynM{} &::=& \Def\ldots\; \Exp
  15110. \end{array}
  15111. \]
  15112. \fi}
  15113. {\if\edition\pythonEd
  15114. \[
  15115. \begin{array}{rcl}
  15116. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15117. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15118. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15119. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15120. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15121. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15122. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15123. \MID \CLEN{\Exp} \\
  15124. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15125. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15126. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15127. \MID \Var\mathop{\key{=}}\Exp \\
  15128. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15129. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15130. &\MID& \CRETURN{\Exp} \\
  15131. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15132. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15133. \end{array}
  15134. \]
  15135. \fi}
  15136. \end{minipage}
  15137. }
  15138. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15139. \label{fig:r7-concrete-syntax}
  15140. \end{figure}
  15141. \begin{figure}[tp]
  15142. \centering
  15143. \fbox{
  15144. \begin{minipage}{0.96\textwidth}
  15145. \small
  15146. {\if\edition\racketEd
  15147. \[
  15148. \begin{array}{lcl}
  15149. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  15150. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  15151. &\MID& \BOOL{\itm{bool}}
  15152. \MID \IF{\Exp}{\Exp}{\Exp} \\
  15153. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  15154. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15155. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  15156. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15157. \end{array}
  15158. \]
  15159. \fi}
  15160. {\if\edition\pythonEd
  15161. \[
  15162. \begin{array}{rcl}
  15163. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15164. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15165. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15166. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15167. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15168. &\MID & \code{Is()} \\
  15169. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15170. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15171. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15172. \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp}
  15173. \MID \VAR{\Var{}} \\
  15174. &\MID& \BOOL{\itm{bool}}
  15175. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15176. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15177. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15178. &\MID& \LEN{\Exp} \\
  15179. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15180. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15181. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15182. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15183. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15184. &\MID& \RETURN{\Exp} \\
  15185. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15186. \Def &::=& \FUNDEF{\Var}{\Params}{\_}{}{\Stmt^{+}} \\
  15187. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15188. \end{array}
  15189. \]
  15190. \fi}
  15191. \end{minipage}
  15192. }
  15193. \caption{The abstract syntax of \LangDyn{}.}
  15194. \label{fig:r7-syntax}
  15195. \end{figure}
  15196. The concrete and abstract syntax of \LangDyn{} is defined in
  15197. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15198. %
  15199. There is no type checker for \LangDyn{} because it is not a statically
  15200. typed language.
  15201. The definitional interpreter for \LangDyn{} is presented in
  15202. \racket{Figure~\ref{fig:interp-Ldyn}}
  15203. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15204. and its auxiliary functions are defined in
  15205. Figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15206. \INT{n}. Instead of simply returning the integer \code{n} (as
  15207. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15208. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15209. value} that combines an underlying value with a tag that identifies
  15210. what kind of value it is. We define the following \racket{struct}\python{class}
  15211. to represented tagged values.
  15212. %
  15213. {\if\edition\racketEd
  15214. \begin{lstlisting}
  15215. (struct Tagged (value tag) #:transparent)
  15216. \end{lstlisting}
  15217. \fi}
  15218. {\if\edition\pythonEd
  15219. \begin{minipage}{\textwidth}
  15220. \begin{lstlisting}
  15221. @dataclass(eq=True)
  15222. class Tagged(Value):
  15223. value : Value
  15224. tag : str
  15225. __match_args__ = ("value", "tag")
  15226. def __str__(self):
  15227. return str(self.value)
  15228. \end{lstlisting}
  15229. \end{minipage}
  15230. \fi}
  15231. %
  15232. \racket{The tags are \code{Integer}, \code{Boolean}, \code{Void},
  15233. \code{Vector}, and \code{Procedure}.}
  15234. %
  15235. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15236. \code{'tuple'}, and \code{'function'}.}
  15237. %
  15238. Tags are closely related to types but don't always capture all the
  15239. information that a type does.
  15240. %
  15241. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15242. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15243. Any)} is tagged with \code{Procedure}.}
  15244. %
  15245. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15246. is tagged with \code{'tuple'} and a function of type
  15247. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15248. is tagged with \code{'function'}.}
  15249. Next consider the match case for accessing the element of a tuple.
  15250. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15251. (Figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15252. argument is a tuple and the second is an integer.
  15253. \racket{
  15254. If they are not, a \code{trapped-error} is raised. Recall from
  15255. Section~\ref{sec:interp_Lint} that when a definition interpreter
  15256. raises a \code{trapped-error} error, the compiled code must also
  15257. signal an error by exiting with return code \code{255}. A
  15258. \code{trapped-error} is also raised if the index is not less than
  15259. length of the vector.
  15260. }
  15261. %
  15262. \python{If they are not, an exception is raised. The compiled code
  15263. must also signal an error by exiting with return code \code{255}. A
  15264. exception is also raised if the index is not less than length of the
  15265. tuple.}
  15266. \begin{figure}[tbp]
  15267. {\if\edition\racketEd
  15268. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15269. (define ((interp-Rdyn-exp env) ast)
  15270. (define recur (interp-Rdyn-exp env))
  15271. (match ast
  15272. [(Var x) (lookup x env)]
  15273. [(Int n) (Tagged n 'Integer)]
  15274. [(Bool b) (Tagged b 'Boolean)]
  15275. [(Lambda xs rt body)
  15276. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15277. [(Prim 'vector es)
  15278. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15279. [(Prim 'vector-ref (list e1 e2))
  15280. (define vec (recur e1)) (define i (recur e2))
  15281. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15282. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15283. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15284. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15285. [(Prim 'vector-set! (list e1 e2 e3))
  15286. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15287. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15288. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15289. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15290. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15291. (Tagged (void) 'Void)]
  15292. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  15293. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15294. [(Prim 'or (list e1 e2))
  15295. (define v1 (recur e1))
  15296. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15297. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15298. [(Prim op (list e1))
  15299. #:when (set-member? type-predicates op)
  15300. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15301. [(Prim op es)
  15302. (define args (map recur es))
  15303. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15304. (unless (for/or ([expected-tags (op-tags op)])
  15305. (equal? expected-tags tags))
  15306. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15307. (tag-value
  15308. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15309. [(If q t f)
  15310. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15311. [(Apply f es)
  15312. (define new-f (recur f)) (define args (map recur es))
  15313. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15314. (match f-val
  15315. [`(function ,xs ,body ,lam-env)
  15316. (unless (eq? (length xs) (length args))
  15317. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15318. (define new-env (append (map cons xs args) lam-env))
  15319. ((interp-Rdyn-exp new-env) body)]
  15320. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  15321. \end{lstlisting}
  15322. \fi}
  15323. {\if\edition\pythonEd
  15324. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15325. class InterpLdyn(InterpLlambda):
  15326. def interp_exp(self, e, env):
  15327. match e:
  15328. case Constant(n):
  15329. return self.tag(super().interp_exp(e, env))
  15330. case Tuple(es, Load()):
  15331. return self.tag(super().interp_exp(e, env))
  15332. case Lambda(params, body):
  15333. return self.tag(super().interp_exp(e, env))
  15334. case Call(Name('input_int'), []):
  15335. return self.tag(super().interp_exp(e, env))
  15336. case BinOp(left, Add(), right):
  15337. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15338. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15339. case BinOp(left, Sub(), right):
  15340. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15341. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15342. case UnaryOp(USub(), e1):
  15343. v = self.interp_exp(e1, env)
  15344. return self.tag(- self.untag(v, 'int', e))
  15345. case IfExp(test, body, orelse):
  15346. v = self.interp_exp(test, env)
  15347. match self.untag(v, 'bool', e):
  15348. case True:
  15349. return self.interp_exp(body, env)
  15350. case False:
  15351. return self.interp_exp(orelse, env)
  15352. case UnaryOp(Not(), e1):
  15353. v = self.interp_exp(e1, env)
  15354. return self.tag(not self.untag(v, 'bool', e))
  15355. case BoolOp(And(), values):
  15356. left = values[0]; right = values[1]
  15357. l = self.interp_exp(left, env)
  15358. match self.untag(l, 'bool', e):
  15359. case True:
  15360. return self.interp_exp(right, env)
  15361. case False:
  15362. return self.tag(False)
  15363. case BoolOp(Or(), values):
  15364. left = values[0]; right = values[1]
  15365. l = self.interp_exp(left, env)
  15366. match self.untag(l, 'bool', e):
  15367. case True:
  15368. return True
  15369. case False:
  15370. return self.interp_exp(right, env)
  15371. case Compare(left, [cmp], [right]):
  15372. l = self.interp_exp(left, env)
  15373. r = self.interp_exp(right, env)
  15374. if l.tag == r.tag:
  15375. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  15376. else:
  15377. raise Exception('interp Compare unexpected ' \
  15378. + repr(l) + ' ' + repr(r))
  15379. case Subscript(tup, index, Load()):
  15380. t = self.interp_exp(tup, env)
  15381. n = self.interp_exp(index, env)
  15382. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  15383. case Call(Name('len'), [tup]):
  15384. t = self.interp_exp(tup, env)
  15385. return self.tag(len(self.untag(t, 'tuple', e)))
  15386. case _:
  15387. return super().interp_exp(e, env)
  15388. \end{lstlisting}
  15389. \fi}
  15390. \caption{Interpreter for the \LangDyn{} language \python{, part 1}.}
  15391. \label{fig:interp-Ldyn}
  15392. \end{figure}
  15393. \begin{figure}[tbp]
  15394. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15395. class InterpLdyn(InterpLlambda):
  15396. def interp_stmts(self, ss, env):
  15397. if len(ss) == 0:
  15398. return
  15399. match ss[0]:
  15400. case If(test, body, orelse):
  15401. v = self.interp_exp(test, env)
  15402. match self.untag(v, 'bool', ss[0]):
  15403. case True:
  15404. return self.interp_stmts(body + ss[1:], env)
  15405. case False:
  15406. return self.interp_stmts(orelse + ss[1:], env)
  15407. case While(test, body, []):
  15408. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  15409. self.interp_stmts(body, env)
  15410. return self.interp_stmts(ss[1:], env)
  15411. case Assign([Subscript(tup, index)], value):
  15412. tup = self.interp_exp(tup, env)
  15413. index = self.interp_exp(index, env)
  15414. tup_v = self.untag(tup, 'tuple', ss[0])
  15415. index_v = self.untag(index, 'int', ss[0])
  15416. tup_v[index_v] = self.interp_exp(value, env)
  15417. return self.interp_stmts(ss[1:], env)
  15418. case FunctionDef(name, params, bod, dl, returns, comment):
  15419. ps = [x for (x,t) in params]
  15420. env[name] = self.tag(Function(name, ps, bod, env))
  15421. return self.interp_stmts(ss[1:], env)
  15422. case _:
  15423. return super().interp_stmts(ss, env)
  15424. \end{lstlisting}
  15425. \caption{Interpreter for the \LangDyn{} language \python{, part 2}.}
  15426. \label{fig:interp-Ldyn-2}
  15427. \end{figure}
  15428. \begin{figure}[tbp]
  15429. {\if\edition\racketEd
  15430. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15431. (define (interp-op op)
  15432. (match op
  15433. ['+ fx+]
  15434. ['- fx-]
  15435. ['read read-fixnum]
  15436. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  15437. ['< (lambda (v1 v2)
  15438. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  15439. ['<= (lambda (v1 v2)
  15440. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  15441. ['> (lambda (v1 v2)
  15442. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  15443. ['>= (lambda (v1 v2)
  15444. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  15445. ['boolean? boolean?]
  15446. ['integer? fixnum?]
  15447. ['void? void?]
  15448. ['vector? vector?]
  15449. ['vector-length vector-length]
  15450. ['procedure? (match-lambda
  15451. [`(functions ,xs ,body ,env) #t] [else #f])]
  15452. [else (error 'interp-op "unknown operator" op)]))
  15453. (define (op-tags op)
  15454. (match op
  15455. ['+ '((Integer Integer))]
  15456. ['- '((Integer Integer) (Integer))]
  15457. ['read '(())]
  15458. ['not '((Boolean))]
  15459. ['< '((Integer Integer))]
  15460. ['<= '((Integer Integer))]
  15461. ['> '((Integer Integer))]
  15462. ['>= '((Integer Integer))]
  15463. ['vector-length '((Vector))]))
  15464. (define type-predicates
  15465. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15466. (define (tag-value v)
  15467. (cond [(boolean? v) (Tagged v 'Boolean)]
  15468. [(fixnum? v) (Tagged v 'Integer)]
  15469. [(procedure? v) (Tagged v 'Procedure)]
  15470. [(vector? v) (Tagged v 'Vector)]
  15471. [(void? v) (Tagged v 'Void)]
  15472. [else (error 'tag-value "unidentified value ~a" v)]))
  15473. (define (check-tag val expected ast)
  15474. (define tag (Tagged-tag val))
  15475. (unless (eq? tag expected)
  15476. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15477. \end{lstlisting}
  15478. \fi}
  15479. {\if\edition\pythonEd
  15480. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15481. class InterpLdyn(InterpLlambda):
  15482. def tag(self, v):
  15483. if v is True or v is False:
  15484. return Tagged(v, 'bool')
  15485. elif isinstance(v, int):
  15486. return Tagged(v, 'int')
  15487. elif isinstance(v, Function):
  15488. return Tagged(v, 'function')
  15489. elif isinstance(v, list):
  15490. return Tagged(v, 'tuple')
  15491. elif isinstance(v, type(None)):
  15492. return Tagged(v, 'none')
  15493. else:
  15494. raise Exception('tag: unexpected ' + repr(v))
  15495. def untag(self, v, expected_tag, ast):
  15496. match v:
  15497. case Tagged(val, tag):
  15498. if tag != expected_tag:
  15499. raise Exception('expected tag ' + expected_tag + ', not ' + ' ' + repr(v))
  15500. return val
  15501. case _:
  15502. raise Exception('expected Tagged value with ' + expected_tag + ', not ' + ' ' + repr(v))
  15503. def apply_fun(self, fun, args, e):
  15504. f = self.untag(fun, 'function', e)
  15505. return super().apply_fun(f, args, e)
  15506. \end{lstlisting}
  15507. \fi}
  15508. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15509. \label{fig:interp-Ldyn-aux}
  15510. \end{figure}
  15511. \clearpage
  15512. \section{Representation of Tagged Values}
  15513. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15514. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15515. values at the bit level. Because almost every operation in \LangDyn{}
  15516. involves manipulating tagged values, the representation must be
  15517. efficient. Recall that all of our values are 64 bits. We shall steal
  15518. the 3 right-most bits to encode the tag. We use $001$ to identify
  15519. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  15520. and $101$ for the void value. We define the following auxiliary
  15521. function for mapping types to tag codes.
  15522. {\if\edition\racketEd
  15523. \begin{align*}
  15524. \itm{tagof}(\key{Integer}) &= 001 \\
  15525. \itm{tagof}(\key{Boolean}) &= 100 \\
  15526. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  15527. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  15528. \itm{tagof}(\key{Void}) &= 101
  15529. \end{align*}
  15530. \fi}
  15531. {\if\edition\pythonEd
  15532. \begin{align*}
  15533. \itm{tagof}(\key{IntType()}) &= 001 \\
  15534. \itm{tagof}(\key{BoolType()}) &= 100 \\
  15535. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  15536. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  15537. \itm{tagof}(\key{type(None)}) &= 101
  15538. \end{align*}
  15539. \fi}
  15540. This stealing of 3 bits comes at some price: our integers are reduced
  15541. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  15542. affect vectors and procedures because those values are addresses, and
  15543. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15544. they are always $000$. Thus, we do not lose information by overwriting
  15545. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15546. to recover the original address.
  15547. To make tagged values into first-class entities, we can give them a
  15548. type, called \racket{\code{Any}}\python{AnyType}, and define operations
  15549. such as \code{Inject} and \code{Project} for creating and using them,
  15550. yielding the \LangAny{} intermediate language. We describe how to
  15551. compile \LangDyn{} to \LangAny{} in Section~\ref{sec:compile-r7}
  15552. but first we describe the \LangAny{} language in greater detail.
  15553. \section{The \LangAny{} Language}
  15554. \label{sec:Rany-lang}
  15555. \newcommand{\LanyASTRacket}{
  15556. \begin{array}{lcl}
  15557. \Type &::= & \key{Any} \\
  15558. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15559. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  15560. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  15561. \itm{op} &::= & \code{any-vector-length}
  15562. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15563. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15564. \MID \code{procedure?} \MID \code{void?} \\
  15565. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15566. \end{array}
  15567. }
  15568. \newcommand{\LanyASTPython}{
  15569. \begin{array}{lcl}
  15570. \Type &::= & \key{AnyType} \\
  15571. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  15572. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  15573. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  15574. \Exp & ::= & \INJECT{\Exp}{\Type} \MID \PROJECT{\Exp}{\Type} \\
  15575. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\Exp\key{, }\INT{n}}\\
  15576. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\Exp}
  15577. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  15578. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  15579. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  15580. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  15581. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  15582. \end{array}
  15583. }
  15584. \begin{figure}[tp]
  15585. \centering
  15586. \fbox{
  15587. \begin{minipage}{0.96\textwidth}
  15588. \small
  15589. {\if\edition\racketEd
  15590. \[
  15591. \begin{array}{l}
  15592. \gray{\LintOpAST} \\ \hline
  15593. \gray{\LvarASTRacket{}} \\ \hline
  15594. \gray{\LifASTRacket{}} \\ \hline
  15595. \gray{\LwhileASTRacket{}} \\ \hline
  15596. \gray{\LtupASTRacket{}} \\ \hline
  15597. \gray{\LfunASTRacket} \\ \hline
  15598. \gray{\LlambdaASTRacket} \\ \hline
  15599. \LanyASTRacket \\
  15600. \begin{array}{lcl}
  15601. %% \Type &::= & \ldots \MID \key{Any} \\
  15602. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  15603. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15604. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15605. %% \MID \code{procedure?} \MID \code{void?} \\
  15606. %% \Exp &::=& \ldots
  15607. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  15608. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15609. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  15610. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15611. \end{array}
  15612. \end{array}
  15613. \]
  15614. \fi}
  15615. {\if\edition\pythonEd
  15616. \[
  15617. \begin{array}{l}
  15618. \gray{\LintASTPython} \\ \hline
  15619. \gray{\LvarASTPython{}} \\ \hline
  15620. \gray{\LifASTPython{}} \\ \hline
  15621. \gray{\LwhileASTPython{}} \\ \hline
  15622. \gray{\LtupASTPython{}} \\ \hline
  15623. \gray{\LfunASTPython} \\ \hline
  15624. \gray{\LlambdaASTPython} \\ \hline
  15625. \LanyASTPython \\
  15626. \begin{array}{lcl}
  15627. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15628. \end{array}
  15629. \end{array}
  15630. \]
  15631. \fi}
  15632. \end{minipage}
  15633. }
  15634. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  15635. \label{fig:Rany-syntax}
  15636. \end{figure}
  15637. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  15638. \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  15639. Figure~\ref{fig:Rany-concrete-syntax}.)} The $\INJECT{e}{T}$ form
  15640. converts the value produced by expression $e$ of type $T$ into a
  15641. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15642. produced by expression $e$ into a value of type $T$ or else halts the
  15643. program if the type tag is not equivalent to $T$.
  15644. %
  15645. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15646. restricted to a flat type $\FType$, which simplifies the
  15647. implementation and corresponds with what is needed for compiling \LangDyn{}.
  15648. The \racket{\code{any-vector}}\python{\code{any\_tuple}} operators
  15649. adapt the tuple operations so that they can be applied to a value of
  15650. type \racket{\code{Any}}{\code{AnyType}}. They also generalize the
  15651. tuple operations in that the index is not restricted to be a literal
  15652. integer in the grammar but is allowed to be any expression.
  15653. \racket{The type predicates such as
  15654. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  15655. to produce a tagged value; they return true if the tag corresponds to
  15656. the predicate and they return false otherwise.}
  15657. The type checker for \LangAny{} is shown in
  15658. Figure~\ref{fig:type-check-Rany}
  15659. %
  15660. \racket{ and uses the auxiliary functions in
  15661. Figure~\ref{fig:type-check-Rany-aux}}.
  15662. %
  15663. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and
  15664. its auxiliary functions are in Figure~\ref{fig:interp-Rany-aux}.
  15665. \begin{figure}[btp]
  15666. {\if\edition\racketEd
  15667. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15668. (define type-check-Rany_class
  15669. (class type-check-Rlambda_class
  15670. (super-new)
  15671. (inherit check-type-equal?)
  15672. (define/override (type-check-exp env)
  15673. (lambda (e)
  15674. (define recur (type-check-exp env))
  15675. (match e
  15676. [(Inject e1 ty)
  15677. (unless (flat-ty? ty)
  15678. (error 'type-check "may only inject from flat type, not ~a" ty))
  15679. (define-values (new-e1 e-ty) (recur e1))
  15680. (check-type-equal? e-ty ty e)
  15681. (values (Inject new-e1 ty) 'Any)]
  15682. [(Project e1 ty)
  15683. (unless (flat-ty? ty)
  15684. (error 'type-check "may only project to flat type, not ~a" ty))
  15685. (define-values (new-e1 e-ty) (recur e1))
  15686. (check-type-equal? e-ty 'Any e)
  15687. (values (Project new-e1 ty) ty)]
  15688. [(Prim 'any-vector-length (list e1))
  15689. (define-values (e1^ t1) (recur e1))
  15690. (check-type-equal? t1 'Any e)
  15691. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15692. [(Prim 'any-vector-ref (list e1 e2))
  15693. (define-values (e1^ t1) (recur e1))
  15694. (define-values (e2^ t2) (recur e2))
  15695. (check-type-equal? t1 'Any e)
  15696. (check-type-equal? t2 'Integer e)
  15697. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15698. [(Prim 'any-vector-set! (list e1 e2 e3))
  15699. (define-values (e1^ t1) (recur e1))
  15700. (define-values (e2^ t2) (recur e2))
  15701. (define-values (e3^ t3) (recur e3))
  15702. (check-type-equal? t1 'Any e)
  15703. (check-type-equal? t2 'Integer e)
  15704. (check-type-equal? t3 'Any e)
  15705. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15706. [(ValueOf e ty)
  15707. (define-values (new-e e-ty) (recur e))
  15708. (values (ValueOf new-e ty) ty)]
  15709. [(Prim pred (list e1))
  15710. #:when (set-member? (type-predicates) pred)
  15711. (define-values (new-e1 e-ty) (recur e1))
  15712. (check-type-equal? e-ty 'Any e)
  15713. (values (Prim pred (list new-e1)) 'Boolean)]
  15714. [(If cnd thn els)
  15715. (define-values (cnd^ Tc) (recur cnd))
  15716. (define-values (thn^ Tt) (recur thn))
  15717. (define-values (els^ Te) (recur els))
  15718. (check-type-equal? Tc 'Boolean cnd)
  15719. (check-type-equal? Tt Te e)
  15720. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  15721. [(Exit) (values (Exit) '_)]
  15722. [(Prim 'eq? (list arg1 arg2))
  15723. (define-values (e1 t1) (recur arg1))
  15724. (define-values (e2 t2) (recur arg2))
  15725. (match* (t1 t2)
  15726. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15727. [(other wise) (check-type-equal? t1 t2 e)])
  15728. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15729. [else ((super type-check-exp env) e)])))
  15730. ))
  15731. \end{lstlisting}
  15732. \fi}
  15733. {\if\edition\pythonEd
  15734. \begin{lstlisting}
  15735. class TypeCheckLany(TypeCheckLlambda):
  15736. def type_check_exp(self, e, env):
  15737. match e:
  15738. case Inject(value, typ):
  15739. self.check_exp(value, typ, env)
  15740. return AnyType()
  15741. case Project(value, typ):
  15742. self.check_exp(value, AnyType(), env)
  15743. return typ
  15744. case Call(Name('any_tuple_load'), [tup, index]):
  15745. self.check_exp(tup, AnyType(), env)
  15746. return AnyType()
  15747. case Call(Name('any_len'), [tup]):
  15748. self.check_exp(tup, AnyType(), env)
  15749. return IntType()
  15750. case Call(Name('arity'), [fun]):
  15751. ty = self.type_check_exp(fun, env)
  15752. match ty:
  15753. case FunctionType(ps, rt):
  15754. return IntType()
  15755. case TupleType([FunctionType(ps,rs)]):
  15756. return IntType()
  15757. case _:
  15758. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  15759. case Call(Name('make_any'), [value, tag]):
  15760. self.type_check_exp(value, env)
  15761. self.check_exp(tag, IntType(), env)
  15762. return AnyType()
  15763. case ValueOf(value, typ):
  15764. self.check_exp(value, AnyType(), env)
  15765. return typ
  15766. case TagOf(value):
  15767. self.check_exp(value, AnyType(), env)
  15768. return IntType()
  15769. case Call(Name('exit'), []):
  15770. return Bottom()
  15771. case AnnLambda(params, returns, body):
  15772. new_env = {x:t for (x,t) in env.items()}
  15773. for (x,t) in params:
  15774. new_env[x] = t
  15775. return_t = self.type_check_exp(body, new_env)
  15776. self.check_type_equal(returns, return_t, e)
  15777. return FunctionType([t for (x,t) in params], return_t)
  15778. case _:
  15779. return super().type_check_exp(e, env)
  15780. \end{lstlisting}
  15781. \fi}
  15782. \caption{Type checker for the \LangAny{} language.}
  15783. \label{fig:type-check-Rany}
  15784. \end{figure}
  15785. {\if\edition\racketEd
  15786. \begin{figure}[tbp]
  15787. {\if\edition\racketEd
  15788. \begin{lstlisting}
  15789. (define/override (operator-types)
  15790. (append
  15791. '((integer? . ((Any) . Boolean))
  15792. (vector? . ((Any) . Boolean))
  15793. (procedure? . ((Any) . Boolean))
  15794. (void? . ((Any) . Boolean))
  15795. (tag-of-any . ((Any) . Integer))
  15796. (make-any . ((_ Integer) . Any)))
  15797. (super operator-types)))
  15798. (define/public (type-predicates)
  15799. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15800. (define/public (combine-types t1 t2)
  15801. (match (list t1 t2)
  15802. [(list '_ t2) t2]
  15803. [(list t1 '_) t1]
  15804. [(list `(Vector ,ts1 ...)
  15805. `(Vector ,ts2 ...))
  15806. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  15807. (combine-types t1 t2)))]
  15808. [(list `(,ts1 ... -> ,rt1)
  15809. `(,ts2 ... -> ,rt2))
  15810. `(,@(for/list ([t1 ts1] [t2 ts2])
  15811. (combine-types t1 t2))
  15812. -> ,(combine-types rt1 rt2))]
  15813. [else t1]))
  15814. (define/public (flat-ty? ty)
  15815. (match ty
  15816. [(or `Integer `Boolean '_ `Void) #t]
  15817. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15818. [`(,ts ... -> ,rt)
  15819. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15820. [else #f]))
  15821. \end{lstlisting}
  15822. \fi}
  15823. \caption{Auxiliary methods for type checking \LangAny{}.}
  15824. \label{fig:type-check-Rany-aux}
  15825. \end{figure}
  15826. \fi}
  15827. \begin{figure}[btp]
  15828. {\if\edition\racketEd
  15829. \begin{lstlisting}
  15830. (define interp-Rany_class
  15831. (class interp-Rlambda_class
  15832. (super-new)
  15833. (define/override (interp-op op)
  15834. (match op
  15835. ['boolean? (match-lambda
  15836. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15837. [else #f])]
  15838. ['integer? (match-lambda
  15839. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15840. [else #f])]
  15841. ['vector? (match-lambda
  15842. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15843. [else #f])]
  15844. ['procedure? (match-lambda
  15845. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15846. [else #f])]
  15847. ['eq? (match-lambda*
  15848. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15849. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15850. [ls (apply (super interp-op op) ls)])]
  15851. ['any-vector-ref (lambda (v i)
  15852. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15853. ['any-vector-set! (lambda (v i a)
  15854. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15855. ['any-vector-length (lambda (v)
  15856. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15857. [else (super interp-op op)]))
  15858. (define/override ((interp-exp env) e)
  15859. (define recur (interp-exp env))
  15860. (match e
  15861. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15862. [(Project e ty2) (apply-project (recur e) ty2)]
  15863. [else ((super interp-exp env) e)]))
  15864. ))
  15865. (define (interp-Rany p)
  15866. (send (new interp-Rany_class) interp-program p))
  15867. \end{lstlisting}
  15868. \fi}
  15869. {\if\edition\pythonEd
  15870. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15871. class InterpLany(InterpLlambda):
  15872. def interp_exp(self, e, env):
  15873. match e:
  15874. case Inject(value, typ):
  15875. v = self.interp_exp(value, env)
  15876. return Tagged(v, self.type_to_tag(typ))
  15877. case Project(value, typ):
  15878. v = self.interp_exp(value, env)
  15879. match v:
  15880. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  15881. return val
  15882. case _:
  15883. raise Exception('interp project to ' + repr(typ) \
  15884. + ' unexpected ' + repr(v))
  15885. case Call(Name('any_tuple_load'), [tup, index]):
  15886. tv = self.interp_exp(tup, env)
  15887. n = self.interp_exp(index, env)
  15888. match tv:
  15889. case Tagged(v, tag):
  15890. return v[n]
  15891. case _:
  15892. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  15893. case Call(Name('any_tuple_store'), [tup, index, value]):
  15894. tv = self.interp_exp(tup, env)
  15895. n = self.interp_exp(index, env)
  15896. val = self.interp_exp(value, env)
  15897. match tv:
  15898. case Tagged(v, tag):
  15899. v[n] = val
  15900. return None
  15901. case _:
  15902. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  15903. case Call(Name('any_len'), [value]):
  15904. v = self.interp_exp(value, env)
  15905. match v:
  15906. case Tagged(value, tag):
  15907. return len(value)
  15908. case _:
  15909. raise Exception('interp any_len unexpected ' + repr(v))
  15910. case Call(Name('make_any'), [value, tag]):
  15911. v = self.interp_exp(value, env)
  15912. t = self.interp_exp(tag, env)
  15913. return Tagged(v, t)
  15914. case Call(Name('arity'), [fun]):
  15915. f = self.interp_exp(fun, env)
  15916. return self.arity(f)
  15917. case Call(Name('exit'), []):
  15918. trace('exiting!')
  15919. exit(0)
  15920. case TagOf(value):
  15921. v = self.interp_exp(value, env)
  15922. match v:
  15923. case Tagged(val, tag):
  15924. return tag
  15925. case _:
  15926. raise Exception('interp TagOf unexpected ' + repr(v))
  15927. case ValueOf(value, typ):
  15928. v = self.interp_exp(value, env)
  15929. match v:
  15930. case Tagged(val, tag):
  15931. return val
  15932. case _:
  15933. raise Exception('interp ValueOf unexpected ' + repr(v))
  15934. case AnnLambda(params, returns, body):
  15935. return Function('lambda', [x for (x,t) in params], [Return(body)], env)
  15936. case _:
  15937. return super().interp_exp(e, env)
  15938. \end{lstlisting}
  15939. \fi}
  15940. \caption{Interpreter for \LangAny{}.}
  15941. \label{fig:interp-Rany}
  15942. \end{figure}
  15943. \begin{figure}[tbp]
  15944. {\if\edition\racketEd
  15945. \begin{lstlisting}
  15946. (define/public (apply-inject v tg) (Tagged v tg))
  15947. (define/public (apply-project v ty2)
  15948. (define tag2 (any-tag ty2))
  15949. (match v
  15950. [(Tagged v1 tag1)
  15951. (cond
  15952. [(eq? tag1 tag2)
  15953. (match ty2
  15954. [`(Vector ,ts ...)
  15955. (define l1 ((interp-op 'vector-length) v1))
  15956. (cond
  15957. [(eq? l1 (length ts)) v1]
  15958. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  15959. l1 (length ts))])]
  15960. [`(,ts ... -> ,rt)
  15961. (match v1
  15962. [`(function ,xs ,body ,env)
  15963. (cond [(eq? (length xs) (length ts)) v1]
  15964. [else
  15965. (error 'apply-project "arity mismatch ~a != ~a"
  15966. (length xs) (length ts))])]
  15967. [else (error 'apply-project "expected function not ~a" v1)])]
  15968. [else v1])]
  15969. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  15970. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  15971. \end{lstlisting}
  15972. \fi}
  15973. {\if\edition\pythonEd
  15974. \begin{lstlisting}
  15975. class InterpLany(InterpLlambda):
  15976. def type_to_tag(self, typ):
  15977. match typ:
  15978. case FunctionType(params, rt):
  15979. return 'function'
  15980. case TupleType(fields):
  15981. return 'tuple'
  15982. case t if t == int:
  15983. return 'int'
  15984. case t if t == bool:
  15985. return 'bool'
  15986. case IntType():
  15987. return 'int'
  15988. case BoolType():
  15989. return 'int'
  15990. case _:
  15991. raise Exception('type_to_tag unexpected ' + repr(typ))
  15992. def arity(self, v):
  15993. match v:
  15994. case Function(name, params, body, env):
  15995. return len(params)
  15996. case ClosureTuple(args, arity):
  15997. return arity
  15998. case _:
  15999. raise Exception('Lany arity unexpected ' + repr(v))
  16000. \end{lstlisting}
  16001. \fi}
  16002. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16003. \label{fig:interp-Rany-aux}
  16004. \end{figure}
  16005. \clearpage
  16006. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16007. \label{sec:compile-r7}
  16008. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16009. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  16010. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  16011. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  16012. an expression $e'$ in \LangAny{} that has type \ANYTY{}. For example, the
  16013. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  16014. the Boolean \TRUE{}, which must be injected to produce an
  16015. expression of type \ANYTY{}.
  16016. %
  16017. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  16018. addition, is representative of compilation for many primitive
  16019. operations: the arguments have type \ANYTY{} and must be projected to
  16020. \INTTYPE{} before the addition can be performed.
  16021. The compilation of \key{lambda} (third row of
  16022. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  16023. produce type annotations: we simply use \ANYTY{}.
  16024. %
  16025. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16026. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16027. this pass has to account for some differences in behavior between
  16028. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16029. permissive than \LangAny{} regarding what kind of values can be used
  16030. in various places. For example, the condition of an \key{if} does
  16031. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16032. of the same type (in that case the result is \code{\#f}).}
  16033. \begin{figure}[btp]
  16034. \centering
  16035. {\if\edition\racketEd
  16036. \begin{tabular}{|lll|} \hline
  16037. \begin{minipage}{0.27\textwidth}
  16038. \begin{lstlisting}
  16039. #t
  16040. \end{lstlisting}
  16041. \end{minipage}
  16042. &
  16043. $\Rightarrow$
  16044. &
  16045. \begin{minipage}{0.65\textwidth}
  16046. \begin{lstlisting}
  16047. (inject #t Boolean)
  16048. \end{lstlisting}
  16049. \end{minipage}
  16050. \\[2ex]\hline
  16051. \begin{minipage}{0.27\textwidth}
  16052. \begin{lstlisting}
  16053. (+ |$e_1$| |$e_2$|)
  16054. \end{lstlisting}
  16055. \end{minipage}
  16056. &
  16057. $\Rightarrow$
  16058. &
  16059. \begin{minipage}{0.65\textwidth}
  16060. \begin{lstlisting}
  16061. (inject
  16062. (+ (project |$e'_1$| Integer)
  16063. (project |$e'_2$| Integer))
  16064. Integer)
  16065. \end{lstlisting}
  16066. \end{minipage}
  16067. \\[2ex]\hline
  16068. \begin{minipage}{0.27\textwidth}
  16069. \begin{lstlisting}
  16070. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  16071. \end{lstlisting}
  16072. \end{minipage}
  16073. &
  16074. $\Rightarrow$
  16075. &
  16076. \begin{minipage}{0.65\textwidth}
  16077. \begin{lstlisting}
  16078. (inject
  16079. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  16080. (Any|$\ldots$|Any -> Any))
  16081. \end{lstlisting}
  16082. \end{minipage}
  16083. \\[2ex]\hline
  16084. \begin{minipage}{0.27\textwidth}
  16085. \begin{lstlisting}
  16086. (|$e_0$| |$e_1 \ldots e_n$|)
  16087. \end{lstlisting}
  16088. \end{minipage}
  16089. &
  16090. $\Rightarrow$
  16091. &
  16092. \begin{minipage}{0.65\textwidth}
  16093. \begin{lstlisting}
  16094. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16095. \end{lstlisting}
  16096. \end{minipage}
  16097. \\[2ex]\hline
  16098. \begin{minipage}{0.27\textwidth}
  16099. \begin{lstlisting}
  16100. (vector-ref |$e_1$| |$e_2$|)
  16101. \end{lstlisting}
  16102. \end{minipage}
  16103. &
  16104. $\Rightarrow$
  16105. &
  16106. \begin{minipage}{0.65\textwidth}
  16107. \begin{lstlisting}
  16108. (any-vector-ref |$e_1'$| |$e_2'$|)
  16109. \end{lstlisting}
  16110. \end{minipage}
  16111. \\[2ex]\hline
  16112. \begin{minipage}{0.27\textwidth}
  16113. \begin{lstlisting}
  16114. (if |$e_1$| |$e_2$| |$e_3$|)
  16115. \end{lstlisting}
  16116. \end{minipage}
  16117. &
  16118. $\Rightarrow$
  16119. &
  16120. \begin{minipage}{0.65\textwidth}
  16121. \begin{lstlisting}
  16122. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16123. \end{lstlisting}
  16124. \end{minipage}
  16125. \\[2ex]\hline
  16126. \begin{minipage}{0.27\textwidth}
  16127. \begin{lstlisting}
  16128. (eq? |$e_1$| |$e_2$|)
  16129. \end{lstlisting}
  16130. \end{minipage}
  16131. &
  16132. $\Rightarrow$
  16133. &
  16134. \begin{minipage}{0.65\textwidth}
  16135. \begin{lstlisting}
  16136. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16137. \end{lstlisting}
  16138. \end{minipage}
  16139. \\[2ex]\hline
  16140. \begin{minipage}{0.27\textwidth}
  16141. \begin{lstlisting}
  16142. (not |$e_1$|)
  16143. \end{lstlisting}
  16144. \end{minipage}
  16145. &
  16146. $\Rightarrow$
  16147. &
  16148. \begin{minipage}{0.65\textwidth}
  16149. \begin{lstlisting}
  16150. (if (eq? |$e'_1$| (inject #f Boolean))
  16151. (inject #t Boolean) (inject #f Boolean))
  16152. \end{lstlisting}
  16153. \end{minipage}
  16154. \\[2ex]\hline
  16155. \end{tabular}
  16156. \fi}
  16157. {\if\edition\pythonEd
  16158. \begin{tabular}{|lll|} \hline
  16159. \begin{minipage}{0.22\textwidth}
  16160. \begin{lstlisting}
  16161. True
  16162. \end{lstlisting}
  16163. \end{minipage}
  16164. &
  16165. $\Rightarrow$
  16166. &
  16167. \begin{minipage}{0.7\textwidth}
  16168. \begin{lstlisting}
  16169. Inject(True, BoolType())
  16170. \end{lstlisting}
  16171. \end{minipage}
  16172. \\[2ex]\hline
  16173. \begin{minipage}{0.22\textwidth}
  16174. \begin{lstlisting}
  16175. |$e_1$| + |$e_2$|
  16176. \end{lstlisting}
  16177. \end{minipage}
  16178. &
  16179. $\Rightarrow$
  16180. &
  16181. \begin{minipage}{0.7\textwidth}
  16182. \begin{lstlisting}
  16183. Inject(Project(|$e'_1$|, IntType())
  16184. + Project(|$e'_2$|, IntType()),
  16185. IntType())
  16186. \end{lstlisting}
  16187. \end{minipage}
  16188. \\[2ex]\hline
  16189. \begin{minipage}{0.22\textwidth}
  16190. \begin{lstlisting}
  16191. lambda |$x_1 \ldots x_n$|: |$e$|
  16192. \end{lstlisting}
  16193. \end{minipage}
  16194. &
  16195. $\Rightarrow$
  16196. &
  16197. \begin{minipage}{0.7\textwidth}
  16198. \begin{lstlisting}
  16199. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|,(|$x_n$|,AnyType)], |$e'$|)
  16200. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16201. \end{lstlisting}
  16202. \end{minipage}
  16203. \\[2ex]\hline
  16204. \begin{minipage}{0.22\textwidth}
  16205. \begin{lstlisting}
  16206. |$e_0$|(|$e_1 \ldots e_n$|)
  16207. \end{lstlisting}
  16208. \end{minipage}
  16209. &
  16210. $\Rightarrow$
  16211. &
  16212. \begin{minipage}{0.7\textwidth}
  16213. \begin{lstlisting}
  16214. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16215. AnyType())), |$e'_1, \ldots, e'_n$|)
  16216. \end{lstlisting}
  16217. \end{minipage}
  16218. \\[2ex]\hline
  16219. \begin{minipage}{0.22\textwidth}
  16220. \begin{lstlisting}
  16221. |$e_1$|[|$e_2$|]
  16222. \end{lstlisting}
  16223. \end{minipage}
  16224. &
  16225. $\Rightarrow$
  16226. &
  16227. \begin{minipage}{0.7\textwidth}
  16228. \begin{lstlisting}
  16229. Call('any_tuple_load',[|$e_1'$|, |$e_2'$|])
  16230. \end{lstlisting}
  16231. \end{minipage}
  16232. \\[2ex]\hline
  16233. %% \begin{minipage}{0.22\textwidth}
  16234. %% \begin{lstlisting}
  16235. %% |$e_2$| if |$e_1$| else |$e_3$|
  16236. %% \end{lstlisting}
  16237. %% \end{minipage}
  16238. %% &
  16239. %% $\Rightarrow$
  16240. %% &
  16241. %% \begin{minipage}{0.7\textwidth}
  16242. %% \begin{lstlisting}
  16243. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16244. %% \end{lstlisting}
  16245. %% \end{minipage}
  16246. %% \\[2ex]\hline
  16247. %% \begin{minipage}{0.22\textwidth}
  16248. %% \begin{lstlisting}
  16249. %% (eq? |$e_1$| |$e_2$|)
  16250. %% \end{lstlisting}
  16251. %% \end{minipage}
  16252. %% &
  16253. %% $\Rightarrow$
  16254. %% &
  16255. %% \begin{minipage}{0.7\textwidth}
  16256. %% \begin{lstlisting}
  16257. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16258. %% \end{lstlisting}
  16259. %% \end{minipage}
  16260. %% \\[2ex]\hline
  16261. %% \begin{minipage}{0.22\textwidth}
  16262. %% \begin{lstlisting}
  16263. %% (not |$e_1$|)
  16264. %% \end{lstlisting}
  16265. %% \end{minipage}
  16266. %% &
  16267. %% $\Rightarrow$
  16268. %% &
  16269. %% \begin{minipage}{0.7\textwidth}
  16270. %% \begin{lstlisting}
  16271. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16272. %% (inject #t Boolean) (inject #f Boolean))
  16273. %% \end{lstlisting}
  16274. %% \end{minipage}
  16275. %% \\[2ex]\hline
  16276. \end{tabular}
  16277. \fi}
  16278. \caption{Cast Insertion}
  16279. \label{fig:compile-r7-Rany}
  16280. \end{figure}
  16281. \section{Reveal Casts}
  16282. \label{sec:reveal-casts-Rany}
  16283. % TODO: define R'_6
  16284. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16285. into a conditional expression that checks whether the value's tag
  16286. matches the target type; if it does, the value is converted to a value
  16287. of the target type by removing the tag; if it does not, the program
  16288. exits.
  16289. %
  16290. {\if\edition\racketEd
  16291. %
  16292. To perform these actions we need a new primitive operation,
  16293. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16294. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16295. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16296. underlying value from a tagged value. The \code{ValueOf} form
  16297. includes the type for the underlying value which is used by the type
  16298. checker. Finally, the \code{Exit} form ends the execution of the
  16299. program.
  16300. %
  16301. \fi}
  16302. %
  16303. {\if\edition\pythonEd
  16304. %
  16305. To perform these actions we need the \code{exit} function (from the C
  16306. standard library) and two new AST classes: \code{TagOf} and
  16307. \code{ValueOf}. The \code{exit} function ends the execution of the
  16308. program. The \code{TagOf} operation retrieves the type tag from a
  16309. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16310. the underlying value from a tagged value. The \code{ValueOf}
  16311. operation includes the type for the underlying value which is used by
  16312. the type checker.
  16313. %
  16314. \fi}
  16315. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16316. \code{Project} can be translated as follows.
  16317. \begin{center}
  16318. \begin{minipage}{1.0\textwidth}
  16319. {\if\edition\racketEd
  16320. \begin{lstlisting}
  16321. (Project |$e$| |$\FType$|)
  16322. |$\Rightarrow$|
  16323. (Let |$\itm{tmp}$| |$e'$|
  16324. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16325. (Int |$\itm{tagof}(\FType)$|)))
  16326. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16327. (Exit)))
  16328. \end{lstlisting}
  16329. \fi}
  16330. {\if\edition\pythonEd
  16331. \begin{lstlisting}
  16332. Project(|$e$|, |$\FType$|)
  16333. |$\Rightarrow$|
  16334. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16335. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16336. [Constant(|$\itm{tagof}(\FType)$|)]),
  16337. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16338. Call(Name('exit'), [])))
  16339. \end{lstlisting}
  16340. \fi}
  16341. \end{minipage}
  16342. \end{center}
  16343. If the target type of the projection is a tuple or function type, then
  16344. there is a bit more work to do. For tuples, check that the length of
  16345. the tuple type matches the length of the tuple. For functions, check
  16346. that the number of parameters in the function type matches the
  16347. function's arity.
  16348. Regarding \code{Inject}, we recommend compiling it to a slightly
  16349. lower-level primitive operation named \code{make\_any}. This operation
  16350. takes a tag instead of a type.
  16351. \begin{center}
  16352. \begin{minipage}{1.0\textwidth}
  16353. {\if\edition\racketEd
  16354. \begin{lstlisting}
  16355. (Inject |$e$| |$\FType$|)
  16356. |$\Rightarrow$|
  16357. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16358. \end{lstlisting}
  16359. \fi}
  16360. {\if\edition\pythonEd
  16361. \begin{lstlisting}
  16362. Inject(|$e$|, |$\FType$|)
  16363. |$\Rightarrow$|
  16364. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16365. \end{lstlisting}
  16366. \fi}
  16367. \end{minipage}
  16368. \end{center}
  16369. {\if\edition\pythonEd
  16370. %
  16371. The introduction of \code{make\_any} makes it difficult to use
  16372. bidirectional type checking because we no longer have an expected type
  16373. to use for type checking the expression $e'$. Thus, we run into
  16374. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16375. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16376. annotated lambda) whose parameters have type annotations and that
  16377. records the return type.
  16378. %
  16379. \fi}
  16380. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16381. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16382. translation of \code{Project}.}
  16383. {\if\edition\racketEd
  16384. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16385. combine the projection action with the vector operation. Also, the
  16386. read and write operations allow arbitrary expressions for the index so
  16387. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany})
  16388. cannot guarantee that the index is within bounds. Thus, we insert code
  16389. to perform bounds checking at runtime. The translation for
  16390. \code{any-vector-ref} is as follows and the other two operations are
  16391. translated in a similar way.
  16392. \begin{lstlisting}
  16393. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16394. |$\Rightarrow$|
  16395. (Let |$v$| |$e'_1$|
  16396. (Let |$i$| |$e'_2$|
  16397. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16398. (If (Prim '< (list (Var |$i$|)
  16399. (Prim 'any-vector-length (list (Var |$v$|)))))
  16400. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16401. (Exit))
  16402. (Exit))))
  16403. \end{lstlisting}
  16404. \fi}
  16405. %
  16406. {\if\edition\pythonEd
  16407. %
  16408. The \code{any\_tuple\_load} operation combines the projection action
  16409. with the load operation. Also, the load operation allows arbitrary
  16410. expressions for the index so the type checker for \LangAny{}
  16411. (Figure~\ref{fig:type-check-Rany}) cannot guarantee that the index is
  16412. within bounds. Thus, we insert code to perform bounds checking at
  16413. runtime. The translation for \code{any\_tuple\_load} is as follows.
  16414. \begin{lstlisting}
  16415. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  16416. |$\Rightarrow$|
  16417. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  16418. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  16419. IfExp(Compare(|$i$|, [LtE()], [Call(Name('any_len'), [|$t$|])]),
  16420. Call(Name('any_tuple_load'), [|$t$|, |$i$|]),
  16421. Call(Name('exit'), [])),
  16422. Call(Name('exit'), [])))
  16423. \end{lstlisting}
  16424. \fi}
  16425. {\if\edition\pythonEd
  16426. \section{Assignment Conversion}
  16427. \label{sec:convert-assignments-Lany}
  16428. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16429. \code{AnnLambda} AST classes.
  16430. \section{Closure Conversion}
  16431. \label{sec:closure-conversion-Lany}
  16432. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16433. \code{AnnLambda} AST classes.
  16434. \fi}
  16435. \section{Remove Complex Operands}
  16436. \label{sec:rco-Rany}
  16437. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  16438. expressions. The subexpression of \code{ValueOf} must be atomic.}
  16439. %
  16440. \python{The \code{ValueOf} and \code{TagOf} operations are both
  16441. complex expressions. Their subexpressions must be atomic.}
  16442. \section{Explicate Control and \LangCAny{}}
  16443. \label{sec:explicate-Rany}
  16444. The output of \code{explicate\_control} is the \LangCAny{} language
  16445. whose syntax is defined in Figure~\ref{fig:c5-syntax}.
  16446. %
  16447. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  16448. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  16449. note that the index argument of \code{vector-ref} and
  16450. \code{vector-set!} is an $\Atm$ instead of an integer, as in
  16451. \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  16452. %
  16453. \python{
  16454. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  16455. and \code{explicate\_pred} as appropriately to handle the new expressions
  16456. in \LangCAny{}.
  16457. }
  16458. \newcommand{\CanyASTPython}{
  16459. \begin{array}{lcl}
  16460. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  16461. &\MID& \key{TagOf}\LP \Atm \RP
  16462. \MID \key{ValueOf}\LP \Atm , \Type \RP \\
  16463. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS \Atm,\Atm \RS}\\
  16464. &\MID& \CALL{\VAR{\key{'any\_tuple\_store'}}}{\LS \Atm,\Atm,\Atm \RS}\\
  16465. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  16466. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  16467. \end{array}
  16468. }
  16469. \begin{figure}[tp]
  16470. \fbox{
  16471. \begin{minipage}{0.96\textwidth}
  16472. \small
  16473. {\if\edition\racketEd
  16474. \[
  16475. \begin{array}{lcl}
  16476. \Exp &::= & \ldots
  16477. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  16478. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  16479. &\MID& \VALUEOF{\Exp}{\FType} \\
  16480. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  16481. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  16482. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  16483. \MID \GOTO{\itm{label}} } \\
  16484. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  16485. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  16486. \MID \LP\key{Exit}\RP \\
  16487. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  16488. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  16489. \end{array}
  16490. \]
  16491. \fi}
  16492. {\if\edition\pythonEd
  16493. \[
  16494. \begin{array}{l}
  16495. \gray{\CifASTPython} \\ \hline
  16496. \gray{\CtupASTPython} \\ \hline
  16497. \gray{\CfunASTPython} \\ \hline
  16498. \gray{\ClambdaASTPython} \\ \hline
  16499. \CanyASTPython \\
  16500. \begin{array}{lcl}
  16501. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16502. \end{array}
  16503. \end{array}
  16504. \]
  16505. \fi}
  16506. \end{minipage}
  16507. }
  16508. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:Clam-syntax}).}
  16509. \label{fig:c5-syntax}
  16510. \end{figure}
  16511. \section{Select Instructions}
  16512. \label{sec:select-Rany}
  16513. In the \code{select\_instructions} pass we translate the primitive
  16514. operations on the \ANYTY{} type to x86 instructions that manipulate
  16515. the 3 tag bits of the tagged value. In the following descriptions,
  16516. given an atom $e$ we use a primed variable $e'$ to refer to the result
  16517. of translating $e$ into an x86 argument.
  16518. \paragraph{\code{make\_any}}
  16519. We recommend compiling the \code{make\_any} operation as follows if
  16520. the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  16521. shifts the destination to the left by the number of bits specified its
  16522. source argument (in this case $3$, the length of the tag) and it
  16523. preserves the sign of the integer. We use the \key{orq} instruction to
  16524. combine the tag and the value to form the tagged value. \\
  16525. %
  16526. {\if\edition\racketEd
  16527. \begin{lstlisting}
  16528. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16529. |$\Rightarrow$|
  16530. movq |$e'$|, |\itm{lhs'}|
  16531. salq $3, |\itm{lhs'}|
  16532. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16533. \end{lstlisting}
  16534. \fi}
  16535. %
  16536. {\if\edition\pythonEd
  16537. \begin{lstlisting}
  16538. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16539. |$\Rightarrow$|
  16540. movq |$e'$|, |\itm{lhs'}|
  16541. salq $3, |\itm{lhs'}|
  16542. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16543. \end{lstlisting}
  16544. \fi}
  16545. %
  16546. The instruction selection for tuples and procedures is different
  16547. because their is no need to shift them to the left. The rightmost 3
  16548. bits are already zeros so we simply combine the value and the tag
  16549. using \key{orq}. \\
  16550. %
  16551. {\if\edition\racketEd
  16552. \begin{lstlisting}
  16553. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16554. |$\Rightarrow$|
  16555. movq |$e'$|, |\itm{lhs'}|
  16556. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16557. \end{lstlisting}
  16558. \fi}
  16559. %
  16560. {\if\edition\pythonEd
  16561. \begin{lstlisting}
  16562. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16563. |$\Rightarrow$|
  16564. movq |$e'$|, |\itm{lhs'}|
  16565. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16566. \end{lstlisting}
  16567. \fi}
  16568. \paragraph{\code{TagOf}}
  16569. Recall that the \code{TagOf} operation extracts the type tag from a
  16570. value of type \ANYTY{}. The type tag is the bottom three bits, so we
  16571. obtain the tag by taking the bitwise-and of the value with $111$ ($7$
  16572. in decimal).
  16573. %
  16574. {\if\edition\racketEd
  16575. \begin{lstlisting}
  16576. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  16577. |$\Rightarrow$|
  16578. movq |$e'$|, |\itm{lhs'}|
  16579. andq $7, |\itm{lhs'}|
  16580. \end{lstlisting}
  16581. \fi}
  16582. %
  16583. {\if\edition\pythonEd
  16584. \begin{lstlisting}
  16585. Assign([|\itm{lhs}|], TagOf(|$e$|))
  16586. |$\Rightarrow$|
  16587. movq |$e'$|, |\itm{lhs'}|
  16588. andq $7, |\itm{lhs'}|
  16589. \end{lstlisting}
  16590. \fi}
  16591. \paragraph{\code{ValueOf}}
  16592. Like \code{make\_any}, the instructions for \key{ValueOf} are
  16593. different depending on whether the type $T$ is a pointer (tuple or
  16594. function) or not (integer or Boolean). The following shows the
  16595. instruction selection for integers and Booleans. We produce an
  16596. untagged value by shifting it to the right by 3 bits.
  16597. %
  16598. {\if\edition\racketEd
  16599. \begin{lstlisting}
  16600. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16601. |$\Rightarrow$|
  16602. movq |$e'$|, |\itm{lhs'}|
  16603. sarq $3, |\itm{lhs'}|
  16604. \end{lstlisting}
  16605. \fi}
  16606. %
  16607. {\if\edition\pythonEd
  16608. \begin{lstlisting}
  16609. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16610. |$\Rightarrow$|
  16611. movq |$e'$|, |\itm{lhs'}|
  16612. sarq $3, |\itm{lhs'}|
  16613. \end{lstlisting}
  16614. \fi}
  16615. %
  16616. In the case for tuples and procedures, we just need to zero-out the
  16617. rightmost 3 bits. We accomplish this by creating the bit pattern
  16618. $\ldots 0111$ ($7$ in decimal) and apply bitwise-not to obtain $\ldots
  16619. 11111000$ (-8 in decimal) which we \code{movq} into the destination
  16620. $\itm{lhs'}$. Finally, we apply \code{andq} with the tagged value to
  16621. get the desired result.
  16622. %
  16623. {\if\edition\racketEd
  16624. \begin{lstlisting}
  16625. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16626. |$\Rightarrow$|
  16627. movq $|$-8$|, |\itm{lhs'}|
  16628. andq |$e'$|, |\itm{lhs'}|
  16629. \end{lstlisting}
  16630. \fi}
  16631. %
  16632. {\if\edition\pythonEd
  16633. \begin{lstlisting}
  16634. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16635. |$\Rightarrow$|
  16636. movq $|$-8$|, |\itm{lhs'}|
  16637. andq |$e'$|, |\itm{lhs'}|
  16638. \end{lstlisting}
  16639. \fi}
  16640. %% \paragraph{Type Predicates} We leave it to the reader to
  16641. %% devise a sequence of instructions to implement the type predicates
  16642. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  16643. \paragraph{\racket{Any-vector-length}\python{\code{any\_len}}}
  16644. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  16645. operation combines the effect of \code{ValueOf} with accessing the
  16646. length of a tuple from the tag stored at the zero index of the tuple.
  16647. {\if\edition\racketEd
  16648. \begin{lstlisting}
  16649. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  16650. |$\Longrightarrow$|
  16651. movq $|$-8$|, %r11
  16652. andq |$e_1'$|, %r11
  16653. movq 0(%r11), %r11
  16654. andq $126, %r11
  16655. sarq $1, %r11
  16656. movq %r11, |$\itm{lhs'}$|
  16657. \end{lstlisting}
  16658. \fi}
  16659. {\if\edition\pythonEd
  16660. \begin{lstlisting}
  16661. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  16662. |$\Longrightarrow$|
  16663. movq $|$-8$|, %r11
  16664. andq |$e_1'$|, %r11
  16665. movq 0(%r11), %r11
  16666. andq $126, %r11
  16667. sarq $1, %r11
  16668. movq %r11, |$\itm{lhs'}$|
  16669. \end{lstlisting}
  16670. \fi}
  16671. \paragraph{\racket{Any-vector-ref}\python{\code{\code{any\_tuple\_load}}}}
  16672. This operation combines the effect of \code{ValueOf} with reading an
  16673. element of the tuple (see
  16674. Section~\ref{sec:select-instructions-gc}). However, the index may be
  16675. an arbitrary atom so instead of computing the offset at compile time,
  16676. we must generate instructions to compute the offset at runtime as
  16677. follows. Note the use of the new instruction \code{imulq}.
  16678. \begin{center}
  16679. \begin{minipage}{0.96\textwidth}
  16680. {\if\edition\racketEd
  16681. \begin{lstlisting}
  16682. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16683. |$\Longrightarrow$|
  16684. movq |$\neg 111$|, %r11
  16685. andq |$e_1'$|, %r11
  16686. movq |$e_2'$|, %rax
  16687. addq $1, %rax
  16688. imulq $8, %rax
  16689. addq %rax, %r11
  16690. movq 0(%r11) |$\itm{lhs'}$|
  16691. \end{lstlisting}
  16692. \fi}
  16693. %
  16694. {\if\edition\pythonEd
  16695. \begin{lstlisting}
  16696. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|]))
  16697. |$\Longrightarrow$|
  16698. movq $|$-8$|, %r11
  16699. andq |$e_1'$|, %r11
  16700. movq |$e_2'$|, %rax
  16701. addq $1, %rax
  16702. imulq $8, %rax
  16703. addq %rax, %r11
  16704. movq 0(%r11) |$\itm{lhs'}$|
  16705. \end{lstlisting}
  16706. \fi}
  16707. \end{minipage}
  16708. \end{center}
  16709. \paragraph{\racket{Any-vector-set!}\python{\code{any\_tuple\_store}}}
  16710. The code generation for
  16711. \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  16712. analogous to the above translation for reading from a tuple.
  16713. \section{Register Allocation for \LangAny{}}
  16714. \label{sec:register-allocation-Rany}
  16715. \index{subject}{register allocation}
  16716. There is an interesting interaction between tagged values and garbage
  16717. collection that has an impact on register allocation. A variable of
  16718. type \ANYTY{} might refer to a tuple and therefore it might be a root
  16719. that needs to be inspected and copied during garbage collection. Thus,
  16720. we need to treat variables of type \ANYTY{} in a similar way to
  16721. variables of tuple type for purposes of register allocation. In
  16722. particular,
  16723. \begin{itemize}
  16724. \item If a variable of type \ANYTY{} is live during a function call,
  16725. then it must be spilled. This can be accomplished by changing
  16726. \code{build\_interference} to mark all variables of type \ANYTY{}
  16727. that are live after a \code{callq} as interfering with all the
  16728. registers.
  16729. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  16730. the root stack instead of the normal procedure call stack.
  16731. \end{itemize}
  16732. Another concern regarding the root stack is that the garbage collector
  16733. needs to differentiate between (1) plain old pointers to tuples, (2) a
  16734. tagged value that points to a tuple, and (3) a tagged value that is
  16735. not a tuple. We enable this differentiation by choosing not to use the
  16736. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  16737. reserved for identifying plain old pointers to tuples. That way, if
  16738. one of the first three bits is set, then we have a tagged value and
  16739. inspecting the tag can differentiation between tuples ($010$) and the
  16740. other kinds of values.
  16741. %% \begin{exercise}\normalfont
  16742. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  16743. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  16744. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  16745. %% compiler on these new programs and all of your previously created test
  16746. %% programs.
  16747. %% \end{exercise}
  16748. \begin{exercise}\normalfont
  16749. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  16750. Create tests for \LangDyn{} by adapting ten of your previous test programs
  16751. by removing type annotations. Add 5 more tests programs that
  16752. specifically rely on the language being dynamically typed. That is,
  16753. they should not be legal programs in a statically typed language, but
  16754. nevertheless, they should be valid \LangDyn{} programs that run to
  16755. completion without error.
  16756. \end{exercise}
  16757. \begin{figure}[p]
  16758. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16759. \node (Rfun) at (0,4) {\large \LangDyn{}};
  16760. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  16761. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  16762. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  16763. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  16764. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  16765. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  16766. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  16767. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  16768. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  16769. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  16770. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  16771. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16772. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16773. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16774. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16775. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16776. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16777. \path[->,bend left=15] (Rfun) edge [above] node
  16778. {\ttfamily\footnotesize shrink} (Rfun-2);
  16779. \path[->,bend left=15] (Rfun-2) edge [above] node
  16780. {\ttfamily\footnotesize uniquify} (Rfun-3);
  16781. \path[->,bend left=15] (Rfun-3) edge [above] node
  16782. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  16783. \path[->,bend right=15] (Rfun-4) edge [left] node
  16784. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  16785. \path[->,bend left=15] (Rfun-5) edge [above] node
  16786. {\ttfamily\footnotesize reveal\_casts} (Rfun-6);
  16787. \path[->,bend left=15] (Rfun-6) edge [left] node
  16788. {\ttfamily\footnotesize convert\_assign.} (Rfun-7);
  16789. \path[->,bend left=15] (Rfun-7) edge [below] node
  16790. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16791. \path[->,bend right=15] (F1-2) edge [above] node
  16792. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16793. \path[->,bend right=15] (F1-3) edge [above] node
  16794. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16795. \path[->,bend right=15] (F1-4) edge [above] node
  16796. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16797. \path[->,bend right=15] (F1-5) edge [right] node
  16798. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16799. \path[->,bend left=15] (C3-2) edge [left] node
  16800. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16801. \path[->,bend right=15] (x86-2) edge [left] node
  16802. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16803. \path[->,bend right=15] (x86-2-1) edge [below] node
  16804. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16805. \path[->,bend right=15] (x86-2-2) edge [left] node
  16806. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16807. \path[->,bend left=15] (x86-3) edge [above] node
  16808. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16809. \path[->,bend left=15] (x86-4) edge [right] node
  16810. {\ttfamily\footnotesize print\_x86} (x86-5);
  16811. \end{tikzpicture}
  16812. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  16813. \label{fig:Rdyn-passes}
  16814. \end{figure}
  16815. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  16816. for the compilation of \LangDyn{}.
  16817. % Further Reading
  16818. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16819. %% {\if\edition\pythonEd
  16820. %% \chapter{Objects}
  16821. %% \label{ch:Lobject}
  16822. %% \index{subject}{objects}
  16823. %% \index{subject}{classes}
  16824. %% \fi}
  16825. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16826. \chapter{Gradual Typing}
  16827. \label{ch:Lgrad}
  16828. \index{subject}{gradual typing}
  16829. \if\edition\pythonEd
  16830. UNDER CONSTRUCTION
  16831. \fi
  16832. \if\edition\racketEd
  16833. This chapter studies a language, \LangGrad{}, in which the programmer
  16834. can choose between static and dynamic type checking in different parts
  16835. of a program, thereby mixing the statically typed \LangLoop{} language
  16836. with the dynamically typed \LangDyn{}. There are several approaches to
  16837. mixing static and dynamic typing, including multi-language
  16838. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  16839. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  16840. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  16841. programmer controls the amount of static versus dynamic checking by
  16842. adding or removing type annotations on parameters and
  16843. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  16844. %
  16845. The concrete syntax of \LangGrad{} is defined in
  16846. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  16847. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  16848. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  16849. non-terminals that make type annotations optional. The return types
  16850. are not optional in the abstract syntax; the parser fills in
  16851. \code{Any} when the return type is not specified in the concrete
  16852. syntax.
  16853. \begin{figure}[tp]
  16854. \centering
  16855. \fbox{
  16856. \begin{minipage}{0.96\textwidth}
  16857. \small
  16858. \[
  16859. \begin{array}{lcl}
  16860. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16861. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  16862. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  16863. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  16864. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  16865. &\MID& \gray{\key{\#t} \MID \key{\#f}
  16866. \MID (\key{and}\;\Exp\;\Exp)
  16867. \MID (\key{or}\;\Exp\;\Exp)
  16868. \MID (\key{not}\;\Exp) } \\
  16869. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  16870. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  16871. (\key{vector-ref}\;\Exp\;\Int)} \\
  16872. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  16873. \MID (\Exp \; \Exp\ldots) } \\
  16874. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  16875. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  16876. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  16877. \MID \CBEGIN{\Exp\ldots}{\Exp}
  16878. \MID \CWHILE{\Exp}{\Exp} } \\
  16879. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  16880. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  16881. \end{array}
  16882. \]
  16883. \end{minipage}
  16884. }
  16885. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  16886. \label{fig:Rgrad-concrete-syntax}
  16887. \end{figure}
  16888. \begin{figure}[tp]
  16889. \centering
  16890. \fbox{
  16891. \begin{minipage}{0.96\textwidth}
  16892. \small
  16893. \[
  16894. \begin{array}{lcl}
  16895. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16896. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  16897. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  16898. &\MID& \gray{ \BOOL{\itm{bool}}
  16899. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  16900. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  16901. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  16902. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  16903. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  16904. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  16905. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  16906. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16907. \end{array}
  16908. \]
  16909. \end{minipage}
  16910. }
  16911. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  16912. \label{fig:Rgrad-syntax}
  16913. \end{figure}
  16914. Both the type checker and the interpreter for \LangGrad{} require some
  16915. interesting changes to enable gradual typing, which we discuss in the
  16916. next two sections in the context of the \code{map} example from
  16917. Chapter~\ref{ch:Lfun}. In Figure~\ref{fig:gradual-map} we
  16918. revised the \code{map} example, omitting the type annotations from
  16919. the \code{inc} function.
  16920. \begin{figure}[btp]
  16921. % gradual_test_9.rkt
  16922. \begin{lstlisting}
  16923. (define (map [f : (Integer -> Integer)]
  16924. [v : (Vector Integer Integer)])
  16925. : (Vector Integer Integer)
  16926. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16927. (define (inc x) (+ x 1))
  16928. (vector-ref (map inc (vector 0 41)) 1)
  16929. \end{lstlisting}
  16930. \caption{A partially-typed version of the \code{map} example.}
  16931. \label{fig:gradual-map}
  16932. \end{figure}
  16933. \section{Type Checking \LangGrad{} and \LangCast{}}
  16934. \label{sec:gradual-type-check}
  16935. The type checker for \LangGrad{} uses the \code{Any} type for missing
  16936. parameter and return types. For example, the \code{x} parameter of
  16937. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  16938. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  16939. consider the \code{+} operator inside \code{inc}. It expects both
  16940. arguments to have type \code{Integer}, but its first argument \code{x}
  16941. has type \code{Any}. In a gradually typed language, such differences
  16942. are allowed so long as the types are \emph{consistent}, that is, they
  16943. are equal except in places where there is an \code{Any} type. The type
  16944. \code{Any} is consistent with every other type.
  16945. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  16946. \begin{figure}[tbp]
  16947. \begin{lstlisting}
  16948. (define/public (consistent? t1 t2)
  16949. (match* (t1 t2)
  16950. [('Integer 'Integer) #t]
  16951. [('Boolean 'Boolean) #t]
  16952. [('Void 'Void) #t]
  16953. [('Any t2) #t]
  16954. [(t1 'Any) #t]
  16955. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16956. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  16957. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16958. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  16959. (consistent? rt1 rt2))]
  16960. [(other wise) #f]))
  16961. \end{lstlisting}
  16962. \caption{The consistency predicate on types.}
  16963. \label{fig:consistent}
  16964. \end{figure}
  16965. Returning to the \code{map} example of
  16966. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  16967. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  16968. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  16969. because the two types are consistent. In particular, \code{->} is
  16970. equal to \code{->} and because \code{Any} is consistent with
  16971. \code{Integer}.
  16972. Next consider a program with an error, such as applying the
  16973. \code{map} to a function that sometimes returns a Boolean, as
  16974. shown in Figure~\ref{fig:map-maybe-inc}. The type checker for
  16975. \LangGrad{} accepts this program because the type of \code{maybe-inc} is
  16976. consistent with the type of parameter \code{f} of \code{map}, that
  16977. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  16978. Integer)}. One might say that a gradual type checker is optimistic
  16979. in that it accepts programs that might execute without a runtime type
  16980. error.
  16981. %
  16982. Unfortunately, running this program with input \code{1} triggers an
  16983. error when the \code{maybe-inc} function returns \code{\#t}. \LangGrad{}
  16984. performs checking at runtime to ensure the integrity of the static
  16985. types, such as the \code{(Integer -> Integer)} annotation on parameter
  16986. \code{f} of \code{map}. This runtime checking is carried out by a
  16987. new \code{Cast} form that is inserted by the type checker. Thus, the
  16988. output of the type checker is a program in the \LangCast{} language, which
  16989. adds \code{Cast} to \LangLoop{}, as shown in
  16990. Figure~\ref{fig:Rgrad-prime-syntax}.
  16991. \begin{figure}[tp]
  16992. \centering
  16993. \fbox{
  16994. \begin{minipage}{0.96\textwidth}
  16995. \small
  16996. \[
  16997. \begin{array}{lcl}
  16998. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  16999. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17000. \end{array}
  17001. \]
  17002. \end{minipage}
  17003. }
  17004. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  17005. \label{fig:Rgrad-prime-syntax}
  17006. \end{figure}
  17007. \begin{figure}[tbp]
  17008. \begin{lstlisting}
  17009. (define (map [f : (Integer -> Integer)]
  17010. [v : (Vector Integer Integer)])
  17011. : (Vector Integer Integer)
  17012. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17013. (define (inc x) (+ x 1))
  17014. (define (true) #t)
  17015. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  17016. (vector-ref (map maybe-inc (vector 0 41)) 0)
  17017. \end{lstlisting}
  17018. \caption{A variant of the \code{map} example with an error.}
  17019. \label{fig:map-maybe-inc}
  17020. \end{figure}
  17021. Figure~\ref{fig:map-cast} shows the output of the type checker for
  17022. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  17023. inserted every time the type checker sees two types that are
  17024. consistent but not equal. In the \code{inc} function, \code{x} is
  17025. cast to \code{Integer} and the result of the \code{+} is cast to
  17026. \code{Any}. In the call to \code{map}, the \code{inc} argument
  17027. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  17028. \begin{figure}[btp]
  17029. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17030. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17031. : (Vector Integer Integer)
  17032. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17033. (define (inc [x : Any]) : Any
  17034. (cast (+ (cast x Any Integer) 1) Integer Any))
  17035. (define (true) : Any (cast #t Boolean Any))
  17036. (define (maybe-inc [x : Any]) : Any
  17037. (if (eq? 0 (read)) (inc x) (true)))
  17038. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  17039. (vector 0 41)) 0)
  17040. \end{lstlisting}
  17041. \caption{Output of type checking \code{map}
  17042. and \code{maybe-inc}.}
  17043. \label{fig:map-cast}
  17044. \end{figure}
  17045. The type checker for \LangGrad{} is defined in
  17046. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  17047. and \ref{fig:type-check-Rgradual-3}.
  17048. \begin{figure}[tbp]
  17049. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17050. (define type-check-gradual_class
  17051. (class type-check-Rwhile_class
  17052. (super-new)
  17053. (inherit operator-types type-predicates)
  17054. (define/override (type-check-exp env)
  17055. (lambda (e)
  17056. (define recur (type-check-exp env))
  17057. (match e
  17058. [(Prim 'vector-length (list e1))
  17059. (define-values (e1^ t) (recur e1))
  17060. (match t
  17061. [`(Vector ,ts ...)
  17062. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17063. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17064. [(Prim 'vector-ref (list e1 e2))
  17065. (define-values (e1^ t1) (recur e1))
  17066. (define-values (e2^ t2) (recur e2))
  17067. (check-consistent? t2 'Integer e)
  17068. (match t1
  17069. [`(Vector ,ts ...)
  17070. (match e2^
  17071. [(Int i)
  17072. (unless (and (0 . <= . i) (i . < . (length ts)))
  17073. (error 'type-check "invalid index ~a in ~a" i e))
  17074. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17075. [else (define e1^^ (make-cast e1^ t1 'Any))
  17076. (define e2^^ (make-cast e2^ t2 'Integer))
  17077. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17078. ['Any
  17079. (define e2^^ (make-cast e2^ t2 'Integer))
  17080. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17081. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17082. [(Prim 'vector-set! (list e1 e2 e3) )
  17083. (define-values (e1^ t1) (recur e1))
  17084. (define-values (e2^ t2) (recur e2))
  17085. (define-values (e3^ t3) (recur e3))
  17086. (check-consistent? t2 'Integer e)
  17087. (match t1
  17088. [`(Vector ,ts ...)
  17089. (match e2^
  17090. [(Int i)
  17091. (unless (and (0 . <= . i) (i . < . (length ts)))
  17092. (error 'type-check "invalid index ~a in ~a" i e))
  17093. (check-consistent? (list-ref ts i) t3 e)
  17094. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17095. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17096. [else
  17097. (define e1^^ (make-cast e1^ t1 'Any))
  17098. (define e2^^ (make-cast e2^ t2 'Integer))
  17099. (define e3^^ (make-cast e3^ t3 'Any))
  17100. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17101. ['Any
  17102. (define e2^^ (make-cast e2^ t2 'Integer))
  17103. (define e3^^ (make-cast e3^ t3 'Any))
  17104. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17105. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17106. \end{lstlisting}
  17107. \caption{Type checker for the \LangGrad{} language, part 1.}
  17108. \label{fig:type-check-Rgradual-1}
  17109. \end{figure}
  17110. \begin{figure}[tbp]
  17111. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17112. [(Prim 'eq? (list e1 e2))
  17113. (define-values (e1^ t1) (recur e1))
  17114. (define-values (e2^ t2) (recur e2))
  17115. (check-consistent? t1 t2 e)
  17116. (define T (meet t1 t2))
  17117. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  17118. 'Boolean)]
  17119. [(Prim 'not (list e1))
  17120. (define-values (e1^ t1) (recur e1))
  17121. (match t1
  17122. ['Any
  17123. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  17124. (Bool #t) (Bool #f)))]
  17125. [else
  17126. (define-values (t-ret new-es^)
  17127. (type-check-op 'not (list t1) (list e1^) e))
  17128. (values (Prim 'not new-es^) t-ret)])]
  17129. [(Prim 'and (list e1 e2))
  17130. (recur (If e1 e2 (Bool #f)))]
  17131. [(Prim 'or (list e1 e2))
  17132. (define tmp (gensym 'tmp))
  17133. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  17134. [(Prim op es)
  17135. #:when (not (set-member? explicit-prim-ops op))
  17136. (define-values (new-es ts)
  17137. (for/lists (exprs types) ([e es])
  17138. (recur e)))
  17139. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  17140. (values (Prim op new-es^) t-ret)]
  17141. [(If e1 e2 e3)
  17142. (define-values (e1^ T1) (recur e1))
  17143. (define-values (e2^ T2) (recur e2))
  17144. (define-values (e3^ T3) (recur e3))
  17145. (check-consistent? T2 T3 e)
  17146. (match T1
  17147. ['Boolean
  17148. (define Tif (join T2 T3))
  17149. (values (If e1^ (make-cast e2^ T2 Tif)
  17150. (make-cast e3^ T3 Tif)) Tif)]
  17151. ['Any
  17152. (define Tif (meet T2 T3))
  17153. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  17154. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  17155. Tif)]
  17156. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  17157. [(HasType e1 T)
  17158. (define-values (e1^ T1) (recur e1))
  17159. (check-consistent? T1 T)
  17160. (values (make-cast e1^ T1 T) T)]
  17161. [(SetBang x e1)
  17162. (define-values (e1^ T1) (recur e1))
  17163. (define varT (dict-ref env x))
  17164. (check-consistent? T1 varT e)
  17165. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  17166. [(WhileLoop e1 e2)
  17167. (define-values (e1^ T1) (recur e1))
  17168. (check-consistent? T1 'Boolean e)
  17169. (define-values (e2^ T2) ((type-check-exp env) e2))
  17170. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  17171. \end{lstlisting}
  17172. \caption{Type checker for the \LangGrad{} language, part 2.}
  17173. \label{fig:type-check-Rgradual-2}
  17174. \end{figure}
  17175. \begin{figure}[tbp]
  17176. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17177. [(Apply e1 e2s)
  17178. (define-values (e1^ T1) (recur e1))
  17179. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  17180. (match T1
  17181. [`(,T1ps ... -> ,T1rt)
  17182. (for ([T2 T2s] [Tp T1ps])
  17183. (check-consistent? T2 Tp e))
  17184. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  17185. (make-cast e2 src tgt)))
  17186. (values (Apply e1^ e2s^^) T1rt)]
  17187. [`Any
  17188. (define e1^^ (make-cast e1^ 'Any
  17189. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  17190. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  17191. (make-cast e2 src 'Any)))
  17192. (values (Apply e1^^ e2s^^) 'Any)]
  17193. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  17194. [(Lambda params Tr e1)
  17195. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  17196. (match p
  17197. [`[,x : ,T] (values x T)]
  17198. [(? symbol? x) (values x 'Any)])))
  17199. (define-values (e1^ T1)
  17200. ((type-check-exp (append (map cons xs Ts) env)) e1))
  17201. (check-consistent? Tr T1 e)
  17202. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  17203. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  17204. [else ((super type-check-exp env) e)]
  17205. )))
  17206. \end{lstlisting}
  17207. \caption{Type checker for the \LangGrad{} language, part 3.}
  17208. \label{fig:type-check-Rgradual-3}
  17209. \end{figure}
  17210. \begin{figure}[tbp]
  17211. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17212. (define/public (join t1 t2)
  17213. (match* (t1 t2)
  17214. [('Integer 'Integer) 'Integer]
  17215. [('Boolean 'Boolean) 'Boolean]
  17216. [('Void 'Void) 'Void]
  17217. [('Any t2) t2]
  17218. [(t1 'Any) t1]
  17219. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17220. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  17221. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17222. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  17223. -> ,(join rt1 rt2))]))
  17224. (define/public (meet t1 t2)
  17225. (match* (t1 t2)
  17226. [('Integer 'Integer) 'Integer]
  17227. [('Boolean 'Boolean) 'Boolean]
  17228. [('Void 'Void) 'Void]
  17229. [('Any t2) 'Any]
  17230. [(t1 'Any) 'Any]
  17231. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17232. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  17233. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17234. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  17235. -> ,(meet rt1 rt2))]))
  17236. (define/public (make-cast e src tgt)
  17237. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  17238. (define/public (check-consistent? t1 t2 e)
  17239. (unless (consistent? t1 t2)
  17240. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  17241. (define/override (type-check-op op arg-types args e)
  17242. (match (dict-ref (operator-types) op)
  17243. [`(,param-types . ,return-type)
  17244. (for ([at arg-types] [pt param-types])
  17245. (check-consistent? at pt e))
  17246. (values return-type
  17247. (for/list ([e args] [s arg-types] [t param-types])
  17248. (make-cast e s t)))]
  17249. [else (error 'type-check-op "unrecognized ~a" op)]))
  17250. (define explicit-prim-ops
  17251. (set-union
  17252. (type-predicates)
  17253. (set 'procedure-arity 'eq?
  17254. 'vector 'vector-length 'vector-ref 'vector-set!
  17255. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  17256. (define/override (fun-def-type d)
  17257. (match d
  17258. [(Def f params rt info body)
  17259. (define ps
  17260. (for/list ([p params])
  17261. (match p
  17262. [`[,x : ,T] T]
  17263. [(? symbol?) 'Any]
  17264. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  17265. `(,@ps -> ,rt)]
  17266. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  17267. \end{lstlisting}
  17268. \caption{Auxiliary functions for type checking \LangGrad{}.}
  17269. \label{fig:type-check-Rgradual-aux}
  17270. \end{figure}
  17271. \clearpage
  17272. \section{Interpreting \LangCast{}}
  17273. \label{sec:interp-casts}
  17274. The runtime behavior of first-order casts is straightforward, that is,
  17275. casts involving simple types such as \code{Integer} and
  17276. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  17277. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  17278. puts the integer into a tagged value
  17279. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  17280. \code{Integer} is accomplished with the \code{Project} operator, that
  17281. is, by checking the value's tag and either retrieving the underlying
  17282. integer or signaling an error if it the tag is not the one for
  17283. integers (Figure~\ref{fig:interp-Rany-aux}).
  17284. %
  17285. Things get more interesting for higher-order casts, that is, casts
  17286. involving function or vector types.
  17287. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  17288. Any)} to \code{(Integer -> Integer)}. When a function flows through
  17289. this cast at runtime, we can't know in general whether the function
  17290. will always return an integer.\footnote{Predicting the return value of
  17291. a function is equivalent to the halting problem, which is
  17292. undecidable.} The \LangCast{} interpreter therefore delays the checking
  17293. of the cast until the function is applied. This is accomplished by
  17294. wrapping \code{maybe-inc} in a new function that casts its parameter
  17295. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  17296. casts the return value from \code{Any} to \code{Integer}.
  17297. Turning our attention to casts involving vector types, we consider the
  17298. example in Figure~\ref{fig:map-bang} that defines a
  17299. partially-typed version of \code{map} whose parameter \code{v} has
  17300. type \code{(Vector Any Any)} and that updates \code{v} in place
  17301. instead of returning a new vector. So we name this function
  17302. \code{map!}. We apply \code{map!} to a vector of integers, so
  17303. the type checker inserts a cast from \code{(Vector Integer Integer)}
  17304. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  17305. cast between vector types would be a build a new vector whose elements
  17306. are the result of casting each of the original elements to the
  17307. appropriate target type. However, this approach is only valid for
  17308. immutable vectors; and our vectors are mutable. In the example of
  17309. Figure~\ref{fig:map-bang}, if the cast created a new vector, then
  17310. the updates inside of \code{map!} would happen to the new vector
  17311. and not the original one.
  17312. \begin{figure}[tbp]
  17313. % gradual_test_11.rkt
  17314. \begin{lstlisting}
  17315. (define (map! [f : (Any -> Any)]
  17316. [v : (Vector Any Any)]) : Void
  17317. (begin
  17318. (vector-set! v 0 (f (vector-ref v 0)))
  17319. (vector-set! v 1 (f (vector-ref v 1)))))
  17320. (define (inc x) (+ x 1))
  17321. (let ([v (vector 0 41)])
  17322. (begin (map! inc v) (vector-ref v 1)))
  17323. \end{lstlisting}
  17324. \caption{An example involving casts on vectors.}
  17325. \label{fig:map-bang}
  17326. \end{figure}
  17327. Instead the interpreter needs to create a new kind of value, a
  17328. \emph{vector proxy}, that intercepts every vector operation. On a
  17329. read, the proxy reads from the underlying vector and then applies a
  17330. cast to the resulting value. On a write, the proxy casts the argument
  17331. value and then performs the write to the underlying vector. For the
  17332. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  17333. \code{0} from \code{Integer} to \code{Any}. For the first
  17334. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  17335. to \code{Integer}.
  17336. The final category of cast that we need to consider are casts between
  17337. the \code{Any} type and either a function or a vector
  17338. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  17339. in which parameter \code{v} does not have a type annotation, so it is
  17340. given type \code{Any}. In the call to \code{map!}, the vector has
  17341. type \code{(Vector Integer Integer)} so the type checker inserts a
  17342. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  17343. thought is to use \code{Inject}, but that doesn't work because
  17344. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  17345. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  17346. to \code{Any}.
  17347. \begin{figure}[tbp]
  17348. \begin{lstlisting}
  17349. (define (map! [f : (Any -> Any)] v) : Void
  17350. (begin
  17351. (vector-set! v 0 (f (vector-ref v 0)))
  17352. (vector-set! v 1 (f (vector-ref v 1)))))
  17353. (define (inc x) (+ x 1))
  17354. (let ([v (vector 0 41)])
  17355. (begin (map! inc v) (vector-ref v 1)))
  17356. \end{lstlisting}
  17357. \caption{Casting a vector to \code{Any}.}
  17358. \label{fig:map-any}
  17359. \end{figure}
  17360. The \LangCast{} interpreter uses an auxiliary function named
  17361. \code{apply-cast} to cast a value from a source type to a target type,
  17362. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  17363. of the kinds of casts that we've discussed in this section.
  17364. \begin{figure}[tbp]
  17365. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17366. (define/public (apply-cast v s t)
  17367. (match* (s t)
  17368. [(t1 t2) #:when (equal? t1 t2) v]
  17369. [('Any t2)
  17370. (match t2
  17371. [`(,ts ... -> ,rt)
  17372. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17373. (define v^ (apply-project v any->any))
  17374. (apply-cast v^ any->any `(,@ts -> ,rt))]
  17375. [`(Vector ,ts ...)
  17376. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17377. (define v^ (apply-project v vec-any))
  17378. (apply-cast v^ vec-any `(Vector ,@ts))]
  17379. [else (apply-project v t2)])]
  17380. [(t1 'Any)
  17381. (match t1
  17382. [`(,ts ... -> ,rt)
  17383. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17384. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  17385. (apply-inject v^ (any-tag any->any))]
  17386. [`(Vector ,ts ...)
  17387. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17388. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  17389. (apply-inject v^ (any-tag vec-any))]
  17390. [else (apply-inject v (any-tag t1))])]
  17391. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17392. (define x (gensym 'x))
  17393. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  17394. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  17395. (define cast-writes
  17396. (for/list ([t1 ts1] [t2 ts2])
  17397. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  17398. `(vector-proxy ,(vector v (apply vector cast-reads)
  17399. (apply vector cast-writes)))]
  17400. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17401. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  17402. `(function ,xs ,(Cast
  17403. (Apply (Value v)
  17404. (for/list ([x xs][t1 ts1][t2 ts2])
  17405. (Cast (Var x) t2 t1)))
  17406. rt1 rt2) ())]
  17407. ))
  17408. \end{lstlisting}
  17409. \caption{The \code{apply-cast} auxiliary method.}
  17410. \label{fig:apply-cast}
  17411. \end{figure}
  17412. The interpreter for \LangCast{} is defined in
  17413. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  17414. dispatching to \code{apply-cast}. To handle the addition of vector
  17415. proxies, we update the vector primitives in \code{interp-op} using the
  17416. functions in Figure~\ref{fig:guarded-vector}.
  17417. \begin{figure}[tbp]
  17418. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17419. (define interp-Rcast_class
  17420. (class interp-Rwhile_class
  17421. (super-new)
  17422. (inherit apply-fun apply-inject apply-project)
  17423. (define/override (interp-op op)
  17424. (match op
  17425. ['vector-length guarded-vector-length]
  17426. ['vector-ref guarded-vector-ref]
  17427. ['vector-set! guarded-vector-set!]
  17428. ['any-vector-ref (lambda (v i)
  17429. (match v [`(tagged ,v^ ,tg)
  17430. (guarded-vector-ref v^ i)]))]
  17431. ['any-vector-set! (lambda (v i a)
  17432. (match v [`(tagged ,v^ ,tg)
  17433. (guarded-vector-set! v^ i a)]))]
  17434. ['any-vector-length (lambda (v)
  17435. (match v [`(tagged ,v^ ,tg)
  17436. (guarded-vector-length v^)]))]
  17437. [else (super interp-op op)]
  17438. ))
  17439. (define/override ((interp-exp env) e)
  17440. (define (recur e) ((interp-exp env) e))
  17441. (match e
  17442. [(Value v) v]
  17443. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  17444. [else ((super interp-exp env) e)]))
  17445. ))
  17446. (define (interp-Rcast p)
  17447. (send (new interp-Rcast_class) interp-program p))
  17448. \end{lstlisting}
  17449. \caption{The interpreter for \LangCast{}.}
  17450. \label{fig:interp-Rcast}
  17451. \end{figure}
  17452. \begin{figure}[tbp]
  17453. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17454. (define (guarded-vector-ref vec i)
  17455. (match vec
  17456. [`(vector-proxy ,proxy)
  17457. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  17458. (define rd (vector-ref (vector-ref proxy 1) i))
  17459. (apply-fun rd (list val) 'guarded-vector-ref)]
  17460. [else (vector-ref vec i)]))
  17461. (define (guarded-vector-set! vec i arg)
  17462. (match vec
  17463. [`(vector-proxy ,proxy)
  17464. (define wr (vector-ref (vector-ref proxy 2) i))
  17465. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  17466. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  17467. [else (vector-set! vec i arg)]))
  17468. (define (guarded-vector-length vec)
  17469. (match vec
  17470. [`(vector-proxy ,proxy)
  17471. (guarded-vector-length (vector-ref proxy 0))]
  17472. [else (vector-length vec)]))
  17473. \end{lstlisting}
  17474. \caption{The guarded-vector auxiliary functions.}
  17475. \label{fig:guarded-vector}
  17476. \end{figure}
  17477. \section{Lower Casts}
  17478. \label{sec:lower-casts}
  17479. The next step in the journey towards x86 is the \code{lower-casts}
  17480. pass that translates the casts in \LangCast{} to the lower-level
  17481. \code{Inject} and \code{Project} operators and a new operator for
  17482. creating vector proxies, extending the \LangLoop{} language to create
  17483. \LangProxy{}. We recommend creating an auxiliary function named
  17484. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  17485. and a target type, and translates it to expression in \LangProxy{} that has
  17486. the same behavior as casting the expression from the source to the
  17487. target type in the interpreter.
  17488. The \code{lower-cast} function can follow a code structure similar to
  17489. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  17490. the interpreter for \LangCast{} because it must handle the same cases as
  17491. \code{apply-cast} and it needs to mimic the behavior of
  17492. \code{apply-cast}. The most interesting cases are those concerning the
  17493. casts between two vector types and between two function types.
  17494. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  17495. type to another vector type is accomplished by creating a proxy that
  17496. intercepts the operations on the underlying vector. Here we make the
  17497. creation of the proxy explicit with the \code{vector-proxy} primitive
  17498. operation. It takes three arguments, the first is an expression for
  17499. the vector, the second is a vector of functions for casting an element
  17500. that is being read from the vector, and the third is a vector of
  17501. functions for casting an element that is being written to the vector.
  17502. You can create the functions using \code{Lambda}. Also, as we shall
  17503. see in the next section, we need to differentiate these vectors from
  17504. the user-created ones, so we recommend using a new primitive operator
  17505. named \code{raw-vector} instead of \code{vector} to create these
  17506. vectors of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  17507. the output of \code{lower-casts} on the example in
  17508. Figure~\ref{fig:map-bang} that involved casting a vector of
  17509. integers to a vector of \code{Any}.
  17510. \begin{figure}[tbp]
  17511. \begin{lstlisting}
  17512. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  17513. (begin
  17514. (vector-set! v 0 (f (vector-ref v 0)))
  17515. (vector-set! v 1 (f (vector-ref v 1)))))
  17516. (define (inc [x : Any]) : Any
  17517. (inject (+ (project x Integer) 1) Integer))
  17518. (let ([v (vector 0 41)])
  17519. (begin
  17520. (map! inc (vector-proxy v
  17521. (raw-vector (lambda: ([x9 : Integer]) : Any
  17522. (inject x9 Integer))
  17523. (lambda: ([x9 : Integer]) : Any
  17524. (inject x9 Integer)))
  17525. (raw-vector (lambda: ([x9 : Any]) : Integer
  17526. (project x9 Integer))
  17527. (lambda: ([x9 : Any]) : Integer
  17528. (project x9 Integer)))))
  17529. (vector-ref v 1)))
  17530. \end{lstlisting}
  17531. \caption{Output of \code{lower-casts} on the example in
  17532. Figure~\ref{fig:map-bang}.}
  17533. \label{fig:map-bang-lower-cast}
  17534. \end{figure}
  17535. A cast from one function type to another function type is accomplished
  17536. by generating a \code{Lambda} whose parameter and return types match
  17537. the target function type. The body of the \code{Lambda} should cast
  17538. the parameters from the target type to the source type (yes,
  17539. backwards! functions are contravariant\index{subject}{contravariant} in the
  17540. parameters), then call the underlying function, and finally cast the
  17541. result from the source return type to the target return type.
  17542. Figure~\ref{fig:map-lower-cast} shows the output of the
  17543. \code{lower-casts} pass on the \code{map} example in
  17544. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument
  17545. in the call to \code{map} is wrapped in a \code{lambda}.
  17546. \begin{figure}[tbp]
  17547. \begin{lstlisting}
  17548. (define (map [f : (Integer -> Integer)]
  17549. [v : (Vector Integer Integer)])
  17550. : (Vector Integer Integer)
  17551. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17552. (define (inc [x : Any]) : Any
  17553. (inject (+ (project x Integer) 1) Integer))
  17554. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  17555. (project (inc (inject x9 Integer)) Integer))
  17556. (vector 0 41)) 1)
  17557. \end{lstlisting}
  17558. \caption{Output of \code{lower-casts} on the example in
  17559. Figure~\ref{fig:gradual-map}.}
  17560. \label{fig:map-lower-cast}
  17561. \end{figure}
  17562. \section{Differentiate Proxies}
  17563. \label{sec:differentiate-proxies}
  17564. So far the job of differentiating vectors and vector proxies has been
  17565. the job of the interpreter. For example, the interpreter for \LangCast{}
  17566. implements \code{vector-ref} using the \code{guarded-vector-ref}
  17567. function in Figure~\ref{fig:guarded-vector}. In the
  17568. \code{differentiate-proxies} pass we shift this responsibility to the
  17569. generated code.
  17570. We begin by designing the output language $R^p_8$. In
  17571. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  17572. proxies. In $R^p_8$ we return the \code{Vector} type to
  17573. its original meaning, as the type of real vectors, and we introduce a
  17574. new type, \code{PVector}, whose values can be either real vectors or
  17575. vector proxies. This new type comes with a suite of new primitive
  17576. operations for creating and using values of type \code{PVector}. We
  17577. don't need to introduce a new type to represent vector proxies. A
  17578. proxy is represented by a vector containing three things: 1) the
  17579. underlying vector, 2) a vector of functions for casting elements that
  17580. are read from the vector, and 3) a vector of functions for casting
  17581. values to be written to the vector. So we define the following
  17582. abbreviation for the type of a vector proxy:
  17583. \[
  17584. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  17585. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  17586. \to (\key{PVector}~ T' \ldots)
  17587. \]
  17588. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  17589. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  17590. %
  17591. Next we describe each of the new primitive operations.
  17592. \begin{description}
  17593. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  17594. (\key{PVector} $T \ldots$)]\ \\
  17595. %
  17596. This operation brands a vector as a value of the \code{PVector} type.
  17597. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  17598. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  17599. %
  17600. This operation brands a vector proxy as value of the \code{PVector} type.
  17601. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  17602. \code{Boolean}] \ \\
  17603. %
  17604. returns true if the value is a vector proxy and false if it is a
  17605. real vector.
  17606. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  17607. (\key{Vector} $T \ldots$)]\ \\
  17608. %
  17609. Assuming that the input is a vector (and not a proxy), this
  17610. operation returns the vector.
  17611. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  17612. $\to$ \code{Boolean}]\ \\
  17613. %
  17614. Given a vector proxy, this operation returns the length of the
  17615. underlying vector.
  17616. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  17617. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  17618. %
  17619. Given a vector proxy, this operation returns the $i$th element of
  17620. the underlying vector.
  17621. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  17622. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  17623. proxy, this operation writes a value to the $i$th element of the
  17624. underlying vector.
  17625. \end{description}
  17626. Now to discuss the translation that differentiates vectors from
  17627. proxies. First, every type annotation in the program must be
  17628. translated (recursively) to replace \code{Vector} with \code{PVector}.
  17629. Next, we must insert uses of \code{PVector} operations in the
  17630. appropriate places. For example, we wrap every vector creation with an
  17631. \code{inject-vector}.
  17632. \begin{lstlisting}
  17633. (vector |$e_1 \ldots e_n$|)
  17634. |$\Rightarrow$|
  17635. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  17636. \end{lstlisting}
  17637. The \code{raw-vector} operator that we introduced in the previous
  17638. section does not get injected.
  17639. \begin{lstlisting}
  17640. (raw-vector |$e_1 \ldots e_n$|)
  17641. |$\Rightarrow$|
  17642. (vector |$e'_1 \ldots e'_n$|)
  17643. \end{lstlisting}
  17644. The \code{vector-proxy} primitive translates as follows.
  17645. \begin{lstlisting}
  17646. (vector-proxy |$e_1~e_2~e_3$|)
  17647. |$\Rightarrow$|
  17648. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  17649. \end{lstlisting}
  17650. We translate the vector operations into conditional expressions that
  17651. check whether the value is a proxy and then dispatch to either the
  17652. appropriate proxy vector operation or the regular vector operation.
  17653. For example, the following is the translation for \code{vector-ref}.
  17654. \begin{lstlisting}
  17655. (vector-ref |$e_1$| |$i$|)
  17656. |$\Rightarrow$|
  17657. (let ([|$v~e_1$|])
  17658. (if (proxy? |$v$|)
  17659. (proxy-vector-ref |$v$| |$i$|)
  17660. (vector-ref (project-vector |$v$|) |$i$|)
  17661. \end{lstlisting}
  17662. Note in the case of a real vector, we must apply \code{project-vector}
  17663. before the \code{vector-ref}.
  17664. \section{Reveal Casts}
  17665. \label{sec:reveal-casts-gradual}
  17666. Recall that the \code{reveal-casts} pass
  17667. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  17668. \code{Inject} and \code{Project} into lower-level operations. In
  17669. particular, \code{Project} turns into a conditional expression that
  17670. inspects the tag and retrieves the underlying value. Here we need to
  17671. augment the translation of \code{Project} to handle the situation when
  17672. the target type is \code{PVector}. Instead of using
  17673. \code{vector-length} we need to use \code{proxy-vector-length}.
  17674. \begin{lstlisting}
  17675. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  17676. |$\Rightarrow$|
  17677. (let |$\itm{tmp}$| |$e'$|
  17678. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  17679. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  17680. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  17681. (exit)))
  17682. \end{lstlisting}
  17683. \section{Closure Conversion}
  17684. \label{sec:closure-conversion-gradual}
  17685. The closure conversion pass only requires one minor adjustment. The
  17686. auxiliary function that translates type annotations needs to be
  17687. updated to handle the \code{PVector} type.
  17688. \section{Explicate Control}
  17689. \label{sec:explicate-control-gradual}
  17690. Update the \code{explicate\_control} pass to handle the new primitive
  17691. operations on the \code{PVector} type.
  17692. \section{Select Instructions}
  17693. \label{sec:select-instructions-gradual}
  17694. Recall that the \code{select\_instructions} pass is responsible for
  17695. lowering the primitive operations into x86 instructions. So we need
  17696. to translate the new \code{PVector} operations to x86. To do so, the
  17697. first question we need to answer is how will we differentiate the two
  17698. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  17699. We need just one bit to accomplish this, and use the bit in position
  17700. $57$ of the 64-bit tag at the front of every vector (see
  17701. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  17702. for \code{inject-vector} we leave it that way.
  17703. \begin{lstlisting}
  17704. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  17705. |$\Rightarrow$|
  17706. movq |$e'_1$|, |$\itm{lhs'}$|
  17707. \end{lstlisting}
  17708. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  17709. \begin{lstlisting}
  17710. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  17711. |$\Rightarrow$|
  17712. movq |$e'_1$|, %r11
  17713. movq |$(1 << 57)$|, %rax
  17714. orq 0(%r11), %rax
  17715. movq %rax, 0(%r11)
  17716. movq %r11, |$\itm{lhs'}$|
  17717. \end{lstlisting}
  17718. The \code{proxy?} operation consumes the information so carefully
  17719. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  17720. isolates the $57$th bit to tell whether the value is a real vector or
  17721. a proxy.
  17722. \begin{lstlisting}
  17723. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  17724. |$\Rightarrow$|
  17725. movq |$e_1'$|, %r11
  17726. movq 0(%r11), %rax
  17727. sarq $57, %rax
  17728. andq $1, %rax
  17729. movq %rax, |$\itm{lhs'}$|
  17730. \end{lstlisting}
  17731. The \code{project-vector} operation is straightforward to translate,
  17732. so we leave it up to the reader.
  17733. Regarding the \code{proxy-vector} operations, the runtime provides
  17734. procedures that implement them (they are recursive functions!) so
  17735. here we simply need to translate these vector operations into the
  17736. appropriate function call. For example, here is the translation for
  17737. \code{proxy-vector-ref}.
  17738. \begin{lstlisting}
  17739. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  17740. |$\Rightarrow$|
  17741. movq |$e_1'$|, %rdi
  17742. movq |$e_2'$|, %rsi
  17743. callq proxy_vector_ref
  17744. movq %rax, |$\itm{lhs'}$|
  17745. \end{lstlisting}
  17746. We have another batch of vector operations to deal with, those for the
  17747. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  17748. \code{any-vector-ref} when there is a \code{vector-ref} on something
  17749. of type \code{Any}, and similarly for \code{any-vector-set!} and
  17750. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  17751. Section~\ref{sec:select-Rany} we selected instructions for these
  17752. operations based on the idea that the underlying value was a real
  17753. vector. But in the current setting, the underlying value is of type
  17754. \code{PVector}. So \code{any-vector-ref} can be translates to
  17755. pseudo-x86 as follows. We begin by projecting the underlying value out
  17756. of the tagged value and then call the \code{proxy\_vector\_ref}
  17757. procedure in the runtime.
  17758. \begin{lstlisting}
  17759. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17760. movq |$\neg 111$|, %rdi
  17761. andq |$e_1'$|, %rdi
  17762. movq |$e_2'$|, %rsi
  17763. callq proxy_vector_ref
  17764. movq %rax, |$\itm{lhs'}$|
  17765. \end{lstlisting}
  17766. The \code{any-vector-set!} and \code{any-vector-length} operators can
  17767. be translated in a similar way.
  17768. \begin{exercise}\normalfont
  17769. Implement a compiler for the gradually-typed \LangGrad{} language by
  17770. extending and adapting your compiler for \LangLoop{}. Create 10 new
  17771. partially-typed test programs. In addition to testing with these
  17772. new programs, also test your compiler on all the tests for \LangLoop{}
  17773. and tests for \LangDyn{}. Sometimes you may get a type checking error
  17774. on the \LangDyn{} programs but you can adapt them by inserting
  17775. a cast to the \code{Any} type around each subexpression
  17776. causing a type error. While \LangDyn{} does not have explicit casts,
  17777. you can induce one by wrapping the subexpression \code{e}
  17778. with a call to an un-annotated identity function, like this:
  17779. \code{((lambda (x) x) e)}.
  17780. \end{exercise}
  17781. \begin{figure}[p]
  17782. \begin{tikzpicture}[baseline=(current bounding box.center)]
  17783. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  17784. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  17785. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  17786. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  17787. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  17788. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  17789. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  17790. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  17791. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  17792. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  17793. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  17794. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  17795. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  17796. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  17797. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17798. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17799. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17800. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17801. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17802. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17803. \path[->,bend right=15] (Rgradual) edge [above] node
  17804. {\ttfamily\footnotesize type\_check} (Rgradualp);
  17805. \path[->,bend right=15] (Rgradualp) edge [above] node
  17806. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  17807. \path[->,bend right=15] (Rwhilepp) edge [right] node
  17808. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  17809. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  17810. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  17811. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  17812. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  17813. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  17814. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  17815. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  17816. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  17817. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  17818. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  17819. \path[->,bend left=15] (F1-1) edge [below] node
  17820. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17821. \path[->,bend right=15] (F1-2) edge [above] node
  17822. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17823. \path[->,bend right=15] (F1-3) edge [above] node
  17824. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17825. \path[->,bend right=15] (F1-4) edge [above] node
  17826. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  17827. \path[->,bend right=15] (F1-5) edge [right] node
  17828. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17829. \path[->,bend left=15] (C3-2) edge [left] node
  17830. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17831. \path[->,bend right=15] (x86-2) edge [left] node
  17832. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17833. \path[->,bend right=15] (x86-2-1) edge [below] node
  17834. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17835. \path[->,bend right=15] (x86-2-2) edge [left] node
  17836. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17837. \path[->,bend left=15] (x86-3) edge [above] node
  17838. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17839. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  17840. \end{tikzpicture}
  17841. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  17842. \label{fig:Rgradual-passes}
  17843. \end{figure}
  17844. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  17845. for the compilation of \LangGrad{}.
  17846. \section{Further Reading}
  17847. This chapter just scratches the surface of gradual typing. The basic
  17848. approach described here is missing two key ingredients that one would
  17849. want in a implementation of gradual typing: blame
  17850. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  17851. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  17852. problem addressed by blame tracking is that when a cast on a
  17853. higher-order value fails, it often does so at a point in the program
  17854. that is far removed from the original cast. Blame tracking is a
  17855. technique for propagating extra information through casts and proxies
  17856. so that when a cast fails, the error message can point back to the
  17857. original location of the cast in the source program.
  17858. The problem addressed by space-efficient casts also relates to
  17859. higher-order casts. It turns out that in partially typed programs, a
  17860. function or vector can flow through very-many casts at runtime. With
  17861. the approach described in this chapter, each cast adds another
  17862. \code{lambda} wrapper or a vector proxy. Not only does this take up
  17863. considerable space, but it also makes the function calls and vector
  17864. operations slow. For example, a partially-typed version of quicksort
  17865. could, in the worst case, build a chain of proxies of length $O(n)$
  17866. around the vector, changing the overall time complexity of the
  17867. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  17868. solution to this problem by representing casts using the coercion
  17869. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  17870. long chains of proxies by compressing them into a concise normal
  17871. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  17872. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  17873. the Grift compiler.
  17874. \begin{center}
  17875. \url{https://github.com/Gradual-Typing/Grift}
  17876. \end{center}
  17877. There are also interesting interactions between gradual typing and
  17878. other language features, such as parametetric polymorphism,
  17879. information-flow types, and type inference, to name a few. We
  17880. recommend the reader to the online gradual typing bibliography:
  17881. \begin{center}
  17882. \url{http://samth.github.io/gradual-typing-bib/}
  17883. \end{center}
  17884. % TODO: challenge problem:
  17885. % type analysis and type specialization?
  17886. % coercions?
  17887. \fi
  17888. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17889. \chapter{Parametric Polymorphism}
  17890. \label{ch:Lpoly}
  17891. \index{subject}{parametric polymorphism}
  17892. \index{subject}{generics}
  17893. \if\edition\pythonEd
  17894. UNDER CONSTRUCTION
  17895. \fi
  17896. \if\edition\racketEd
  17897. This chapter studies the compilation of parametric
  17898. polymorphism\index{subject}{parametric polymorphism}
  17899. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  17900. Racket. Parametric polymorphism enables improved code reuse by
  17901. parameterizing functions and data structures with respect to the types
  17902. that they operate on. For example, Figure~\ref{fig:map-poly}
  17903. revisits the \code{map} example but this time gives it a more
  17904. fitting type. This \code{map} function is parameterized with
  17905. respect to the element type of the vector. The type of \code{map}
  17906. is the following polymorphic type as specified by the \code{All} and
  17907. the type parameter \code{a}.
  17908. \begin{lstlisting}
  17909. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17910. \end{lstlisting}
  17911. The idea is that \code{map} can be used at \emph{all} choices of a
  17912. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  17913. \code{map} to a vector of integers, a choice of \code{Integer} for
  17914. \code{a}, but we could have just as well applied \code{map} to a
  17915. vector of Booleans (and a function on Booleans).
  17916. \begin{figure}[tbp]
  17917. % poly_test_2.rkt
  17918. \begin{lstlisting}
  17919. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  17920. (define (map f v)
  17921. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17922. (define (inc [x : Integer]) : Integer (+ x 1))
  17923. (vector-ref (map inc (vector 0 41)) 1)
  17924. \end{lstlisting}
  17925. \caption{The \code{map} example using parametric polymorphism.}
  17926. \label{fig:map-poly}
  17927. \end{figure}
  17928. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  17929. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  17930. syntax. We add a second form for function definitions in which a type
  17931. declaration comes before the \code{define}. In the abstract syntax,
  17932. the return type in the \code{Def} is \code{Any}, but that should be
  17933. ignored in favor of the return type in the type declaration. (The
  17934. \code{Any} comes from using the same parser as in
  17935. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  17936. enables the use of an \code{All} type for a function, thereby making
  17937. it polymorphic. The grammar for types is extended to include
  17938. polymorphic types and type variables.
  17939. \begin{figure}[tp]
  17940. \centering
  17941. \fbox{
  17942. \begin{minipage}{0.96\textwidth}
  17943. \small
  17944. \[
  17945. \begin{array}{lcl}
  17946. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17947. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  17948. &\MID& \LP\key{:}~\Var~\Type\RP \\
  17949. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  17950. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  17951. \end{array}
  17952. \]
  17953. \end{minipage}
  17954. }
  17955. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  17956. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  17957. \label{fig:Rpoly-concrete-syntax}
  17958. \end{figure}
  17959. \begin{figure}[tp]
  17960. \centering
  17961. \fbox{
  17962. \begin{minipage}{0.96\textwidth}
  17963. \small
  17964. \[
  17965. \begin{array}{lcl}
  17966. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17967. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  17968. &\MID& \DECL{\Var}{\Type} \\
  17969. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  17970. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17971. \end{array}
  17972. \]
  17973. \end{minipage}
  17974. }
  17975. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  17976. (Figure~\ref{fig:Lwhile-syntax}).}
  17977. \label{fig:Rpoly-syntax}
  17978. \end{figure}
  17979. By including polymorphic types in the $\Type$ non-terminal we choose
  17980. to make them first-class which has interesting repercussions on the
  17981. compiler. Many languages with polymorphism, such as
  17982. C++~\citep{stroustrup88:_param_types} and Standard
  17983. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  17984. it is useful to see an example of first-class polymorphism. In
  17985. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  17986. whose parameter is a polymorphic function. The occurrence of a
  17987. polymorphic type underneath a function type is enabled by the normal
  17988. recursive structure of the grammar for $\Type$ and the categorization
  17989. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  17990. applies the polymorphic function to a Boolean and to an integer.
  17991. \begin{figure}[tbp]
  17992. \begin{lstlisting}
  17993. (: apply-twice ((All (b) (b -> b)) -> Integer))
  17994. (define (apply-twice f)
  17995. (if (f #t) (f 42) (f 777)))
  17996. (: id (All (a) (a -> a)))
  17997. (define (id x) x)
  17998. (apply-twice id)
  17999. \end{lstlisting}
  18000. \caption{An example illustrating first-class polymorphism.}
  18001. \label{fig:apply-twice}
  18002. \end{figure}
  18003. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  18004. three new responsibilities (compared to \LangLoop{}). The type checking of
  18005. function application is extended to handle the case where the operator
  18006. expression is a polymorphic function. In that case the type arguments
  18007. are deduced by matching the type of the parameters with the types of
  18008. the arguments.
  18009. %
  18010. The \code{match-types} auxiliary function carries out this deduction
  18011. by recursively descending through a parameter type \code{pt} and the
  18012. corresponding argument type \code{at}, making sure that they are equal
  18013. except when there is a type parameter on the left (in the parameter
  18014. type). If it is the first time that the type parameter has been
  18015. encountered, then the algorithm deduces an association of the type
  18016. parameter to the corresponding type on the right (in the argument
  18017. type). If it is not the first time that the type parameter has been
  18018. encountered, the algorithm looks up its deduced type and makes sure
  18019. that it is equal to the type on the right.
  18020. %
  18021. Once the type arguments are deduced, the operator expression is
  18022. wrapped in an \code{Inst} AST node (for instantiate) that records the
  18023. type of the operator, but more importantly, records the deduced type
  18024. arguments. The return type of the application is the return type of
  18025. the polymorphic function, but with the type parameters replaced by the
  18026. deduced type arguments, using the \code{subst-type} function.
  18027. The second responsibility of the type checker is extending the
  18028. function \code{type-equal?} to handle the \code{All} type. This is
  18029. not quite a simple as equal on other types, such as function and
  18030. vector types, because two polymorphic types can be syntactically
  18031. different even though they are equivalent types. For example,
  18032. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  18033. Two polymorphic types should be considered equal if they differ only
  18034. in the choice of the names of the type parameters. The
  18035. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  18036. renames the type parameters of the first type to match the type
  18037. parameters of the second type.
  18038. The third responsibility of the type checker is making sure that only
  18039. defined type variables appear in type annotations. The
  18040. \code{check-well-formed} function defined in
  18041. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  18042. sure that each type variable has been defined.
  18043. The output language of the type checker is \LangInst{}, defined in
  18044. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  18045. declaration and polymorphic function into a single definition, using
  18046. the \code{Poly} form, to make polymorphic functions more convenient to
  18047. process in next pass of the compiler.
  18048. \begin{figure}[tp]
  18049. \centering
  18050. \fbox{
  18051. \begin{minipage}{0.96\textwidth}
  18052. \small
  18053. \[
  18054. \begin{array}{lcl}
  18055. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18056. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  18057. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  18058. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  18059. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18060. \end{array}
  18061. \]
  18062. \end{minipage}
  18063. }
  18064. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  18065. (Figure~\ref{fig:Lwhile-syntax}).}
  18066. \label{fig:Rpoly-prime-syntax}
  18067. \end{figure}
  18068. The output of the type checker on the polymorphic \code{map}
  18069. example is listed in Figure~\ref{fig:map-type-check}.
  18070. \begin{figure}[tbp]
  18071. % poly_test_2.rkt
  18072. \begin{lstlisting}
  18073. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  18074. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  18075. (define (inc [x : Integer]) : Integer (+ x 1))
  18076. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18077. (Integer))
  18078. inc (vector 0 41)) 1)
  18079. \end{lstlisting}
  18080. \caption{Output of the type checker on the \code{map} example.}
  18081. \label{fig:map-type-check}
  18082. \end{figure}
  18083. \begin{figure}[tbp]
  18084. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18085. (define type-check-poly-class
  18086. (class type-check-Rwhile-class
  18087. (super-new)
  18088. (inherit check-type-equal?)
  18089. (define/override (type-check-apply env e1 es)
  18090. (define-values (e^ ty) ((type-check-exp env) e1))
  18091. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  18092. ((type-check-exp env) e)))
  18093. (match ty
  18094. [`(,ty^* ... -> ,rt)
  18095. (for ([arg-ty ty*] [param-ty ty^*])
  18096. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  18097. (values e^ es^ rt)]
  18098. [`(All ,xs (,tys ... -> ,rt))
  18099. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18100. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  18101. (match-types env^^ param-ty arg-ty)))
  18102. (define targs
  18103. (for/list ([x xs])
  18104. (match (dict-ref env^^ x (lambda () #f))
  18105. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  18106. x (Apply e1 es))]
  18107. [ty ty])))
  18108. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  18109. [else (error 'type-check "expected a function, not ~a" ty)]))
  18110. (define/override ((type-check-exp env) e)
  18111. (match e
  18112. [(Lambda `([,xs : ,Ts] ...) rT body)
  18113. (for ([T Ts]) ((check-well-formed env) T))
  18114. ((check-well-formed env) rT)
  18115. ((super type-check-exp env) e)]
  18116. [(HasType e1 ty)
  18117. ((check-well-formed env) ty)
  18118. ((super type-check-exp env) e)]
  18119. [else ((super type-check-exp env) e)]))
  18120. (define/override ((type-check-def env) d)
  18121. (verbose 'type-check "poly/def" d)
  18122. (match d
  18123. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  18124. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  18125. (for ([p ps]) ((check-well-formed ts-env) p))
  18126. ((check-well-formed ts-env) rt)
  18127. (define new-env (append ts-env (map cons xs ps) env))
  18128. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18129. (check-type-equal? ty^ rt body)
  18130. (Generic ts (Def f p:t* rt info body^))]
  18131. [else ((super type-check-def env) d)]))
  18132. (define/override (type-check-program p)
  18133. (match p
  18134. [(Program info body)
  18135. (type-check-program (ProgramDefsExp info '() body))]
  18136. [(ProgramDefsExp info ds body)
  18137. (define ds^ (combine-decls-defs ds))
  18138. (define new-env (for/list ([d ds^])
  18139. (cons (def-name d) (fun-def-type d))))
  18140. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  18141. (define-values (body^ ty) ((type-check-exp new-env) body))
  18142. (check-type-equal? ty 'Integer body)
  18143. (ProgramDefsExp info ds^^ body^)]))
  18144. ))
  18145. \end{lstlisting}
  18146. \caption{Type checker for the \LangPoly{} language.}
  18147. \label{fig:type-check-Lvar0}
  18148. \end{figure}
  18149. \begin{figure}[tbp]
  18150. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18151. (define/override (type-equal? t1 t2)
  18152. (match* (t1 t2)
  18153. [(`(All ,xs ,T1) `(All ,ys ,T2))
  18154. (define env (map cons xs ys))
  18155. (type-equal? (subst-type env T1) T2)]
  18156. [(other wise)
  18157. (super type-equal? t1 t2)]))
  18158. (define/public (match-types env pt at)
  18159. (match* (pt at)
  18160. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  18161. [('Void 'Void) env] [('Any 'Any) env]
  18162. [(`(Vector ,pts ...) `(Vector ,ats ...))
  18163. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  18164. (match-types env^ pt1 at1))]
  18165. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  18166. (define env^ (match-types env prt art))
  18167. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  18168. (match-types env^^ pt1 at1))]
  18169. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  18170. (define env^ (append (map cons pxs axs) env))
  18171. (match-types env^ pt1 at1)]
  18172. [((? symbol? x) at)
  18173. (match (dict-ref env x (lambda () #f))
  18174. [#f (error 'type-check "undefined type variable ~a" x)]
  18175. ['Type (cons (cons x at) env)]
  18176. [t^ (check-type-equal? at t^ 'matching) env])]
  18177. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  18178. (define/public (subst-type env pt)
  18179. (match pt
  18180. ['Integer 'Integer] ['Boolean 'Boolean]
  18181. ['Void 'Void] ['Any 'Any]
  18182. [`(Vector ,ts ...)
  18183. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  18184. [`(,ts ... -> ,rt)
  18185. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  18186. [`(All ,xs ,t)
  18187. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  18188. [(? symbol? x) (dict-ref env x)]
  18189. [else (error 'type-check "expected a type not ~a" pt)]))
  18190. (define/public (combine-decls-defs ds)
  18191. (match ds
  18192. ['() '()]
  18193. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  18194. (unless (equal? name f)
  18195. (error 'type-check "name mismatch, ~a != ~a" name f))
  18196. (match type
  18197. [`(All ,xs (,ps ... -> ,rt))
  18198. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18199. (cons (Generic xs (Def name params^ rt info body))
  18200. (combine-decls-defs ds^))]
  18201. [`(,ps ... -> ,rt)
  18202. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18203. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  18204. [else (error 'type-check "expected a function type, not ~a" type) ])]
  18205. [`(,(Def f params rt info body) . ,ds^)
  18206. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  18207. \end{lstlisting}
  18208. \caption{Auxiliary functions for type checking \LangPoly{}.}
  18209. \label{fig:type-check-Lvar0-aux}
  18210. \end{figure}
  18211. \begin{figure}[tbp]
  18212. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  18213. (define/public ((check-well-formed env) ty)
  18214. (match ty
  18215. ['Integer (void)]
  18216. ['Boolean (void)]
  18217. ['Void (void)]
  18218. [(? symbol? a)
  18219. (match (dict-ref env a (lambda () #f))
  18220. ['Type (void)]
  18221. [else (error 'type-check "undefined type variable ~a" a)])]
  18222. [`(Vector ,ts ...)
  18223. (for ([t ts]) ((check-well-formed env) t))]
  18224. [`(,ts ... -> ,t)
  18225. (for ([t ts]) ((check-well-formed env) t))
  18226. ((check-well-formed env) t)]
  18227. [`(All ,xs ,t)
  18228. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18229. ((check-well-formed env^) t)]
  18230. [else (error 'type-check "unrecognized type ~a" ty)]))
  18231. \end{lstlisting}
  18232. \caption{Well-formed types.}
  18233. \label{fig:well-formed-types}
  18234. \end{figure}
  18235. % TODO: interpreter for R'_10
  18236. \section{Compiling Polymorphism}
  18237. \label{sec:compiling-poly}
  18238. Broadly speaking, there are four approaches to compiling parametric
  18239. polymorphism, which we describe below.
  18240. \begin{description}
  18241. \item[Monomorphization] generates a different version of a polymorphic
  18242. function for each set of type arguments that it is used with,
  18243. producing type-specialized code. This approach results in the most
  18244. efficient code but requires whole-program compilation (no separate
  18245. compilation) and increases code size. For our current purposes
  18246. monomorphization is a non-starter because, with first-class
  18247. polymorphism, it is sometimes not possible to determine which
  18248. generic functions are used with which type arguments during
  18249. compilation. (It can be done at runtime, with just-in-time
  18250. compilation.) This approach is used to compile C++
  18251. templates~\citep{stroustrup88:_param_types} and polymorphic
  18252. functions in NESL~\citep{Blelloch:1993aa} and
  18253. ML~\citep{Weeks:2006aa}.
  18254. \item[Uniform representation] generates one version of each
  18255. polymorphic function but requires all values have a common ``boxed''
  18256. format, such as the tagged values of type \code{Any} in
  18257. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  18258. similarly to code in a dynamically typed language (like \LangDyn{}),
  18259. in which primitive operators require their arguments to be projected
  18260. from \code{Any} and their results are injected into \code{Any}. (In
  18261. object-oriented languages, the projection is accomplished via
  18262. virtual method dispatch.) The uniform representation approach is
  18263. compatible with separate compilation and with first-class
  18264. polymorphism. However, it produces the least-efficient code because
  18265. it introduces overhead in the entire program, including
  18266. non-polymorphic code. This approach is used in implementations of
  18267. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  18268. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  18269. Java~\citep{Bracha:1998fk}.
  18270. \item[Mixed representation] generates one version of each polymorphic
  18271. function, using a boxed representation for type
  18272. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  18273. and conversions are performed at the boundaries between monomorphic
  18274. and polymorphic (e.g. when a polymorphic function is instantiated
  18275. and called). This approach is compatible with separate compilation
  18276. and first-class polymorphism and maintains the efficiency of
  18277. monomorphic code. The tradeoff is increased overhead at the boundary
  18278. between monomorphic and polymorphic code. This approach is used in
  18279. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  18280. Java 5 with the addition of autoboxing.
  18281. \item[Type passing] uses the unboxed representation in both
  18282. monomorphic and polymorphic code. Each polymorphic function is
  18283. compiled to a single function with extra parameters that describe
  18284. the type arguments. The type information is used by the generated
  18285. code to know how to access the unboxed values at runtime. This
  18286. approach is used in implementation of the Napier88
  18287. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  18288. passing is compatible with separate compilation and first-class
  18289. polymorphism and maintains the efficiency for monomorphic
  18290. code. There is runtime overhead in polymorphic code from dispatching
  18291. on type information.
  18292. \end{description}
  18293. In this chapter we use the mixed representation approach, partly
  18294. because of its favorable attributes, and partly because it is
  18295. straightforward to implement using the tools that we have already
  18296. built to support gradual typing. To compile polymorphic functions, we
  18297. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  18298. \LangCast{}.
  18299. \section{Erase Types}
  18300. \label{sec:erase-types}
  18301. We use the \code{Any} type from Chapter~\ref{ch:Ldyn} to
  18302. represent type variables. For example, Figure~\ref{fig:map-erase}
  18303. shows the output of the \code{erase-types} pass on the polymorphic
  18304. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  18305. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  18306. \code{All} types are removed from the type of \code{map}.
  18307. \begin{figure}[tbp]
  18308. \begin{lstlisting}
  18309. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  18310. : (Vector Any Any)
  18311. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18312. (define (inc [x : Integer]) : Integer (+ x 1))
  18313. (vector-ref ((cast map
  18314. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18315. ((Integer -> Integer) (Vector Integer Integer)
  18316. -> (Vector Integer Integer)))
  18317. inc (vector 0 41)) 1)
  18318. \end{lstlisting}
  18319. \caption{The polymorphic \code{map} example after type erasure.}
  18320. \label{fig:map-erase}
  18321. \end{figure}
  18322. This process of type erasure creates a challenge at points of
  18323. instantiation. For example, consider the instantiation of
  18324. \code{map} in Figure~\ref{fig:map-type-check}.
  18325. The type of \code{map} is
  18326. \begin{lstlisting}
  18327. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18328. \end{lstlisting}
  18329. and it is instantiated to
  18330. \begin{lstlisting}
  18331. ((Integer -> Integer) (Vector Integer Integer)
  18332. -> (Vector Integer Integer))
  18333. \end{lstlisting}
  18334. After erasure, the type of \code{map} is
  18335. \begin{lstlisting}
  18336. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18337. \end{lstlisting}
  18338. but we need to convert it to the instantiated type. This is easy to
  18339. do in the target language \LangCast{} with a single \code{cast}. In
  18340. Figure~\ref{fig:map-erase}, the instantiation of \code{map}
  18341. has been compiled to a \code{cast} from the type of \code{map} to
  18342. the instantiated type. The source and target type of a cast must be
  18343. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  18344. because both the source and target are obtained from the same
  18345. polymorphic type of \code{map}, replacing the type parameters with
  18346. \code{Any} in the former and with the deduced type arguments in the
  18347. later. (Recall that the \code{Any} type is consistent with any type.)
  18348. To implement the \code{erase-types} pass, we recommend defining a
  18349. recursive auxiliary function named \code{erase-type} that applies the
  18350. following two transformations. It replaces type variables with
  18351. \code{Any}
  18352. \begin{lstlisting}
  18353. |$x$|
  18354. |$\Rightarrow$|
  18355. Any
  18356. \end{lstlisting}
  18357. and it removes the polymorphic \code{All} types.
  18358. \begin{lstlisting}
  18359. (All |$xs$| |$T_1$|)
  18360. |$\Rightarrow$|
  18361. |$T'_1$|
  18362. \end{lstlisting}
  18363. Apply the \code{erase-type} function to all of the type annotations in
  18364. the program.
  18365. Regarding the translation of expressions, the case for \code{Inst} is
  18366. the interesting one. We translate it into a \code{Cast}, as shown
  18367. below. The type of the subexpression $e$ is the polymorphic type
  18368. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  18369. $T$, the type $T'$. The target type $T''$ is the result of
  18370. substituting the arguments types $ts$ for the type parameters $xs$ in
  18371. $T$ followed by doing type erasure.
  18372. \begin{lstlisting}
  18373. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  18374. |$\Rightarrow$|
  18375. (Cast |$e'$| |$T'$| |$T''$|)
  18376. \end{lstlisting}
  18377. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  18378. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  18379. Finally, each polymorphic function is translated to a regular
  18380. functions in which type erasure has been applied to all the type
  18381. annotations and the body.
  18382. \begin{lstlisting}
  18383. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  18384. |$\Rightarrow$|
  18385. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  18386. \end{lstlisting}
  18387. \begin{exercise}\normalfont
  18388. Implement a compiler for the polymorphic language \LangPoly{} by
  18389. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  18390. programs that use polymorphic functions. Some of them should make
  18391. use of first-class polymorphism.
  18392. \end{exercise}
  18393. \begin{figure}[p]
  18394. \begin{tikzpicture}[baseline=(current bounding box.center)]
  18395. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  18396. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  18397. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  18398. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  18399. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  18400. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  18401. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  18402. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  18403. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  18404. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  18405. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  18406. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  18407. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  18408. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  18409. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  18410. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  18411. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  18412. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  18413. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  18414. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  18415. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  18416. \path[->,bend right=15] (Rpoly) edge [above] node
  18417. {\ttfamily\footnotesize type\_check} (Rpolyp);
  18418. \path[->,bend right=15] (Rpolyp) edge [above] node
  18419. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  18420. \path[->,bend right=15] (Rgradualp) edge [above] node
  18421. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  18422. \path[->,bend right=15] (Rwhilepp) edge [right] node
  18423. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  18424. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  18425. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  18426. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  18427. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  18428. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  18429. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  18430. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  18431. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  18432. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  18433. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  18434. \path[->,bend left=15] (F1-1) edge [below] node
  18435. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  18436. \path[->,bend right=15] (F1-2) edge [above] node
  18437. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  18438. \path[->,bend right=15] (F1-3) edge [above] node
  18439. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  18440. \path[->,bend right=15] (F1-4) edge [above] node
  18441. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  18442. \path[->,bend right=15] (F1-5) edge [right] node
  18443. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18444. \path[->,bend left=15] (C3-2) edge [left] node
  18445. {\ttfamily\footnotesize select\_instr.} (x86-2);
  18446. \path[->,bend right=15] (x86-2) edge [left] node
  18447. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18448. \path[->,bend right=15] (x86-2-1) edge [below] node
  18449. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  18450. \path[->,bend right=15] (x86-2-2) edge [left] node
  18451. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  18452. \path[->,bend left=15] (x86-3) edge [above] node
  18453. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  18454. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  18455. \end{tikzpicture}
  18456. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  18457. \label{fig:Rpoly-passes}
  18458. \end{figure}
  18459. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  18460. for the compilation of \LangPoly{}.
  18461. % TODO: challenge problem: specialization of instantiations
  18462. % Further Reading
  18463. \fi
  18464. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18465. \clearpage
  18466. \appendix
  18467. \chapter{Appendix}
  18468. \if\edition\racketEd
  18469. \section{Interpreters}
  18470. \label{appendix:interp}
  18471. \index{subject}{interpreter}
  18472. We provide interpreters for each of the source languages \LangInt{},
  18473. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  18474. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  18475. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  18476. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  18477. and x86 are in the \key{interp.rkt} file.
  18478. \section{Utility Functions}
  18479. \label{appendix:utilities}
  18480. The utility functions described in this section are in the
  18481. \key{utilities.rkt} file of the support code.
  18482. \paragraph{\code{interp-tests}}
  18483. The \key{interp-tests} function runs the compiler passes and the
  18484. interpreters on each of the specified tests to check whether each pass
  18485. is correct. The \key{interp-tests} function has the following
  18486. parameters:
  18487. \begin{description}
  18488. \item[name (a string)] a name to identify the compiler,
  18489. \item[typechecker] a function of exactly one argument that either
  18490. raises an error using the \code{error} function when it encounters a
  18491. type error, or returns \code{\#f} when it encounters a type
  18492. error. If there is no type error, the type checker returns the
  18493. program.
  18494. \item[passes] a list with one entry per pass. An entry is a list with
  18495. four things:
  18496. \begin{enumerate}
  18497. \item a string giving the name of the pass,
  18498. \item the function that implements the pass (a translator from AST
  18499. to AST),
  18500. \item a function that implements the interpreter (a function from
  18501. AST to result value) for the output language,
  18502. \item and a type checker for the output language. Type checkers for
  18503. the $R$ and $C$ languages are provided in the support code. For
  18504. example, the type checkers for \LangVar{} and \LangCVar{} are in
  18505. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  18506. type checker entry is optional. The support code does not provide
  18507. type checkers for the x86 languages.
  18508. \end{enumerate}
  18509. \item[source-interp] an interpreter for the source language. The
  18510. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  18511. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  18512. \item[tests] a list of test numbers that specifies which tests to
  18513. run. (see below)
  18514. \end{description}
  18515. %
  18516. The \key{interp-tests} function assumes that the subdirectory
  18517. \key{tests} has a collection of Racket programs whose names all start
  18518. with the family name, followed by an underscore and then the test
  18519. number, ending with the file extension \key{.rkt}. Also, for each test
  18520. program that calls \code{read} one or more times, there is a file with
  18521. the same name except that the file extension is \key{.in} that
  18522. provides the input for the Racket program. If the test program is
  18523. expected to fail type checking, then there should be an empty file of
  18524. the same name but with extension \key{.tyerr}.
  18525. \paragraph{\code{compiler-tests}}
  18526. runs the compiler passes to generate x86 (a \key{.s} file) and then
  18527. runs the GNU C compiler (gcc) to generate machine code. It runs the
  18528. machine code and checks that the output is $42$. The parameters to the
  18529. \code{compiler-tests} function are similar to those of the
  18530. \code{interp-tests} function, and consist of
  18531. \begin{itemize}
  18532. \item a compiler name (a string),
  18533. \item a type checker,
  18534. \item description of the passes,
  18535. \item name of a test-family, and
  18536. \item a list of test numbers.
  18537. \end{itemize}
  18538. \paragraph{\code{compile-file}}
  18539. takes a description of the compiler passes (see the comment for
  18540. \key{interp-tests}) and returns a function that, given a program file
  18541. name (a string ending in \key{.rkt}), applies all of the passes and
  18542. writes the output to a file whose name is the same as the program file
  18543. name but with \key{.rkt} replaced with \key{.s}.
  18544. \paragraph{\code{read-program}}
  18545. takes a file path and parses that file (it must be a Racket program)
  18546. into an abstract syntax tree.
  18547. \paragraph{\code{parse-program}}
  18548. takes an S-expression representation of an abstract syntax tree and converts it into
  18549. the struct-based representation.
  18550. \paragraph{\code{assert}}
  18551. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  18552. and displays the message \key{msg} if the Boolean \key{bool} is false.
  18553. \paragraph{\code{lookup}}
  18554. % remove discussion of lookup? -Jeremy
  18555. takes a key and an alist, and returns the first value that is
  18556. associated with the given key, if there is one. If not, an error is
  18557. triggered. The alist may contain both immutable pairs (built with
  18558. \key{cons}) and mutable pairs (built with \key{mcons}).
  18559. %The \key{map2} function ...
  18560. \fi %\racketEd
  18561. \section{x86 Instruction Set Quick-Reference}
  18562. \label{sec:x86-quick-reference}
  18563. \index{subject}{x86}
  18564. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  18565. do. We write $A \to B$ to mean that the value of $A$ is written into
  18566. location $B$. Address offsets are given in bytes. The instruction
  18567. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  18568. registers (such as \code{\%rax}), or memory references (such as
  18569. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  18570. reference per instruction. Other operands must be immediates or
  18571. registers.
  18572. \begin{table}[tbp]
  18573. \centering
  18574. \begin{tabular}{l|l}
  18575. \textbf{Instruction} & \textbf{Operation} \\ \hline
  18576. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  18577. \texttt{negq} $A$ & $- A \to A$ \\
  18578. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  18579. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  18580. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  18581. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  18582. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  18583. \texttt{retq} & Pops the return address and jumps to it \\
  18584. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  18585. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  18586. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  18587. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  18588. be an immediate) \\
  18589. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  18590. matches the condition code of the instruction, otherwise go to the
  18591. next instructions. The condition codes are \key{e} for ``equal'',
  18592. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  18593. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  18594. \texttt{jl} $L$ & \\
  18595. \texttt{jle} $L$ & \\
  18596. \texttt{jg} $L$ & \\
  18597. \texttt{jge} $L$ & \\
  18598. \texttt{jmp} $L$ & Jump to label $L$ \\
  18599. \texttt{movq} $A$, $B$ & $A \to B$ \\
  18600. \texttt{movzbq} $A$, $B$ &
  18601. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  18602. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  18603. and the extra bytes of $B$ are set to zero.} \\
  18604. & \\
  18605. & \\
  18606. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  18607. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  18608. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  18609. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  18610. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  18611. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  18612. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  18613. description of the condition codes. $A$ must be a single byte register
  18614. (e.g., \texttt{al} or \texttt{cl}).} \\
  18615. \texttt{setl} $A$ & \\
  18616. \texttt{setle} $A$ & \\
  18617. \texttt{setg} $A$ & \\
  18618. \texttt{setge} $A$ &
  18619. \end{tabular}
  18620. \vspace{5pt}
  18621. \caption{Quick-reference for the x86 instructions used in this book.}
  18622. \label{tab:x86-instr}
  18623. \end{table}
  18624. \if\edition\racketEd
  18625. \cleardoublepage
  18626. \section{Concrete Syntax for Intermediate Languages}
  18627. The concrete syntax of \LangAny{} is defined in
  18628. Figure~\ref{fig:Rany-concrete-syntax}.
  18629. \begin{figure}[tp]
  18630. \centering
  18631. \fbox{
  18632. \begin{minipage}{0.97\textwidth}\small
  18633. \[
  18634. \begin{array}{lcl}
  18635. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  18636. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  18637. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  18638. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  18639. \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  18640. &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  18641. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  18642. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  18643. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  18644. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  18645. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  18646. \MID \LP\key{void?}\;\Exp\RP \\
  18647. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  18648. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  18649. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  18650. \end{array}
  18651. \]
  18652. \end{minipage}
  18653. }
  18654. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  18655. (Figure~\ref{fig:Rlam-syntax}).}
  18656. \label{fig:Rany-concrete-syntax}
  18657. \end{figure}
  18658. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  18659. \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  18660. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  18661. \ref{fig:c3-concrete-syntax}, respectively.
  18662. \begin{figure}[tbp]
  18663. \fbox{
  18664. \begin{minipage}{0.96\textwidth}
  18665. \small
  18666. \[
  18667. \begin{array}{lcl}
  18668. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  18669. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18670. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  18671. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  18672. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  18673. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  18674. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  18675. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  18676. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  18677. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  18678. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  18679. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  18680. \end{array}
  18681. \]
  18682. \end{minipage}
  18683. }
  18684. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  18685. \label{fig:c2-concrete-syntax}
  18686. \end{figure}
  18687. \begin{figure}[tp]
  18688. \fbox{
  18689. \begin{minipage}{0.96\textwidth}
  18690. \small
  18691. \[
  18692. \begin{array}{lcl}
  18693. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  18694. \\
  18695. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18696. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  18697. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  18698. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  18699. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  18700. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  18701. &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  18702. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  18703. \MID \LP\key{collect} \,\itm{int}\RP }\\
  18704. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  18705. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  18706. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  18707. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  18708. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  18709. \LangCFunM{} & ::= & \Def\ldots
  18710. \end{array}
  18711. \]
  18712. \end{minipage}
  18713. }
  18714. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  18715. \label{fig:c3-concrete-syntax}
  18716. \end{figure}
  18717. \fi % racketEd
  18718. \backmatter
  18719. \addtocontents{toc}{\vspace{11pt}}
  18720. %% \addtocontents{toc}{\vspace{11pt}}
  18721. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  18722. \nocite{*}\let\bibname\refname
  18723. \addcontentsline{toc}{fmbm}{\refname}
  18724. \printbibliography
  18725. \printindex{authors}{Author Index}
  18726. \printindex{subject}{Subject Index}
  18727. \end{document}
  18728. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  18729. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  18730. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  18731. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  18732. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  18733. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  18734. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  18735. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  18736. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  18737. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  18738. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  18739. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  18740. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  18741. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  18742. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  18743. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  18744. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  18745. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  18746. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  18747. % LocalWords: morekeywords fullflexible