book.tex 653 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089
  1. \documentclass[7x10]{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{1}
  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},
  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 ground breaking 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 by 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, 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 code that runs on hardware. We
  149. take this approach to the extreme by partitioning our compiler into a
  150. large number of \emph{nanopasses}, each of which performs a single
  151. task. This allows us to test the output of each pass in isolation, and
  152. furthermore, allows us to focus our attention which makes the compiler
  153. far easier to understand.
  154. The most familiar approach to describing compilers is with one pass
  155. per chapter. The problem with that approach is it obfuscates how
  156. language features motivate design choices in a compiler. We take an
  157. \emph{incremental} approach in which we build a complete compiler in
  158. each chapter, starting with a small input language that includes only
  159. arithmetic and variables and we add new language features in
  160. subsequent chapters.
  161. Our choice of language features is designed to elicit the fundamental
  162. concepts and algorithms used in compilers.
  163. \begin{itemize}
  164. \item We begin with integer arithmetic and local variables in
  165. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  166. the fundamental tools of compiler construction: \emph{abstract
  167. syntax trees} and \emph{recursive functions}.
  168. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  169. \emph{graph coloring} to assign variables to machine registers.
  170. \item Chapter~\ref{ch:Lif} adds \code{if} expressions, which motivates
  171. an elegant recursive algorithm for translating them into conditional
  172. \code{goto}'s.
  173. \item Chapter~\ref{ch:Lwhile} fleshes out support for imperative
  174. programming languages with the addition of 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:Rfun} adds functions that are first-class values
  180. but lack lexical scoping, similar to the C programming
  181. language~\citep{Kernighan:1988nx} except that we generate efficient
  182. tail calls. The reader learns about the procedure call stack,
  183. \emph{calling conventions}, and their interaction with register
  184. allocation and garbage collection.
  185. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  186. scoping, i.e., \emph{lambda abstraction}. 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:Rdyn} 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:Robject} adds support for \emph{objects} and
  196. \emph{classes}.
  197. \fi}
  198. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  199. Chapter~\ref{ch:Rdyn} 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:Rpoly} adds \emph{generics} with autoboxing,
  204. leveraging the \code{Any} type and type casts developed in Chapters
  205. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  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}. Many chapters include a challenge problem that
  224. we assign to the graduate students. The last two weeks of the course
  225. involve a final project in which students design and implement a
  226. compiler extension of their choosing. Chapters~\ref{ch:Rgrad} and
  227. \ref{ch:Rpoly} can be used in support of these projects or they can
  228. replace some of the other chapters. For example, a course with an
  229. emphasis on statically-typed imperative languages could include
  230. Chapter~\ref{ch:Rpoly} but skip Chapter~\ref{ch:Rdyn}. For compiler
  231. courses at universities on the quarter system, with 10 weeks, we
  232. recommend completing up through Chapter~\ref{ch:Rfun}. (If pressed
  233. for time, one can skip Chapter~\ref{ch:Lvec} but still include
  234. Chapter~\ref{ch:Rfun} by limiting the number of parameters allowed in
  235. functions.) Figure~\ref{fig:chapter-dependences} depicts the
  236. dependencies between chapters.
  237. This book has also been used in compiler courses at California
  238. Polytechnic State University, Portland State University, Rose–Hulman
  239. Institute of Technology, University of Massachusetts Lowell, and the
  240. University of Vermont.
  241. \begin{figure}[tp]
  242. {\if\edition\racketEd
  243. \begin{tikzpicture}[baseline=(current bounding box.center)]
  244. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  245. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  246. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  247. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  248. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  249. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  250. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  251. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  252. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  253. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  254. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  255. \path[->] (C1) edge [above] node {} (C2);
  256. \path[->] (C2) edge [above] node {} (C3);
  257. \path[->] (C3) edge [above] node {} (C4);
  258. \path[->] (C4) edge [above] node {} (C5);
  259. \path[->] (C5) edge [above] node {} (C6);
  260. \path[->] (C6) edge [above] node {} (C7);
  261. \path[->] (C4) edge [above] node {} (C8);
  262. \path[->] (C4) edge [above] node {} (C9);
  263. \path[->] (C8) edge [above] node {} (C10);
  264. \path[->] (C10) edge [above] node {} (C11);
  265. \end{tikzpicture}
  266. \fi}
  267. {\if\edition\pythonEd
  268. \begin{tikzpicture}[baseline=(current bounding box.center)]
  269. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  270. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  271. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  272. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  273. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  274. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  275. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  276. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  277. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Robject} Objects};
  278. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  279. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  280. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  281. \path[->] (C1) edge [above] node {} (C2);
  282. \path[->] (C2) edge [above] node {} (C3);
  283. \path[->] (C3) edge [above] node {} (C4);
  284. \path[->] (C4) edge [above] node {} (C5);
  285. \path[->] (C5) edge [above] node {} (C6);
  286. \path[->] (C6) edge [above] node {} (C7);
  287. \path[->] (C4) edge [above] node {} (C8);
  288. \path[->] (C4) edge [above] node {} (C9);
  289. \path[->] (C8) edge [above] node {} (C10);
  290. \path[->] (C8) edge [above] node {} (CO);
  291. \path[->] (C10) edge [above] node {} (C11);
  292. \end{tikzpicture}
  293. \fi}
  294. \caption{Diagram of chapter dependencies.}
  295. \label{fig:chapter-dependences}
  296. \end{figure}
  297. \racket{
  298. We use the \href{https://racket-lang.org/}{Racket} language both for
  299. the implementation of the compiler and for the input language, so the
  300. reader should be proficient with Racket or Scheme. There are many
  301. excellent resources for learning Scheme and
  302. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  303. }
  304. \python{
  305. This edition of the book uses \href{https://www.python.org/}{Python}
  306. both for the implementation of the compiler and for the input language, so the
  307. reader should be proficient with Python. There are many
  308. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  309. }
  310. The support code for this book is in the github repository at
  311. the following URL:
  312. \if\edition\racketEd
  313. \begin{center}\small
  314. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  315. \end{center}
  316. \fi
  317. \if\edition\pythonEd
  318. \begin{center}\small
  319. \url{https://github.com/IUCompilerCourse/}
  320. \end{center}
  321. \fi
  322. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  323. is helpful but not necessary for the reader to have taken a computer
  324. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  325. of x86-64 assembly language that are needed.
  326. %
  327. We follow the System V calling
  328. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  329. that we generate works with the runtime system (written in C) when it
  330. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  331. operating systems on Intel hardware.
  332. %
  333. On the Windows operating system, \code{gcc} uses the Microsoft x64
  334. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  335. assembly code that we generate does \emph{not} work with the runtime
  336. system on Windows. One workaround is to use a virtual machine with
  337. Linux as the guest operating system.
  338. \section*{Acknowledgments}
  339. The tradition of compiler construction at Indiana University goes back
  340. to research and courses on programming languages by Daniel Friedman in
  341. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  342. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  343. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  344. the compiler course and continued the development of Chez Scheme.
  345. %
  346. The compiler course evolved to incorporate novel pedagogical ideas
  347. while also including elements of real-world compilers. One of
  348. Friedman's ideas was to split the compiler into many small
  349. passes. Another idea, called ``the game'', was to test the code
  350. generated by each pass using interpreters.
  351. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  352. developed infrastructure to support this approach and evolved the
  353. course to use even smaller
  354. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  355. design decisions in this book are inspired by the assignment
  356. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  357. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  358. organization of the course made it difficult for students to
  359. understand the rationale for the compiler design. Ghuloum proposed the
  360. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  361. on.
  362. We thank the many students who served as teaching assistants for the
  363. compiler course at IU and made suggestions for improving the book
  364. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  365. thank Andre Kuhlenschmidt for his work on the garbage collector,
  366. Michael Vollmer for his work on efficient tail calls, and Michael
  367. Vitousek for his help running the first offering of the incremental
  368. compiler course at IU.
  369. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  370. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  371. for teaching courses based on drafts of this book and for their
  372. invaluable feedback.
  373. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  374. course in the early 2000's and especially for finding the bug that
  375. sent our garbage collector on a wild goose chase!
  376. \mbox{}\\
  377. \noindent Jeremy G. Siek \\
  378. Bloomington, Indiana
  379. \mainmatter
  380. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  381. \chapter{Preliminaries}
  382. \label{ch:trees-recur}
  383. In this chapter we review the basic tools that are needed to implement
  384. a compiler. Programs are typically input by a programmer as text,
  385. i.e., a sequence of characters. The program-as-text representation is
  386. called \emph{concrete syntax}. We use concrete syntax to concisely
  387. write down and talk about programs. Inside the compiler, we use
  388. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  389. that efficiently supports the operations that the compiler needs to
  390. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  391. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  392. from concrete syntax to abstract syntax is a process called
  393. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  394. implementation of parsing in this book.
  395. %
  396. \racket{A parser is provided in the support code for translating from
  397. concrete to abstract syntax.}
  398. %
  399. \python{We use Python's \code{ast} module to translate from concrete
  400. to abstract syntax.}
  401. ASTs can be represented in many different ways inside the compiler,
  402. depending on the programming language used to write the compiler.
  403. %
  404. \racket{We use Racket's
  405. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  406. feature to represent ASTs (Section~\ref{sec:ast}).}
  407. %
  408. \python{We use Python classes and objects to represent ASTs, especially the
  409. classes defined in the standard \code{ast} module for the Python
  410. source language.}
  411. %
  412. We use grammars to define the abstract syntax of programming languages
  413. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  414. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  415. recursive functions to construct and deconstruct ASTs
  416. (Section~\ref{sec:recursion}). This chapter provides an brief
  417. introduction to these ideas.
  418. \racket{\index{subject}{struct}}
  419. \python{\index{subject}{class}\index{subject}{object}}
  420. \section{Abstract Syntax Trees}
  421. \label{sec:ast}
  422. Compilers use abstract syntax trees to represent programs because they
  423. often need to ask questions like: for a given part of a program, what
  424. kind of language feature is it? What are its sub-parts? Consider the
  425. program on the left and its AST on the right. This program is an
  426. addition operation and it has two sub-parts, a
  427. \racket{read}\python{input} operation and a negation. The negation has
  428. another sub-part, the integer constant \code{8}. By using a tree to
  429. represent the program, we can easily follow the links to go from one
  430. part of a program to its sub-parts.
  431. \begin{center}
  432. \begin{minipage}{0.4\textwidth}
  433. \if\edition\racketEd
  434. \begin{lstlisting}
  435. (+ (read) (- 8))
  436. \end{lstlisting}
  437. \fi
  438. \if\edition\pythonEd
  439. \begin{lstlisting}
  440. input_int() + -8
  441. \end{lstlisting}
  442. \fi
  443. \end{minipage}
  444. \begin{minipage}{0.4\textwidth}
  445. \begin{equation}
  446. \begin{tikzpicture}
  447. \node[draw] (plus) at (0 , 0) {\key{+}};
  448. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  449. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  450. \node[draw] (8) at (1 , -3) {\key{8}};
  451. \draw[->] (plus) to (read);
  452. \draw[->] (plus) to (minus);
  453. \draw[->] (minus) to (8);
  454. \end{tikzpicture}
  455. \label{eq:arith-prog}
  456. \end{equation}
  457. \end{minipage}
  458. \end{center}
  459. We use the standard terminology for trees to describe ASTs: each
  460. rectangle above is called a \emph{node}. The arrows connect a node to its
  461. \emph{children} (which are also nodes). The top-most node is the
  462. \emph{root}. Every node except for the root has a \emph{parent} (the
  463. node it is the child of). If a node has no children, it is a
  464. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  465. \index{subject}{node}
  466. \index{subject}{children}
  467. \index{subject}{root}
  468. \index{subject}{parent}
  469. \index{subject}{leaf}
  470. \index{subject}{internal node}
  471. %% Recall that an \emph{symbolic expression} (S-expression) is either
  472. %% \begin{enumerate}
  473. %% \item an atom, or
  474. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  475. %% where $e_1$ and $e_2$ are each an S-expression.
  476. %% \end{enumerate}
  477. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  478. %% null value \code{'()}, etc. We can create an S-expression in Racket
  479. %% simply by writing a backquote (called a quasi-quote in Racket)
  480. %% followed by the textual representation of the S-expression. It is
  481. %% quite common to use S-expressions to represent a list, such as $a, b
  482. %% ,c$ in the following way:
  483. %% \begin{lstlisting}
  484. %% `(a . (b . (c . ())))
  485. %% \end{lstlisting}
  486. %% Each element of the list is in the first slot of a pair, and the
  487. %% second slot is either the rest of the list or the null value, to mark
  488. %% the end of the list. Such lists are so common that Racket provides
  489. %% special notation for them that removes the need for the periods
  490. %% and so many parenthesis:
  491. %% \begin{lstlisting}
  492. %% `(a b c)
  493. %% \end{lstlisting}
  494. %% The following expression creates an S-expression that represents AST
  495. %% \eqref{eq:arith-prog}.
  496. %% \begin{lstlisting}
  497. %% `(+ (read) (- 8))
  498. %% \end{lstlisting}
  499. %% When using S-expressions to represent ASTs, the convention is to
  500. %% represent each AST node as a list and to put the operation symbol at
  501. %% the front of the list. The rest of the list contains the children. So
  502. %% in the above case, the root AST node has operation \code{`+} and its
  503. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  504. %% diagram \eqref{eq:arith-prog}.
  505. %% To build larger S-expressions one often needs to splice together
  506. %% several smaller S-expressions. Racket provides the comma operator to
  507. %% splice an S-expression into a larger one. For example, instead of
  508. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  509. %% we could have first created an S-expression for AST
  510. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  511. %% S-expression.
  512. %% \begin{lstlisting}
  513. %% (define ast1.4 `(- 8))
  514. %% (define ast1_1 `(+ (read) ,ast1.4))
  515. %% \end{lstlisting}
  516. %% In general, the Racket expression that follows the comma (splice)
  517. %% can be any expression that produces an S-expression.
  518. {\if\edition\racketEd
  519. We define a Racket \code{struct} for each kind of node. For this
  520. chapter we require just two kinds of nodes: one for integer constants
  521. and one for primitive operations. The following is the \code{struct}
  522. definition for integer constants.
  523. \begin{lstlisting}
  524. (struct Int (value))
  525. \end{lstlisting}
  526. An integer node includes just one thing: the integer value.
  527. To create an AST node for the integer $8$, we write \INT{8}.
  528. \begin{lstlisting}
  529. (define eight (Int 8))
  530. \end{lstlisting}
  531. We say that the value created by \INT{8} is an
  532. \emph{instance} of the
  533. \code{Int} structure.
  534. The following is the \code{struct} definition for primitive operations.
  535. \begin{lstlisting}
  536. (struct Prim (op args))
  537. \end{lstlisting}
  538. A primitive operation node includes an operator symbol \code{op} and a
  539. list of child \code{args}. For example, to create an AST that negates
  540. the number $8$, we write \code{(Prim '- (list eight))}.
  541. \begin{lstlisting}
  542. (define neg-eight (Prim '- (list eight)))
  543. \end{lstlisting}
  544. Primitive operations may have zero or more children. The \code{read}
  545. operator has zero children:
  546. \begin{lstlisting}
  547. (define rd (Prim 'read '()))
  548. \end{lstlisting}
  549. whereas the addition operator has two children:
  550. \begin{lstlisting}
  551. (define ast1_1 (Prim '+ (list rd neg-eight)))
  552. \end{lstlisting}
  553. We have made a design choice regarding the \code{Prim} structure.
  554. Instead of using one structure for many different operations
  555. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  556. structure for each operation, as follows.
  557. \begin{lstlisting}
  558. (struct Read ())
  559. (struct Add (left right))
  560. (struct Neg (value))
  561. \end{lstlisting}
  562. The reason we choose to use just one structure is that in many parts
  563. of the compiler the code for the different primitive operators is the
  564. same, so we might as well just write that code once, which is enabled
  565. by using a single structure.
  566. \fi}
  567. {\if\edition\pythonEd
  568. We use a Python \code{class} for each kind of node.
  569. The following is the class definition for constants.
  570. \begin{lstlisting}
  571. class Constant:
  572. def __init__(self, value):
  573. self.value = value
  574. \end{lstlisting}
  575. An integer constant node includes just one thing: the integer value.
  576. To create an AST node for the integer $8$, we write \INT{8}.
  577. \begin{lstlisting}
  578. eight = Constant(8)
  579. \end{lstlisting}
  580. We say that the value created by \INT{8} is an
  581. \emph{instance} of the \code{Constant} class.
  582. The following is the class definition for unary operators.
  583. \begin{lstlisting}
  584. class UnaryOp:
  585. def __init__(self, op, operand):
  586. self.op = op
  587. self.operand = operand
  588. \end{lstlisting}
  589. The specific operation is specified by the \code{op} parameter. For
  590. example, the class \code{USub} is for unary subtraction. (More unary
  591. operators are introduced in later chapters.) To create an AST that
  592. negates the number $8$, we write the following.
  593. \begin{lstlisting}
  594. neg_eight = UnaryOp(USub(), eight)
  595. \end{lstlisting}
  596. The call to the \code{input\_int} function is represented by the
  597. \code{Call} and \code{Name} classes.
  598. \begin{lstlisting}
  599. class Call:
  600. def __init__(self, func, args):
  601. self.func = func
  602. self.args = args
  603. class Name:
  604. def __init__(self, id):
  605. self.id = id
  606. \end{lstlisting}
  607. To create an AST node that calls \code{input\_int}, we write
  608. \begin{lstlisting}
  609. read = Call(Name('input_int'), [])
  610. \end{lstlisting}
  611. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  612. the \code{BinOp} class for binary operators.
  613. \begin{lstlisting}
  614. class BinOp:
  615. def __init__(self, left, op, right):
  616. self.op = op
  617. self.left = left
  618. self.right = right
  619. \end{lstlisting}
  620. Similar to \code{UnaryOp}, the specific operation is specified by the
  621. \code{op} parameter, which for now is just an instance of the
  622. \code{Add} class. So to create the AST node that adds negative eight
  623. to some user input, we write the following.
  624. \begin{lstlisting}
  625. ast1_1 = BinOp(read, Add(), neg_eight)
  626. \end{lstlisting}
  627. \fi}
  628. When compiling a program such as \eqref{eq:arith-prog}, we need to
  629. know that the operation associated with the root node is addition and
  630. we need to be able to access its two children. \racket{Racket}\python{Python}
  631. provides pattern matching to support these kinds of queries, as we see in
  632. Section~\ref{sec:pattern-matching}.
  633. In this book, we often write down the concrete syntax of a program
  634. even when we really have in mind the AST because the concrete syntax
  635. is more concise. We recommend that, in your mind, you always think of
  636. programs as abstract syntax trees.
  637. \section{Grammars}
  638. \label{sec:grammar}
  639. \index{subject}{integer}
  640. \index{subject}{literal}
  641. \index{subject}{constant}
  642. A programming language can be thought of as a \emph{set} of programs.
  643. The set is typically infinite (one can always create larger and larger
  644. programs), so one cannot simply describe a language by listing all of
  645. the programs in the language. Instead we write down a set of rules, a
  646. \emph{grammar}, for building programs. Grammars are often used to
  647. define the concrete syntax of a language, but they can also be used to
  648. describe the abstract syntax. We write our rules in a variant of
  649. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  650. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  651. As an example, we describe a small language, named \LangInt{}, that consists of
  652. integers and arithmetic operations.
  653. \index{subject}{grammar}
  654. The first grammar rule for the abstract syntax of \LangInt{} says that an
  655. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  656. \begin{equation}
  657. \Exp ::= \INT{\Int} \label{eq:arith-int}
  658. \end{equation}
  659. %
  660. Each rule has a left-hand-side and a right-hand-side.
  661. If you have an AST node that matches the
  662. right-hand-side, then you can categorize it according to the
  663. left-hand-side.
  664. %
  665. A name such as $\Exp$ that is defined by the grammar rules is a
  666. \emph{non-terminal}. \index{subject}{non-terminal}
  667. %
  668. The name $\Int$ is also a non-terminal, but instead of defining it
  669. with a grammar rule, we define it with the following explanation. An
  670. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  671. $-$ (for negative integers), such that the sequence of decimals
  672. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  673. the representation of integers using 63 bits, which simplifies several
  674. aspects of compilation. \racket{Thus, these integers corresponds to
  675. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  676. \python{In contrast, integers in Python have unlimited precision, but
  677. the techniques need to handle unlimited precision fall outside the
  678. scope of this book.}
  679. The second grammar rule is the \READOP{} operation that receives an
  680. input integer from the user of the program.
  681. \begin{equation}
  682. \Exp ::= \READ{} \label{eq:arith-read}
  683. \end{equation}
  684. The third rule says that, given an $\Exp$ node, the negation of that
  685. node is also an $\Exp$.
  686. \begin{equation}
  687. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  688. \end{equation}
  689. Symbols in typewriter font are \emph{terminal} symbols and must
  690. literally appear in the program for the rule to be applicable.
  691. \index{subject}{terminal}
  692. We can apply these rules to categorize the ASTs that are in the
  693. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  694. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  695. following AST is an $\Exp$.
  696. \begin{center}
  697. \begin{minipage}{0.5\textwidth}
  698. \NEG{\INT{\code{8}}}
  699. \end{minipage}
  700. \begin{minipage}{0.25\textwidth}
  701. \begin{equation}
  702. \begin{tikzpicture}
  703. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  704. \node[draw, circle] (8) at (0, -1.2) {$8$};
  705. \draw[->] (minus) to (8);
  706. \end{tikzpicture}
  707. \label{eq:arith-neg8}
  708. \end{equation}
  709. \end{minipage}
  710. \end{center}
  711. The next grammar rules are for addition and subtraction expressions:
  712. \begin{align}
  713. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  714. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  715. \end{align}
  716. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  717. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  718. \eqref{eq:arith-read} and we have already categorized
  719. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  720. to show that
  721. \[
  722. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  723. \]
  724. is an $\Exp$ in the \LangInt{} language.
  725. If you have an AST for which the above rules do not apply, then the
  726. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  727. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  728. because there are no rules for the \key{*} operator. Whenever we
  729. define a language with a grammar, the language only includes those
  730. programs that are justified by the grammar rules.
  731. {\if\edition\pythonEd
  732. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  733. There is a statement for printing the value of an expression
  734. \[
  735. \Stmt{} ::= \PRINT{\Exp}
  736. \]
  737. and a statement that evaluates an expression but ignores the result.
  738. \[
  739. \Stmt{} ::= \EXPR{\Exp}
  740. \]
  741. \fi}
  742. {\if\edition\racketEd
  743. The last grammar rule for \LangInt{} states that there is a
  744. \code{Program} node to mark the top of the whole program:
  745. \[
  746. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  747. \]
  748. The \code{Program} structure is defined as follows
  749. \begin{lstlisting}
  750. (struct Program (info body))
  751. \end{lstlisting}
  752. where \code{body} is an expression. In later chapters, the \code{info}
  753. part will be used to store auxiliary information but for now it is
  754. just the empty list.
  755. \fi}
  756. {\if\edition\pythonEd
  757. The last grammar rule for \LangInt{} states that there is a
  758. \code{Module} node to mark the top of the whole program:
  759. \[
  760. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  761. \]
  762. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  763. this case, a list of statements.
  764. %
  765. The \code{Module} class is defined as follows
  766. \begin{lstlisting}
  767. class Module:
  768. def __init__(self, body):
  769. self.body = body
  770. \end{lstlisting}
  771. where \code{body} is a list of statements.
  772. \fi}
  773. It is common to have many grammar rules with the same left-hand side
  774. but different right-hand sides, such as the rules for $\Exp$ in the
  775. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  776. combine several right-hand-sides into a single rule.
  777. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  778. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  779. defined in Figure~\ref{fig:r0-concrete-syntax}.
  780. \racket{The \code{read-program} function provided in
  781. \code{utilities.rkt} of the support code reads a program in from a
  782. file (the sequence of characters in the concrete syntax of Racket)
  783. and parses it into an abstract syntax tree. See the description of
  784. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  785. details.}
  786. \python{The \code{parse} function in Python's \code{ast} module
  787. converts the concrete syntax (represented as a string) into an
  788. abstract syntax tree.}
  789. \newcommand{\LintGrammarRacket}{
  790. \begin{array}{rcl}
  791. \Type &::=& \key{Integer} \\
  792. \Exp{} &::=& \Int{} \MID \LP\key{read}\RP \MID \LP\key{-}\;\Exp\RP \MID \LP\key{+} \; \Exp{}\;\Exp{}\RP
  793. \end{array}
  794. }
  795. \newcommand{\LintASTRacket}{
  796. \begin{array}{rcl}
  797. \Type &::=& \key{Integer} \\
  798. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  799. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp}
  800. \end{array}
  801. }
  802. \newcommand{\LintGrammarPython}{
  803. \begin{array}{rcl}
  804. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \\
  805. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  806. \end{array}
  807. }
  808. \newcommand{\LintASTPython}{
  809. \begin{array}{rcl}
  810. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  811. \itm{unaryop} &::= & \code{USub()} \\
  812. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  813. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  814. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  815. \end{array}
  816. }
  817. \begin{figure}[tp]
  818. \fbox{
  819. \begin{minipage}{0.96\textwidth}
  820. {\if\edition\racketEd
  821. \[
  822. \begin{array}{l}
  823. \LintGrammarRacket \\
  824. \begin{array}{rcl}
  825. \LangInt{} &::=& \Exp
  826. \end{array}
  827. \end{array}
  828. \]
  829. \fi}
  830. {\if\edition\pythonEd
  831. \[
  832. \begin{array}{l}
  833. \LintGrammarPython \\
  834. \begin{array}{rcl}
  835. \LangInt{} &::=& \Stmt^{*}
  836. \end{array}
  837. \end{array}
  838. \]
  839. \fi}
  840. \end{minipage}
  841. }
  842. \caption{The concrete syntax of \LangInt{}.}
  843. \label{fig:r0-concrete-syntax}
  844. \end{figure}
  845. \begin{figure}[tp]
  846. \fbox{
  847. \begin{minipage}{0.96\textwidth}
  848. {\if\edition\racketEd
  849. \[
  850. \begin{array}{l}
  851. \LintASTRacket{} \\
  852. \begin{array}{rcl}
  853. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  854. \end{array}
  855. \end{array}
  856. \]
  857. \fi}
  858. {\if\edition\pythonEd
  859. \[
  860. \begin{array}{l}
  861. \LintASTPython\\
  862. \begin{array}{rcl}
  863. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  864. \end{array}
  865. \end{array}
  866. \]
  867. \fi}
  868. \end{minipage}
  869. }
  870. \caption{The abstract syntax of \LangInt{}.}
  871. \label{fig:r0-syntax}
  872. \end{figure}
  873. \section{Pattern Matching}
  874. \label{sec:pattern-matching}
  875. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  876. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  877. \texttt{match} feature to access the parts of a value.
  878. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  879. \begin{center}
  880. \begin{minipage}{0.5\textwidth}
  881. {\if\edition\racketEd
  882. \begin{lstlisting}
  883. (match ast1_1
  884. [(Prim op (list child1 child2))
  885. (print op)])
  886. \end{lstlisting}
  887. \fi}
  888. {\if\edition\pythonEd
  889. \begin{lstlisting}
  890. match ast1_1:
  891. case BinOp(child1, op, child2):
  892. print(op)
  893. \end{lstlisting}
  894. \fi}
  895. \end{minipage}
  896. \end{center}
  897. {\if\edition\racketEd
  898. %
  899. In the above example, the \texttt{match} form checks whether the AST
  900. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  901. three pattern variables \texttt{op}, \texttt{child1}, and
  902. \texttt{child2}, and then prints out the operator. In general, a match
  903. clause consists of a \emph{pattern} and a
  904. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  905. to be either a pattern variable, a structure name followed by a
  906. pattern for each of the structure's arguments, or an S-expression
  907. (symbols, lists, etc.). (See Chapter 12 of The Racket
  908. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  909. and Chapter 9 of The Racket
  910. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  911. for a complete description of \code{match}.)
  912. %
  913. The body of a match clause may contain arbitrary Racket code. The
  914. pattern variables can be used in the scope of the body, such as
  915. \code{op} in \code{(print op)}.
  916. %
  917. \fi}
  918. %
  919. %
  920. {\if\edition\pythonEd
  921. %
  922. In the above example, the \texttt{match} form checks whether the AST
  923. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  924. three pattern variables \texttt{child1}, \texttt{op}, and
  925. \texttt{child2}, and then prints out the operator. In general, each
  926. \code{case} consists of a \emph{pattern} and a
  927. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  928. to be either a pattern variable, a class name followed by a pattern
  929. for each of its constructor's arguments, or other literals such as
  930. strings, lists, etc.
  931. %
  932. The body of each \code{case} may contain arbitrary Python code. The
  933. pattern variables can be used in the body, such as \code{op} in
  934. \code{print(op)}.
  935. %
  936. \fi}
  937. A \code{match} form may contain several clauses, as in the following
  938. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  939. the AST. The \code{match} proceeds through the clauses in order,
  940. checking whether the pattern can match the input AST. The body of the
  941. first clause that matches is executed. The output of \code{leaf} for
  942. several ASTs is shown on the right.
  943. \begin{center}
  944. \begin{minipage}{0.6\textwidth}
  945. {\if\edition\racketEd
  946. \begin{lstlisting}
  947. (define (leaf arith)
  948. (match arith
  949. [(Int n) #t]
  950. [(Prim 'read '()) #t]
  951. [(Prim '- (list e1)) #f]
  952. [(Prim '+ (list e1 e2)) #f]))
  953. (leaf (Prim 'read '()))
  954. (leaf (Prim '- (list (Int 8))))
  955. (leaf (Int 8))
  956. \end{lstlisting}
  957. \fi}
  958. {\if\edition\pythonEd
  959. \begin{lstlisting}
  960. def leaf(arith):
  961. match arith:
  962. case Constant(n):
  963. return True
  964. case Call(Name('input_int'), []):
  965. return True
  966. case UnaryOp(USub(), e1):
  967. return False
  968. case BinOp(e1, Add(), e2):
  969. return False
  970. print(leaf(Call(Name('input_int'), [])))
  971. print(leaf(UnaryOp(USub(), eight)))
  972. print(leaf(Constant(8)))
  973. \end{lstlisting}
  974. \fi}
  975. \end{minipage}
  976. \vrule
  977. \begin{minipage}{0.25\textwidth}
  978. {\if\edition\racketEd
  979. \begin{lstlisting}
  980. #t
  981. #f
  982. #t
  983. \end{lstlisting}
  984. \fi}
  985. {\if\edition\pythonEd
  986. \begin{lstlisting}
  987. True
  988. False
  989. True
  990. \end{lstlisting}
  991. \fi}
  992. \end{minipage}
  993. \end{center}
  994. When writing a \code{match}, we refer to the grammar definition to
  995. identify which non-terminal we are expecting to match against, then we
  996. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  997. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  998. corresponding right-hand side of a grammar rule. For the \code{match}
  999. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  1000. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  1001. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  1002. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  1003. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  1004. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  1005. patterns, replace non-terminals such as $\Exp$ with pattern variables
  1006. of your choice (e.g. \code{e1} and \code{e2}).
  1007. \section{Recursive Functions}
  1008. \label{sec:recursion}
  1009. \index{subject}{recursive function}
  1010. Programs are inherently recursive. For example, an expression is often
  1011. made of smaller expressions. Thus, the natural way to process an
  1012. entire program is with a recursive function. As a first example of
  1013. such a recursive function, we define the function \code{exp} in
  1014. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1015. determines whether or not it is an expression in \LangInt{}.
  1016. %
  1017. We say that a function is defined by \emph{structural recursion} when
  1018. it is defined using a sequence of match \racket{clauses}\python{cases}
  1019. that correspond to a grammar, and the body of each
  1020. \racket{clause}\python{case} makes a recursive call on each child
  1021. node.\footnote{This principle of structuring code according to the
  1022. data definition is advocated in the book \emph{How to Design
  1023. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  1024. \python{We define a second function, named \code{stmt}, that
  1025. recognizes whether a value is a \LangInt{} statement.}
  1026. \python{Finally, } Figure~\ref{fig:exp-predicate} \racket{also}
  1027. defines \code{Lint}, which determines whether an AST is a program in
  1028. \LangInt{}. In general we can expect to write one recursive function
  1029. to handle each non-terminal in a grammar.\index{subject}{structural
  1030. recursion} Of the two examples at the bottom of the figure, the
  1031. first is in \code{Lint} and the second is not.
  1032. \begin{figure}[tp]
  1033. {\if\edition\racketEd
  1034. \begin{lstlisting}
  1035. (define (exp ast)
  1036. (match ast
  1037. [(Int n) #t]
  1038. [(Prim 'read '()) #t]
  1039. [(Prim '- (list e)) (exp e)]
  1040. [(Prim '+ (list e1 e2))
  1041. (and (exp e1) (exp e2))]
  1042. [else #f]))
  1043. (define (Lint ast)
  1044. (match ast
  1045. [(Program '() e) (exp e)]
  1046. [else #f]))
  1047. (Lint (Program '() ast1_1)
  1048. (Lint (Program '()
  1049. (Prim '- (list (Prim 'read '())
  1050. (Prim '+ (list (Num 8)))))))
  1051. \end{lstlisting}
  1052. \fi}
  1053. {\if\edition\pythonEd
  1054. \begin{lstlisting}
  1055. def exp(e):
  1056. match e:
  1057. case Constant(n):
  1058. return True
  1059. case Call(Name('input_int'), []):
  1060. return True
  1061. case UnaryOp(USub(), e1):
  1062. return exp(e1)
  1063. case BinOp(e1, Add(), e2):
  1064. return exp(e1) and exp(e2)
  1065. case BinOp(e1, Sub(), e2):
  1066. return exp(e1) and exp(e2)
  1067. case _:
  1068. return False
  1069. def stmt(s):
  1070. match s:
  1071. case Call(Name('print'), [e]):
  1072. return exp(e)
  1073. case Expr(e):
  1074. return exp(e)
  1075. case _:
  1076. return False
  1077. def Lint(p):
  1078. match p:
  1079. case Module(body):
  1080. return all([stmt(s) for s in body])
  1081. case _:
  1082. return False
  1083. print(Lint(Module([Expr(ast1_1)])))
  1084. print(Lint(Module([Expr(BinOp(read, Sub(),
  1085. UnaryOp(Add(), Constant(8))))])))
  1086. \end{lstlisting}
  1087. \fi}
  1088. \caption{Example of recursive functions for \LangInt{}. These functions
  1089. recognize whether an AST is in \LangInt{}.}
  1090. \label{fig:exp-predicate}
  1091. \end{figure}
  1092. %% You may be tempted to merge the two functions into one, like this:
  1093. %% \begin{center}
  1094. %% \begin{minipage}{0.5\textwidth}
  1095. %% \begin{lstlisting}
  1096. %% (define (Lint ast)
  1097. %% (match ast
  1098. %% [(Int n) #t]
  1099. %% [(Prim 'read '()) #t]
  1100. %% [(Prim '- (list e)) (Lint e)]
  1101. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1102. %% [(Program '() e) (Lint e)]
  1103. %% [else #f]))
  1104. %% \end{lstlisting}
  1105. %% \end{minipage}
  1106. %% \end{center}
  1107. %% %
  1108. %% Sometimes such a trick will save a few lines of code, especially when
  1109. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1110. %% \emph{not} recommended because it can get you into trouble.
  1111. %% %
  1112. %% For example, the above function is subtly wrong:
  1113. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1114. %% returns true when it should return false.
  1115. \section{Interpreters}
  1116. \label{sec:interp_Lint}
  1117. \index{subject}{interpreter}
  1118. The behavior of a program is defined by the specification of the
  1119. programming language.
  1120. %
  1121. \racket{For example, the Scheme language is defined in the report by
  1122. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1123. reference manual~\citep{plt-tr}.}
  1124. %
  1125. \python{For example, the Python language is defined in the Python
  1126. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1127. %
  1128. In this book we use interpreters
  1129. to specify each language that we consider. An interpreter that is
  1130. designated as the definition of a language is called a
  1131. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1132. \index{subject}{definitional interpreter} We warm up by creating a
  1133. definitional interpreter for the \LangInt{} language, which serves as
  1134. a second example of structural recursion. The \code{interp\_Lint}
  1135. function is defined in Figure~\ref{fig:interp_Lint}.
  1136. %
  1137. \racket{The body of the function is a match on the input program
  1138. followed by a call to the \lstinline{interp_exp} helper function,
  1139. which in turn has one match clause per grammar rule for \LangInt{}
  1140. expressions.}
  1141. %
  1142. \python{The body of the function matches on the \code{Module} AST node
  1143. and then invokes \code{interp\_stmt} on each statement in the
  1144. module. The \code{interp\_stmt} function includes a case for each
  1145. grammar rule of the \Stmt{} non-terminal and it calls
  1146. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1147. function includes a case for each grammar rule of the \Exp{}
  1148. non-terminal.}
  1149. \begin{figure}[tp]
  1150. {\if\edition\racketEd
  1151. \begin{lstlisting}
  1152. (define (interp_exp e)
  1153. (match e
  1154. [(Int n) n]
  1155. [(Prim 'read '())
  1156. (define r (read))
  1157. (cond [(fixnum? r) r]
  1158. [else (error 'interp_exp "read expected an integer" r)])]
  1159. [(Prim '- (list e))
  1160. (define v (interp_exp e))
  1161. (fx- 0 v)]
  1162. [(Prim '+ (list e1 e2))
  1163. (define v1 (interp_exp e1))
  1164. (define v2 (interp_exp e2))
  1165. (fx+ v1 v2)]))
  1166. (define (interp_Lint p)
  1167. (match p
  1168. [(Program '() e) (interp_exp e)]))
  1169. \end{lstlisting}
  1170. \fi}
  1171. {\if\edition\pythonEd
  1172. \begin{lstlisting}
  1173. def interp_exp(e):
  1174. match e:
  1175. case BinOp(left, Add(), right):
  1176. l = interp_exp(left); r = interp_exp(right)
  1177. return l + r
  1178. case BinOp(left, Sub(), right):
  1179. l = interp_exp(left); r = interp_exp(right)
  1180. return l - r
  1181. case UnaryOp(USub(), v):
  1182. return - interp_exp(v)
  1183. case Constant(value):
  1184. return value
  1185. case Call(Name('input_int'), []):
  1186. return int(input())
  1187. def interp_stmt(s):
  1188. match s:
  1189. case Expr(Call(Name('print'), [arg])):
  1190. print(interp_exp(arg))
  1191. case Expr(value):
  1192. interp_exp(value)
  1193. def interp_Lint(p):
  1194. match p:
  1195. case Module(body):
  1196. for s in body:
  1197. interp_stmt(s)
  1198. \end{lstlisting}
  1199. \fi}
  1200. \caption{Interpreter for the \LangInt{} language.}
  1201. \label{fig:interp_Lint}
  1202. \end{figure}
  1203. Let us consider the result of interpreting a few \LangInt{} programs. The
  1204. following program adds two integers.
  1205. {\if\edition\racketEd
  1206. \begin{lstlisting}
  1207. (+ 10 32)
  1208. \end{lstlisting}
  1209. \fi}
  1210. {\if\edition\pythonEd
  1211. \begin{lstlisting}
  1212. print(10 + 32)
  1213. \end{lstlisting}
  1214. \fi}
  1215. The result is \key{42}, the answer to life, the universe, and
  1216. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1217. Galaxy} by Douglas Adams.}.
  1218. %
  1219. We wrote the above program in concrete syntax whereas the parsed
  1220. abstract syntax is:
  1221. {\if\edition\racketEd
  1222. \begin{lstlisting}
  1223. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1224. \end{lstlisting}
  1225. \fi}
  1226. {\if\edition\pythonEd
  1227. \begin{lstlisting}
  1228. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1229. \end{lstlisting}
  1230. \fi}
  1231. The next example demonstrates that expressions may be nested within
  1232. each other, in this case nesting several additions and negations.
  1233. {\if\edition\racketEd
  1234. \begin{lstlisting}
  1235. (+ 10 (- (+ 12 20)))
  1236. \end{lstlisting}
  1237. \fi}
  1238. {\if\edition\pythonEd
  1239. \begin{lstlisting}
  1240. print(10 + -(12 + 20))
  1241. \end{lstlisting}
  1242. \fi}
  1243. %
  1244. \noindent What is the result of the above program?
  1245. {\if\edition\racketEd
  1246. As mentioned previously, the \LangInt{} language does not support
  1247. arbitrarily-large integers, but only $63$-bit integers, so we
  1248. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1249. in Racket.
  1250. Suppose
  1251. \[
  1252. n = 999999999999999999
  1253. \]
  1254. which indeed fits in $63$-bits. What happens when we run the
  1255. following program in our interpreter?
  1256. \begin{lstlisting}
  1257. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1258. \end{lstlisting}
  1259. It produces an error:
  1260. \begin{lstlisting}
  1261. fx+: result is not a fixnum
  1262. \end{lstlisting}
  1263. We establish the convention that if running the definitional
  1264. interpreter on a program produces an error then the meaning of that
  1265. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1266. error is a \code{trapped-error}. A compiler for the language is under
  1267. no obligations regarding programs with unspecified behavior; it does
  1268. not have to produce an executable, and if it does, that executable can
  1269. do anything. On the other hand, if the error is a
  1270. \code{trapped-error}, then the compiler must produce an executable and
  1271. it is required to report that an error occurred. To signal an error,
  1272. exit with a return code of \code{255}. The interpreters in chapters
  1273. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1274. \code{trapped-error}.
  1275. \fi}
  1276. % TODO: how to deal with too-large integers in the Python interpreter?
  1277. %% This convention applies to the languages defined in this
  1278. %% book, as a way to simplify the student's task of implementing them,
  1279. %% but this convention is not applicable to all programming languages.
  1280. %%
  1281. Moving on to the last feature of the \LangInt{} language, the
  1282. \READOP{} operation prompts the user of the program for an integer.
  1283. Recall that program \eqref{eq:arith-prog} requests an integer input
  1284. and then subtracts \code{8}. So if we run
  1285. {\if\edition\racketEd
  1286. \begin{lstlisting}
  1287. (interp_Lint (Program '() ast1_1))
  1288. \end{lstlisting}
  1289. \fi}
  1290. {\if\edition\pythonEd
  1291. \begin{lstlisting}
  1292. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1293. \end{lstlisting}
  1294. \fi}
  1295. \noindent and if the input is \code{50}, the result is \code{42}.
  1296. We include the \READOP{} operation in \LangInt{} so a clever student
  1297. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1298. during compilation to obtain the output and then generates the trivial
  1299. code to produce the output.\footnote{Yes, a clever student did this in the
  1300. first instance of this course!}
  1301. The job of a compiler is to translate a program in one language into a
  1302. program in another language so that the output program behaves the
  1303. same way as the input program. This idea is depicted in the
  1304. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1305. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1306. Given a compiler that translates from language $\mathcal{L}_1$ to
  1307. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1308. compiler must translate it into some program $P_2$ such that
  1309. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1310. same input $i$ yields the same output $o$.
  1311. \begin{equation} \label{eq:compile-correct}
  1312. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1313. \node (p1) at (0, 0) {$P_1$};
  1314. \node (p2) at (3, 0) {$P_2$};
  1315. \node (o) at (3, -2.5) {$o$};
  1316. \path[->] (p1) edge [above] node {compile} (p2);
  1317. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1318. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1319. \end{tikzpicture}
  1320. \end{equation}
  1321. In the next section we see our first example of a compiler.
  1322. \section{Example Compiler: a Partial Evaluator}
  1323. \label{sec:partial-evaluation}
  1324. In this section we consider a compiler that translates \LangInt{}
  1325. programs into \LangInt{} programs that may be more efficient. The
  1326. compiler eagerly computes the parts of the program that do not depend
  1327. on any inputs, a process known as \emph{partial
  1328. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1329. For example, given the following program
  1330. {\if\edition\racketEd
  1331. \begin{lstlisting}
  1332. (+ (read) (- (+ 5 3)))
  1333. \end{lstlisting}
  1334. \fi}
  1335. {\if\edition\pythonEd
  1336. \begin{lstlisting}
  1337. print(input_int() + -(5 + 3) )
  1338. \end{lstlisting}
  1339. \fi}
  1340. \noindent our compiler translates it into the program
  1341. {\if\edition\racketEd
  1342. \begin{lstlisting}
  1343. (+ (read) -8)
  1344. \end{lstlisting}
  1345. \fi}
  1346. {\if\edition\pythonEd
  1347. \begin{lstlisting}
  1348. print(input_int() + -8)
  1349. \end{lstlisting}
  1350. \fi}
  1351. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1352. evaluator for the \LangInt{} language. The output of the partial evaluator
  1353. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1354. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1355. whereas the code for partially evaluating the negation and addition
  1356. operations is factored into two auxiliary functions:
  1357. \code{pe\_neg} and \code{pe\_add}. The input to these
  1358. functions is the output of partially evaluating the children.
  1359. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1360. arguments are integers and if they are, perform the appropriate
  1361. arithmetic. Otherwise, they create an AST node for the arithmetic
  1362. operation.
  1363. \begin{figure}[tp]
  1364. {\if\edition\racketEd
  1365. \begin{lstlisting}
  1366. (define (pe_neg r)
  1367. (match r
  1368. [(Int n) (Int (fx- 0 n))]
  1369. [else (Prim '- (list r))]))
  1370. (define (pe_add r1 r2)
  1371. (match* (r1 r2)
  1372. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1373. [(_ _) (Prim '+ (list r1 r2))]))
  1374. (define (pe_exp e)
  1375. (match e
  1376. [(Int n) (Int n)]
  1377. [(Prim 'read '()) (Prim 'read '())]
  1378. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1379. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1380. (define (pe_Lint p)
  1381. (match p
  1382. [(Program '() e) (Program '() (pe_exp e))]))
  1383. \end{lstlisting}
  1384. \fi}
  1385. {\if\edition\pythonEd
  1386. \begin{lstlisting}
  1387. def pe_neg(r):
  1388. match r:
  1389. case Constant(n):
  1390. return Constant(-n)
  1391. case _:
  1392. return UnaryOp(USub(), r)
  1393. def pe_add(r1, r2):
  1394. match (r1, r2):
  1395. case (Constant(n1), Constant(n2)):
  1396. return Constant(n1 + n2)
  1397. case _:
  1398. return BinOp(r1, Add(), r2)
  1399. def pe_sub(r1, r2):
  1400. match (r1, r2):
  1401. case (Constant(n1), Constant(n2)):
  1402. return Constant(n1 - n2)
  1403. case _:
  1404. return BinOp(r1, Sub(), r2)
  1405. def pe_exp(e):
  1406. match e:
  1407. case BinOp(left, Add(), right):
  1408. return pe_add(pe_exp(left), pe_exp(right))
  1409. case BinOp(left, Sub(), right):
  1410. return pe_sub(pe_exp(left), pe_exp(right))
  1411. case UnaryOp(USub(), v):
  1412. return pe_neg(pe_exp(v))
  1413. case Constant(value):
  1414. return e
  1415. case Call(Name('input_int'), []):
  1416. return e
  1417. def pe_stmt(s):
  1418. match s:
  1419. case Expr(Call(Name('print'), [arg])):
  1420. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1421. case Expr(value):
  1422. return Expr(pe_exp(value))
  1423. def pe_P_int(p):
  1424. match p:
  1425. case Module(body):
  1426. new_body = [pe_stmt(s) for s in body]
  1427. return Module(new_body)
  1428. \end{lstlisting}
  1429. \fi}
  1430. \caption{A partial evaluator for \LangInt{}.}
  1431. \label{fig:pe-arith}
  1432. \end{figure}
  1433. To gain some confidence that the partial evaluator is correct, we can
  1434. test whether it produces programs that get the same result as the
  1435. input programs. That is, we can test whether it satisfies Diagram
  1436. \ref{eq:compile-correct}.
  1437. %
  1438. {\if\edition\racketEd
  1439. The following code runs the partial evaluator on several examples and
  1440. tests the output program. The \texttt{parse-program} and
  1441. \texttt{assert} functions are defined in
  1442. Appendix~\ref{appendix:utilities}.\\
  1443. \begin{minipage}{1.0\textwidth}
  1444. \begin{lstlisting}
  1445. (define (test_pe p)
  1446. (assert "testing pe_Lint"
  1447. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1448. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1449. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1450. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1451. \end{lstlisting}
  1452. \end{minipage}
  1453. \fi}
  1454. % TODO: python version of testing the PE
  1455. \begin{exercise}\normalfont
  1456. Create three programs in the \LangInt{} language and test whether
  1457. partially evaluating them with \code{pe\_Lint} and then
  1458. interpreting them with \code{interp\_Lint} gives the same result
  1459. as directly interpreting them with \code{interp\_Lint}.
  1460. \end{exercise}
  1461. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1462. \chapter{Integers and Variables}
  1463. \label{ch:Lvar}
  1464. This chapter is about compiling a subset of
  1465. \racket{Racket}\python{Python} to x86-64 assembly
  1466. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1467. integer arithmetic and local variables. We often refer to x86-64
  1468. simply as x86. The chapter begins with a description of the
  1469. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1470. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1471. large so we discuss only the instructions needed for compiling
  1472. \LangVar{}. We introduce more x86 instructions in later chapters.
  1473. After introducing \LangVar{} and x86, we reflect on their differences
  1474. and come up with a plan to break down the translation from \LangVar{}
  1475. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1476. rest of the sections in this chapter give detailed hints regarding
  1477. each step. We hope to give enough hints that the well-prepared
  1478. reader, together with a few friends, can implement a compiler from
  1479. \LangVar{} to x86 in a couple weeks. To give the reader a feeling for
  1480. the scale of this first compiler, the instructor solution for the
  1481. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1482. code.
  1483. \section{The \LangVar{} Language}
  1484. \label{sec:s0}
  1485. \index{subject}{variable}
  1486. The \LangVar{} language extends the \LangInt{} language with
  1487. variables. The concrete syntax of the \LangVar{} language is defined
  1488. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1489. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1490. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1491. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1492. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1493. syntax of \LangVar{} includes the \racket{\key{Program}
  1494. struct}\python{\key{Module} instance} to mark the top of the
  1495. program.
  1496. %% The $\itm{info}$
  1497. %% field of the \key{Program} structure contains an \emph{association
  1498. %% list} (a list of key-value pairs) that is used to communicate
  1499. %% auxiliary data from one compiler pass the next.
  1500. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1501. exhibit several compilation techniques.
  1502. \newcommand{\LvarGrammarRacket}{
  1503. \begin{array}{rcl}
  1504. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1505. \end{array}
  1506. }
  1507. \newcommand{\LvarAST}{
  1508. \begin{array}{rcl}
  1509. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1510. \end{array}
  1511. }
  1512. \newcommand{\LvarGrammarPython}{
  1513. \begin{array}{rcl}
  1514. \Exp &::=& \Var{} \\
  1515. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1516. \end{array}
  1517. }
  1518. \newcommand{\LvarASTPython}{
  1519. \begin{array}{rcl}
  1520. \Exp{} &::=& \VAR{\Var{}} \\
  1521. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1522. \end{array}
  1523. }
  1524. \begin{figure}[tp]
  1525. \centering
  1526. \fbox{
  1527. \begin{minipage}{0.96\textwidth}
  1528. {\if\edition\racketEd
  1529. \[
  1530. \begin{array}{l}
  1531. \gray{\LintGrammarRacket{}} \\ \hline
  1532. \LvarGrammarRacket{} \\
  1533. \begin{array}{rcl}
  1534. \LangVarM{} &::=& \Exp
  1535. \end{array}
  1536. \end{array}
  1537. \]
  1538. \fi}
  1539. {\if\edition\pythonEd
  1540. \[
  1541. \begin{array}{l}
  1542. \gray{\LintGrammarPython} \\ \hline
  1543. \LvarGrammarPython \\
  1544. \begin{array}{rcl}
  1545. \LangVarM{} &::=& \Stmt^{*}
  1546. \end{array}
  1547. \end{array}
  1548. \]
  1549. \fi}
  1550. \end{minipage}
  1551. }
  1552. \caption{The concrete syntax of \LangVar{}.}
  1553. \label{fig:Lvar-concrete-syntax}
  1554. \end{figure}
  1555. \begin{figure}[tp]
  1556. \centering
  1557. \fbox{
  1558. \begin{minipage}{0.96\textwidth}
  1559. {\if\edition\racketEd
  1560. \[
  1561. \begin{array}{l}
  1562. \gray{\LintASTRacket{}} \\ \hline
  1563. \LvarAST \\
  1564. \begin{array}{rcl}
  1565. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1566. \end{array}
  1567. \end{array}
  1568. \]
  1569. \fi}
  1570. {\if\edition\pythonEd
  1571. \[
  1572. \begin{array}{l}
  1573. \gray{\LintASTPython}\\ \hline
  1574. \LvarASTPython \\
  1575. \begin{array}{rcl}
  1576. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1577. \end{array}
  1578. \end{array}
  1579. \]
  1580. \fi}
  1581. \end{minipage}
  1582. }
  1583. \caption{The abstract syntax of \LangVar{}.}
  1584. \label{fig:Lvar-syntax}
  1585. \end{figure}
  1586. {\if\edition\racketEd
  1587. Let us dive further into the syntax and semantics of the \LangVar{}
  1588. language. The \key{let} feature defines a variable for use within its
  1589. body and initializes the variable with the value of an expression.
  1590. The abstract syntax for \key{let} is defined in
  1591. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1592. \begin{lstlisting}
  1593. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1594. \end{lstlisting}
  1595. For example, the following program initializes \code{x} to $32$ and then
  1596. evaluates the body \code{(+ 10 x)}, producing $42$.
  1597. \begin{lstlisting}
  1598. (let ([x (+ 12 20)]) (+ 10 x))
  1599. \end{lstlisting}
  1600. \fi}
  1601. %
  1602. {\if\edition\pythonEd
  1603. %
  1604. The \LangVar{} language includes assignment statements, which define a
  1605. variable for use in later statements and initializes the variable with
  1606. the value of an expression. The abstract syntax for assignment is
  1607. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1608. assignment is
  1609. \begin{lstlisting}
  1610. |$\itm{var}$| = |$\itm{exp}$|
  1611. \end{lstlisting}
  1612. For example, the following program initializes the variable \code{x}
  1613. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1614. \begin{lstlisting}
  1615. x = 12 + 20
  1616. print(10 + x)
  1617. \end{lstlisting}
  1618. \fi}
  1619. {\if\edition\racketEd
  1620. %
  1621. When there are multiple \key{let}'s for the same variable, the closest
  1622. enclosing \key{let} is used. That is, variable definitions overshadow
  1623. prior definitions. Consider the following program with two \key{let}'s
  1624. that define variables named \code{x}. Can you figure out the result?
  1625. \begin{lstlisting}
  1626. (let ([x 32]) (+ (let ([x 10]) x) x))
  1627. \end{lstlisting}
  1628. For the purposes of depicting which variable uses correspond to which
  1629. definitions, the following shows the \code{x}'s annotated with
  1630. subscripts to distinguish them. Double check that your answer for the
  1631. above is the same as your answer for this annotated version of the
  1632. program.
  1633. \begin{lstlisting}
  1634. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1635. \end{lstlisting}
  1636. The initializing expression is always evaluated before the body of the
  1637. \key{let}, so in the following, the \key{read} for \code{x} is
  1638. performed before the \key{read} for \code{y}. Given the input
  1639. $52$ then $10$, the following produces $42$ (not $-42$).
  1640. \begin{lstlisting}
  1641. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1642. \end{lstlisting}
  1643. \fi}
  1644. \subsection{Extensible Interpreters via Method Overriding}
  1645. \label{sec:extensible-interp}
  1646. To prepare for discussing the interpreter of \LangVar{}, we explain
  1647. why we implement it in an object-oriented style. Throughout this book
  1648. we define many interpreters, one for each of language that we
  1649. study. Because each language builds on the prior one, there is a lot
  1650. of commonality between these interpreters. We want to write down the
  1651. common parts just once instead of many times. A naive approach would
  1652. be for the interpreter of \LangVar{} to handle the
  1653. \racket{cases for variables and \code{let}}
  1654. \python{case for variables}
  1655. but dispatch to \LangInt{}
  1656. for the rest of the cases. The following code sketches this idea. (We
  1657. explain the \code{env} parameter soon, in
  1658. Section~\ref{sec:interp-Lvar}.)
  1659. \begin{center}
  1660. {\if\edition\racketEd
  1661. \begin{minipage}{0.45\textwidth}
  1662. \begin{lstlisting}
  1663. (define ((interp_Lint env) e)
  1664. (match e
  1665. [(Prim '- (list e1))
  1666. (fx- 0 ((interp_Lint env) e1))]
  1667. ...))
  1668. \end{lstlisting}
  1669. \end{minipage}
  1670. \begin{minipage}{0.45\textwidth}
  1671. \begin{lstlisting}
  1672. (define ((interp_Lvar env) e)
  1673. (match e
  1674. [(Var x)
  1675. (dict-ref env x)]
  1676. [(Let x e body)
  1677. (define v ((interp_exp env) e))
  1678. (define env^ (dict-set env x v))
  1679. ((interp_exp env^) body)]
  1680. [else ((interp_Lint env) e)]))
  1681. \end{lstlisting}
  1682. \end{minipage}
  1683. \fi}
  1684. {\if\edition\pythonEd
  1685. \begin{minipage}{0.45\textwidth}
  1686. \begin{lstlisting}
  1687. def interp_Lint(e, env):
  1688. match e:
  1689. case UnaryOp(USub(), e1):
  1690. return - interp_Lint(e1, env)
  1691. ...
  1692. \end{lstlisting}
  1693. \end{minipage}
  1694. \begin{minipage}{0.45\textwidth}
  1695. \begin{lstlisting}
  1696. def interp_Lvar(e, env):
  1697. match e:
  1698. case Name(id):
  1699. return env[id]
  1700. case _:
  1701. return interp_Lint(e, env)
  1702. \end{lstlisting}
  1703. \end{minipage}
  1704. \fi}
  1705. \end{center}
  1706. The problem with this approach is that it does not handle situations
  1707. in which an \LangVar{} feature, such as a variable, is nested inside
  1708. an \LangInt{} feature, like the \code{-} operator, as in the following
  1709. program.
  1710. %
  1711. {\if\edition\racketEd
  1712. \begin{lstlisting}
  1713. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1714. \end{lstlisting}
  1715. \fi}
  1716. {\if\edition\pythonEd
  1717. \begin{lstlisting}
  1718. y = 10
  1719. print(-y)
  1720. \end{lstlisting}
  1721. \fi}
  1722. %
  1723. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1724. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1725. then it recursively calls \code{interp\_Lint} again on its argument.
  1726. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1727. an error!
  1728. To make our interpreters extensible we need something called
  1729. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1730. recursive knot is delayed to when the functions are
  1731. composed. Object-oriented languages provide open recursion via
  1732. method overriding\index{subject}{method overriding}. The
  1733. following code uses method overriding to interpret \LangInt{} and
  1734. \LangVar{} using
  1735. %
  1736. \racket{the
  1737. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1738. \index{subject}{class} feature of Racket}
  1739. %
  1740. \python{a Python \code{class} definition}.
  1741. %
  1742. We define one class for each language and define a method for
  1743. interpreting expressions inside each class. The class for \LangVar{}
  1744. inherits from the class for \LangInt{} and the method
  1745. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1746. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1747. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1748. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1749. \code{interp\_exp} in \LangInt{}.
  1750. \begin{center}
  1751. \hspace{-20pt}
  1752. {\if\edition\racketEd
  1753. \begin{minipage}{0.45\textwidth}
  1754. \begin{lstlisting}
  1755. (define interp_Lint_class
  1756. (class object%
  1757. (define/public ((interp_exp env) e)
  1758. (match e
  1759. [(Prim '- (list e))
  1760. (fx- 0 ((interp_exp env) e))]
  1761. ...))
  1762. ...))
  1763. \end{lstlisting}
  1764. \end{minipage}
  1765. \begin{minipage}{0.45\textwidth}
  1766. \begin{lstlisting}
  1767. (define interp_Lvar_class
  1768. (class interp_Lint_class
  1769. (define/override ((interp_exp env) e)
  1770. (match e
  1771. [(Var x)
  1772. (dict-ref env x)]
  1773. [(Let x e body)
  1774. (define v ((interp_exp env) e))
  1775. (define env^ (dict-set env x v))
  1776. ((interp_exp env^) body)]
  1777. [else
  1778. (super (interp_exp env) e)]))
  1779. ...
  1780. ))
  1781. \end{lstlisting}
  1782. \end{minipage}
  1783. \fi}
  1784. {\if\edition\pythonEd
  1785. \begin{minipage}{0.45\textwidth}
  1786. \begin{lstlisting}
  1787. class InterpLint:
  1788. def interp_exp(e):
  1789. match e:
  1790. case UnaryOp(USub(), e1):
  1791. return -self.interp_exp(e1)
  1792. ...
  1793. ...
  1794. \end{lstlisting}
  1795. \end{minipage}
  1796. \begin{minipage}{0.45\textwidth}
  1797. \begin{lstlisting}
  1798. def InterpLvar(InterpLint):
  1799. def interp_exp(e):
  1800. match e:
  1801. case Name(id):
  1802. return env[id]
  1803. case _:
  1804. return super().interp_exp(e)
  1805. ...
  1806. \end{lstlisting}
  1807. \end{minipage}
  1808. \fi}
  1809. \end{center}
  1810. Getting back to the troublesome example, repeated here:
  1811. {\if\edition\racketEd
  1812. \begin{lstlisting}
  1813. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1814. \end{lstlisting}
  1815. \fi}
  1816. {\if\edition\pythonEd
  1817. \begin{lstlisting}
  1818. y = 10
  1819. print(-y)
  1820. \end{lstlisting}
  1821. \fi}
  1822. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1823. \racket{on this expression,}
  1824. \python{on the \code{-y} expression,}
  1825. %
  1826. call it \code{e0}, by creating an object of the \LangVar{} class
  1827. and calling the \code{interp\_exp} method.
  1828. {\if\edition\racketEd
  1829. \begin{lstlisting}
  1830. (send (new interp_Lvar_class) interp_exp e0)
  1831. \end{lstlisting}
  1832. \fi}
  1833. {\if\edition\pythonEd
  1834. \begin{lstlisting}
  1835. InterpLvar().interp_exp(e0)
  1836. \end{lstlisting}
  1837. \fi}
  1838. \noindent To process the \code{-} operator, the default case of
  1839. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1840. method in \LangInt{}. But then for the recursive method call, it
  1841. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1842. \code{Var} node is handled correctly. Thus, method overriding gives us
  1843. the open recursion that we need to implement our interpreters in an
  1844. extensible way.
  1845. \subsection{Definitional Interpreter for \LangVar{}}
  1846. \label{sec:interp-Lvar}
  1847. {\if\edition\racketEd
  1848. \begin{figure}[tp]
  1849. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1850. \small
  1851. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1852. An \emph{association list} (alist) is a list of key-value pairs.
  1853. For example, we can map people to their ages with an alist.
  1854. \index{subject}{alist}\index{subject}{association list}
  1855. \begin{lstlisting}[basicstyle=\ttfamily]
  1856. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1857. \end{lstlisting}
  1858. The \emph{dictionary} interface is for mapping keys to values.
  1859. Every alist implements this interface. \index{subject}{dictionary} The package
  1860. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1861. provides many functions for working with dictionaries. Here
  1862. are a few of them:
  1863. \begin{description}
  1864. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1865. returns the value associated with the given $\itm{key}$.
  1866. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1867. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1868. but otherwise is the same as $\itm{dict}$.
  1869. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1870. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1871. of keys and values in $\itm{dict}$. For example, the following
  1872. creates a new alist in which the ages are incremented.
  1873. \end{description}
  1874. \vspace{-10pt}
  1875. \begin{lstlisting}[basicstyle=\ttfamily]
  1876. (for/list ([(k v) (in-dict ages)])
  1877. (cons k (add1 v)))
  1878. \end{lstlisting}
  1879. \end{tcolorbox}
  1880. %\end{wrapfigure}
  1881. \caption{Association lists implement the dictionary interface.}
  1882. \label{fig:alist}
  1883. \end{figure}
  1884. \fi}
  1885. Having justified the use of classes and methods to implement
  1886. interpreters, we revisit the definitional interpreter for \LangInt{}
  1887. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1888. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1889. interpreter for \LangVar{} adds two new \key{match} cases for
  1890. variables and \racket{\key{let}}\python{assignment}. For
  1891. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1892. value bound to a variable to all the uses of the variable. To
  1893. accomplish this, we maintain a mapping from variables to values
  1894. called an \emph{environment}\index{subject}{environment}.
  1895. %
  1896. We use%
  1897. %
  1898. \racket{an association list (alist)}
  1899. %
  1900. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1901. %
  1902. to represent the environment.
  1903. %
  1904. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1905. and the \code{racket/dict} package.}
  1906. %
  1907. The \code{interp\_exp} function takes the current environment,
  1908. \code{env}, as an extra parameter. When the interpreter encounters a
  1909. variable, it looks up the corresponding value in the dictionary.
  1910. %
  1911. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1912. initializing expression, extends the environment with the result
  1913. value bound to the variable, using \code{dict-set}, then evaluates
  1914. the body of the \key{Let}.}
  1915. %
  1916. \python{When the interpreter encounters an assignment, it evaluates
  1917. the initializing expression and then associates the resulting value
  1918. with the variable in the environment.}
  1919. \begin{figure}[tp]
  1920. {\if\edition\racketEd
  1921. \begin{lstlisting}
  1922. (define interp_Lint_class
  1923. (class object%
  1924. (super-new)
  1925. (define/public ((interp_exp env) e)
  1926. (match e
  1927. [(Int n) n]
  1928. [(Prim 'read '())
  1929. (define r (read))
  1930. (cond [(fixnum? r) r]
  1931. [else (error 'interp_exp "expected an integer" r)])]
  1932. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1933. [(Prim '+ (list e1 e2))
  1934. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]))
  1935. (define/public (interp_program p)
  1936. (match p
  1937. [(Program '() e) ((interp_exp '()) e)]))
  1938. ))
  1939. \end{lstlisting}
  1940. \fi}
  1941. {\if\edition\pythonEd
  1942. \begin{lstlisting}
  1943. class InterpLint:
  1944. def interp_exp(self, e, env):
  1945. match e:
  1946. case BinOp(left, Add(), right):
  1947. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1948. case UnaryOp(USub(), v):
  1949. return - self.interp_exp(v, env)
  1950. case Constant(value):
  1951. return value
  1952. case Call(Name('input_int'), []):
  1953. return int(input())
  1954. def interp_stmts(self, ss, env):
  1955. if len(ss) == 0:
  1956. return
  1957. match ss[0]:
  1958. case Expr(Call(Name('print'), [arg])):
  1959. print(self.interp_exp(arg, env), end='')
  1960. return self.interp_stmts(ss[1:], env)
  1961. case Expr(value):
  1962. self.interp_exp(value, env)
  1963. return self.interp_stmts(ss[1:], env)
  1964. def interp(self, p):
  1965. match p:
  1966. case Module(body):
  1967. self.interp_stmts(body, {})
  1968. def interp_Lint(p):
  1969. return InterpLint().interp(p)
  1970. \end{lstlisting}
  1971. \fi}
  1972. \caption{Interpreter for \LangInt{} as a class.}
  1973. \label{fig:interp-Lint-class}
  1974. \end{figure}
  1975. \begin{figure}[tp]
  1976. {\if\edition\racketEd
  1977. \begin{lstlisting}
  1978. (define interp_Lvar_class
  1979. (class interp_Lint_class
  1980. (super-new)
  1981. (define/override ((interp_exp env) e)
  1982. (match e
  1983. [(Var x) (dict-ref env x)]
  1984. [(Let x e body)
  1985. (define new-env (dict-set env x ((interp_exp env) e)))
  1986. ((interp_exp new-env) body)]
  1987. [else ((super interp-exp env) e)]))
  1988. ))
  1989. (define (interp_Lvar p)
  1990. (send (new interp_Lvar_class) interp_program p))
  1991. \end{lstlisting}
  1992. \fi}
  1993. {\if\edition\pythonEd
  1994. \begin{lstlisting}
  1995. class InterpLvar(InterpLint):
  1996. def interp_exp(self, e, env):
  1997. match e:
  1998. case Name(id):
  1999. return env[id]
  2000. case _:
  2001. return super().interp_exp(e, env)
  2002. def interp_stmts(self, ss, env):
  2003. if len(ss) == 0:
  2004. return
  2005. match ss[0]:
  2006. case Assign([lhs], value):
  2007. env[lhs.id] = self.interp_exp(value, env)
  2008. return self.interp_stmts(ss[1:], env)
  2009. case _:
  2010. return super().interp_stmts(ss, env)
  2011. def interp_Lvar(p):
  2012. return InterpLvar().interp(p)
  2013. \end{lstlisting}
  2014. \fi}
  2015. \caption{Interpreter for the \LangVar{} language.}
  2016. \label{fig:interp-Lvar}
  2017. \end{figure}
  2018. The goal for this chapter is to implement a compiler that translates
  2019. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2020. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2021. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2022. That is, they output the same integer $n$. We depict this correctness
  2023. criteria in the following diagram.
  2024. \[
  2025. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2026. \node (p1) at (0, 0) {$P_1$};
  2027. \node (p2) at (4, 0) {$P_2$};
  2028. \node (o) at (4, -2) {$n$};
  2029. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2030. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2031. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2032. \end{tikzpicture}
  2033. \]
  2034. In the next section we introduce the \LangXInt{} subset of x86 that
  2035. suffices for compiling \LangVar{}.
  2036. \section{The \LangXInt{} Assembly Language}
  2037. \label{sec:x86}
  2038. \index{subject}{x86}
  2039. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2040. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2041. assembler.
  2042. %
  2043. A program begins with a \code{main} label followed by a sequence of
  2044. instructions. The \key{globl} directive says that the \key{main}
  2045. procedure is externally visible, which is necessary so that the
  2046. operating system can call it.
  2047. %
  2048. An x86 program is stored in the computer's memory. For our purposes,
  2049. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2050. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2051. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2052. the address of the next instruction to be executed. For most
  2053. instructions, the program counter is incremented after the instruction
  2054. is executed, so it points to the next instruction in memory. Most x86
  2055. instructions take two operands, where each operand is either an
  2056. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2057. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2058. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2059. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2060. && \key{r8} \MID \key{r9} \MID \key{r10}
  2061. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2062. \MID \key{r14} \MID \key{r15}}
  2063. \begin{figure}[tp]
  2064. \fbox{
  2065. \begin{minipage}{0.96\textwidth}
  2066. {\if\edition\racketEd
  2067. \[
  2068. \begin{array}{lcl}
  2069. \Reg &::=& \allregisters{} \\
  2070. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2071. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2072. \key{subq} \; \Arg\key{,} \Arg \MID
  2073. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2074. && \key{callq} \; \mathit{label} \MID
  2075. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  2076. && \itm{label}\key{:}\; \Instr \\
  2077. \LangXIntM{} &::= & \key{.globl main}\\
  2078. & & \key{main:} \; \Instr\ldots
  2079. \end{array}
  2080. \]
  2081. \fi}
  2082. {\if\edition\pythonEd
  2083. \[
  2084. \begin{array}{lcl}
  2085. \Reg &::=& \allregisters{} \\
  2086. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2087. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2088. \key{subq} \; \Arg\key{,} \Arg \MID
  2089. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2090. && \key{callq} \; \mathit{label} \MID
  2091. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2092. \LangXIntM{} &::= & \key{.globl main}\\
  2093. & & \key{main:} \; \Instr^{*}
  2094. \end{array}
  2095. \]
  2096. \fi}
  2097. \end{minipage}
  2098. }
  2099. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2100. \label{fig:x86-int-concrete}
  2101. \end{figure}
  2102. A register is a special kind of variable that holds a 64-bit
  2103. value. There are 16 general-purpose registers in the computer and
  2104. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2105. is written with a \key{\%} followed by the register name, such as
  2106. \key{\%rax}.
  2107. An immediate value is written using the notation \key{\$}$n$ where $n$
  2108. is an integer.
  2109. %
  2110. %
  2111. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2112. which obtains the address stored in register $r$ and then adds $n$
  2113. bytes to the address. The resulting address is used to load or store
  2114. to memory depending on whether it occurs as a source or destination
  2115. argument of an instruction.
  2116. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2117. source $s$ and destination $d$, applies the arithmetic operation, then
  2118. writes the result back to the destination $d$. \index{subject}{instruction}
  2119. %
  2120. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2121. stores the result in $d$.
  2122. %
  2123. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2124. specified by the label and $\key{retq}$ returns from a procedure to
  2125. its caller.
  2126. %
  2127. We discuss procedure calls in more detail later in this chapter and in
  2128. Chapter~\ref{ch:Rfun}.
  2129. %
  2130. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2131. counter to the address of the instruction after the specified
  2132. label.}
  2133. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2134. all of the x86 instructions used in this book.
  2135. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2136. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2137. \lstinline{movq $10, %rax}
  2138. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2139. adds $32$ to the $10$ in \key{rax} and
  2140. puts the result, $42$, back into \key{rax}.
  2141. %
  2142. The last instruction, \key{retq}, finishes the \key{main} function by
  2143. returning the integer in \key{rax} to the operating system. The
  2144. operating system interprets this integer as the program's exit
  2145. code. By convention, an exit code of 0 indicates that a program
  2146. completed successfully, and all other exit codes indicate various
  2147. errors.
  2148. %
  2149. \racket{Nevertheless, in this book we return the result of the program
  2150. as the exit code.}
  2151. \begin{figure}[tbp]
  2152. \begin{lstlisting}
  2153. .globl main
  2154. main:
  2155. movq $10, %rax
  2156. addq $32, %rax
  2157. retq
  2158. \end{lstlisting}
  2159. \caption{An x86 program that computes
  2160. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2161. \label{fig:p0-x86}
  2162. \end{figure}
  2163. We exhibit the use of memory for storing intermediate results in the
  2164. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2165. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2166. uses a region of memory called the \emph{procedure call stack} (or
  2167. \emph{stack} for
  2168. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2169. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2170. for each procedure call. The memory layout for an individual frame is
  2171. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2172. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  2173. item at the top of the stack. The stack grows downward in memory, so
  2174. we increase the size of the stack by subtracting from the stack
  2175. pointer. In the context of a procedure call, the \emph{return
  2176. address}\index{subject}{return address} is the instruction after the
  2177. call instruction on the caller side. The function call instruction,
  2178. \code{callq}, pushes the return address onto the stack prior to
  2179. jumping to the procedure. The register \key{rbp} is the \emph{base
  2180. pointer}\index{subject}{base pointer} and is used to access variables
  2181. that are stored in the frame of the current procedure call. The base
  2182. pointer of the caller is store after the return address. In
  2183. Figure~\ref{fig:frame} we number the variables from $1$ to
  2184. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2185. at $-16\key{(\%rbp)}$, etc.
  2186. \begin{figure}[tbp]
  2187. {\if\edition\racketEd
  2188. \begin{lstlisting}
  2189. start:
  2190. movq $10, -8(%rbp)
  2191. negq -8(%rbp)
  2192. movq -8(%rbp), %rax
  2193. addq $52, %rax
  2194. jmp conclusion
  2195. .globl main
  2196. main:
  2197. pushq %rbp
  2198. movq %rsp, %rbp
  2199. subq $16, %rsp
  2200. jmp start
  2201. conclusion:
  2202. addq $16, %rsp
  2203. popq %rbp
  2204. retq
  2205. \end{lstlisting}
  2206. \fi}
  2207. {\if\edition\pythonEd
  2208. \begin{lstlisting}
  2209. .globl main
  2210. main:
  2211. pushq %rbp
  2212. movq %rsp, %rbp
  2213. subq $16, %rsp
  2214. movq $10, -8(%rbp)
  2215. negq -8(%rbp)
  2216. movq -8(%rbp), %rax
  2217. addq $52, %rax
  2218. addq $16, %rsp
  2219. popq %rbp
  2220. retq
  2221. \end{lstlisting}
  2222. \fi}
  2223. \caption{An x86 program that computes
  2224. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2225. \label{fig:p1-x86}
  2226. \end{figure}
  2227. \begin{figure}[tbp]
  2228. \centering
  2229. \begin{tabular}{|r|l|} \hline
  2230. Position & Contents \\ \hline
  2231. 8(\key{\%rbp}) & return address \\
  2232. 0(\key{\%rbp}) & old \key{rbp} \\
  2233. -8(\key{\%rbp}) & variable $1$ \\
  2234. -16(\key{\%rbp}) & variable $2$ \\
  2235. \ldots & \ldots \\
  2236. 0(\key{\%rsp}) & variable $n$\\ \hline
  2237. \end{tabular}
  2238. \caption{Memory layout of a frame.}
  2239. \label{fig:frame}
  2240. \end{figure}
  2241. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2242. control is transferred from the operating system to the \code{main}
  2243. function. The operating system issues a \code{callq main} instruction
  2244. which pushes its return address on the stack and then jumps to
  2245. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2246. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2247. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2248. alignment (because the \code{callq} pushed the return address). The
  2249. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2250. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2251. pointer for the caller onto the stack and subtracts $8$ from the stack
  2252. pointer. The next instruction \code{movq \%rsp, \%rbp} sets the
  2253. base pointer to the current stack pointer, which is pointing at the location
  2254. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2255. pointer down to make enough room for storing variables. This program
  2256. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2257. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2258. functions.
  2259. \racket{The last instruction of the prelude is \code{jmp start},
  2260. which transfers control to the instructions that were generated from
  2261. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2262. \racket{The first instruction under the \code{start} label is}
  2263. %
  2264. \python{The first instruction after the prelude is}
  2265. %
  2266. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2267. %
  2268. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2269. %
  2270. The next instruction moves the $-10$ from variable $1$ into the
  2271. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2272. the value in \code{rax}, updating its contents to $42$.
  2273. \racket{The three instructions under the label \code{conclusion} are the
  2274. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2275. %
  2276. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2277. \code{main} function consists of the last three instructions.}
  2278. %
  2279. The first two restore the \code{rsp} and \code{rbp} registers to the
  2280. state they were in at the beginning of the procedure. In particular,
  2281. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2282. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2283. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2284. \key{retq}, jumps back to the procedure that called this one and adds
  2285. $8$ to the stack pointer.
  2286. Our compiler needs a convenient representation for manipulating x86
  2287. programs, so we define an abstract syntax for x86 in
  2288. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2289. \LangXInt{}.
  2290. %
  2291. {\if\edition\racketEd
  2292. The main difference compared to the concrete syntax of \LangXInt{}
  2293. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2294. front of every instruction. Instead instructions are grouped into
  2295. \emph{blocks}\index{subject}{block} with a
  2296. label associated with every block, which is why the \key{X86Program}
  2297. struct includes an alist mapping labels to blocks. The reason for this
  2298. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2299. introduce conditional branching. The \code{Block} structure includes
  2300. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2301. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2302. $\itm{info}$ field should contain an empty list.
  2303. \fi}
  2304. %
  2305. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2306. node includes an integer for representing the arity of the function,
  2307. i.e., the number of arguments, which is helpful to know during
  2308. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2309. \begin{figure}[tp]
  2310. \fbox{
  2311. \begin{minipage}{0.98\textwidth}
  2312. \small
  2313. {\if\edition\racketEd
  2314. \[
  2315. \begin{array}{lcl}
  2316. \Reg &::=& \allregisters{} \\
  2317. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2318. \MID \DEREF{\Reg}{\Int} \\
  2319. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2320. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2321. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2322. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2323. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2324. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2325. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2326. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2327. \end{array}
  2328. \]
  2329. \fi}
  2330. {\if\edition\pythonEd
  2331. \[
  2332. \begin{array}{lcl}
  2333. \Reg &::=& \allregisters{} \\
  2334. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2335. \MID \DEREF{\Reg}{\Int} \\
  2336. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2337. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2338. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2339. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2340. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2341. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2342. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2343. \end{array}
  2344. \]
  2345. \fi}
  2346. \end{minipage}
  2347. }
  2348. \caption{The abstract syntax of \LangXInt{} assembly.}
  2349. \label{fig:x86-int-ast}
  2350. \end{figure}
  2351. \section{Planning the trip to x86}
  2352. \label{sec:plan-s0-x86}
  2353. To compile one language to another it helps to focus on the
  2354. differences between the two languages because the compiler will need
  2355. to bridge those differences. What are the differences between \LangVar{}
  2356. and x86 assembly? Here are some of the most important ones:
  2357. \begin{enumerate}
  2358. \item x86 arithmetic instructions typically have two arguments and
  2359. update the second argument in place. In contrast, \LangVar{}
  2360. arithmetic operations take two arguments and produce a new value.
  2361. An x86 instruction may have at most one memory-accessing argument.
  2362. Furthermore, some x86 instructions place special restrictions on
  2363. their arguments.
  2364. \item An argument of an \LangVar{} operator can be a deeply-nested
  2365. expression, whereas x86 instructions restrict their arguments to be
  2366. integer constants, registers, and memory locations.
  2367. {\if\edition\racketEd
  2368. \item The order of execution in x86 is explicit in the syntax: a
  2369. sequence of instructions and jumps to labeled positions, whereas in
  2370. \LangVar{} the order of evaluation is a left-to-right depth-first
  2371. traversal of the abstract syntax tree.
  2372. \fi}
  2373. \item A program in \LangVar{} can have any number of variables
  2374. whereas x86 has 16 registers and the procedure call stack.
  2375. {\if\edition\racketEd
  2376. \item Variables in \LangVar{} can shadow other variables with the
  2377. same name. In x86, registers have unique names and memory locations
  2378. have unique addresses.
  2379. \fi}
  2380. \end{enumerate}
  2381. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2382. down the problem into several steps, dealing with the above
  2383. differences one at a time. Each of these steps is called a \emph{pass}
  2384. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2385. %
  2386. This terminology comes from the way each step passes over, that is,
  2387. traverses the AST of the program.
  2388. %
  2389. Furthermore, we follow the nanopass approach, which means we strive
  2390. for each pass to accomplish one clear objective (not two or three at
  2391. the same time).
  2392. %
  2393. We begin by sketching how we might implement each pass, and give them
  2394. names. We then figure out an ordering of the passes and the
  2395. input/output language for each pass. The very first pass has
  2396. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2397. its output language. In between we can choose whichever language is
  2398. most convenient for expressing the output of each pass, whether that
  2399. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2400. our own design. Finally, to implement each pass we write one
  2401. recursive function per non-terminal in the grammar of the input
  2402. language of the pass. \index{subject}{intermediate language}
  2403. Our compiler for \LangVar{} consists of the following passes.
  2404. %
  2405. \begin{description}
  2406. {\if\edition\racketEd
  2407. \item[\key{uniquify}] deals with the shadowing of variables by
  2408. renaming every variable to a unique name.
  2409. \fi}
  2410. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2411. of a primitive operation or function call is a variable or integer,
  2412. that is, an \emph{atomic} expression. We refer to non-atomic
  2413. expressions as \emph{complex}. This pass introduces temporary
  2414. variables to hold the results of complex
  2415. subexpressions.\index{subject}{atomic
  2416. expression}\index{subject}{complex expression}%
  2417. {\if\edition\racketEd
  2418. \item[\key{explicate\_control}] makes the execution order of the
  2419. program explicit. It converts the abstract syntax tree representation
  2420. into a control-flow graph in which each node contains a sequence of
  2421. statements and the edges between nodes say which nodes contain jumps
  2422. to other nodes.
  2423. \fi}
  2424. \item[\key{select\_instructions}] handles the difference between
  2425. \LangVar{} operations and x86 instructions. This pass converts each
  2426. \LangVar{} operation to a short sequence of instructions that
  2427. accomplishes the same task.
  2428. \item[\key{assign\_homes}] replaces variables with registers or stack
  2429. locations.
  2430. \end{description}
  2431. %
  2432. {\if\edition\racketEd
  2433. %
  2434. Our treatment of \code{remove\_complex\_operands} and
  2435. \code{explicate\_control} as separate passes is an example of the
  2436. nanopass approach\footnote{For analogous decompositions of the
  2437. translation into continuation passing style, see the work of
  2438. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2439. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2440. %
  2441. \fi}
  2442. The next question is: in what order should we apply these passes? This
  2443. question can be challenging because it is difficult to know ahead of
  2444. time which orderings will be better (easier to implement, produce more
  2445. efficient code, etc.) so oftentimes trial-and-error is
  2446. involved. Nevertheless, we can try to plan ahead and make educated
  2447. choices regarding the ordering.
  2448. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2449. \key{uniquify}? The \key{uniquify} pass should come first because
  2450. \key{explicate\_control} changes all the \key{let}-bound variables to
  2451. become local variables whose scope is the entire program, which would
  2452. confuse variables with the same name.}
  2453. %
  2454. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2455. because the later removes the \key{let} form, but it is convenient to
  2456. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2457. %
  2458. \racket{The ordering of \key{uniquify} with respect to
  2459. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2460. \key{uniquify} to come first.}
  2461. The \key{select\_instructions} and \key{assign\_homes} passes are
  2462. intertwined.
  2463. %
  2464. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers are used for
  2465. passing arguments to functions and it is preferable to assign
  2466. parameters to their corresponding registers. This suggests that it
  2467. would be better to start with the \key{select\_instructions} pass,
  2468. which generates the instructions for argument passing, before
  2469. performing register allocation.
  2470. %
  2471. On the other hand, by selecting instructions first we may run into a
  2472. dead end in \key{assign\_homes}. Recall that only one argument of an
  2473. x86 instruction may be a memory access but \key{assign\_homes} might
  2474. be forced to assign both arguments to memory locations.
  2475. %
  2476. A sophisticated approach is to iteratively repeat the two passes until
  2477. a solution is found. However, to reduce implementation complexity we
  2478. recommend placing \key{select\_instructions} first, followed by the
  2479. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2480. that uses a reserved register to fix outstanding problems.
  2481. \begin{figure}[tbp]
  2482. {\if\edition\racketEd
  2483. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2484. \node (Lvar) at (0,2) {\large \LangVar{}};
  2485. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2486. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2487. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2488. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2489. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2490. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2491. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2492. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2493. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2494. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2495. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2496. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2497. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2498. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2499. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2500. \end{tikzpicture}
  2501. \fi}
  2502. {\if\edition\pythonEd
  2503. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2504. \node (Lvar) at (0,2) {\large \LangVar{}};
  2505. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2506. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2507. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2508. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2509. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2510. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2511. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2512. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2513. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2514. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2515. \end{tikzpicture}
  2516. \fi}
  2517. \caption{Diagram of the passes for compiling \LangVar{}. }
  2518. \label{fig:Lvar-passes}
  2519. \end{figure}
  2520. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2521. passes and identifies the input and output language of each pass.
  2522. %
  2523. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2524. language, which extends \LangXInt{} with an unbounded number of
  2525. program-scope variables and removes the restrictions regarding
  2526. instruction arguments.
  2527. %
  2528. The last pass, \key{prelude\_and\_conclusion}, places the program
  2529. instructions inside a \code{main} function with instructions for the
  2530. prelude and conclusion.
  2531. %
  2532. \racket{In the following section we discuss the \LangCVar{}
  2533. intermediate language.}
  2534. %
  2535. The remainder of this chapter provides guidance on the implementation
  2536. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2537. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2538. %% are programs that are still in the \LangVar{} language, though the
  2539. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2540. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2541. %% %
  2542. %% The output of \code{explicate\_control} is in an intermediate language
  2543. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2544. %% syntax, which we introduce in the next section. The
  2545. %% \key{select-instruction} pass translates from \LangCVar{} to
  2546. %% \LangXVar{}. The \key{assign-homes} and
  2547. %% \key{patch-instructions}
  2548. %% passes input and output variants of x86 assembly.
  2549. {\if\edition\racketEd
  2550. \subsection{The \LangCVar{} Intermediate Language}
  2551. The output of \code{explicate\_control} is similar to the $C$
  2552. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2553. categories for expressions and statements, so we name it \LangCVar{}.
  2554. This style of intermediate language is also known as
  2555. \emph{three-address code}, to emphasize that the typical form of a
  2556. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2557. addresses~\citep{Aho:2006wb}.
  2558. The concrete syntax for \LangCVar{} is defined in
  2559. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2560. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2561. %
  2562. The \LangCVar{} language supports the same operators as \LangVar{} but
  2563. the arguments of operators are restricted to atomic
  2564. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2565. assignment statements which can be executed in sequence using the
  2566. \key{Seq} form. A sequence of statements always ends with
  2567. \key{Return}, a guarantee that is baked into the grammar rules for
  2568. \itm{tail}. The naming of this non-terminal comes from the term
  2569. \emph{tail position}\index{subject}{tail position}, which refers to an
  2570. expression that is the last one to execute within a function.
  2571. A \LangCVar{} program consists of an alist mapping labels to
  2572. tails. This is more general than necessary for the present chapter, as
  2573. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2574. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2575. there will be just one label, \key{start}, and the whole program is
  2576. its tail.
  2577. %
  2578. The $\itm{info}$ field of the \key{CProgram} form, after the
  2579. \code{explicate\_control} pass, contains a mapping from the symbol
  2580. \key{locals} to a list of variables, that is, a list of all the
  2581. variables used in the program. At the start of the program, these
  2582. variables are uninitialized; they become initialized on their first
  2583. assignment.
  2584. \begin{figure}[tbp]
  2585. \fbox{
  2586. \begin{minipage}{0.96\textwidth}
  2587. \[
  2588. \begin{array}{lcl}
  2589. \Atm &::=& \Int \MID \Var \\
  2590. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  2591. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  2592. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  2593. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2594. \end{array}
  2595. \]
  2596. \end{minipage}
  2597. }
  2598. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2599. \label{fig:c0-concrete-syntax}
  2600. \end{figure}
  2601. \begin{figure}[tbp]
  2602. \fbox{
  2603. \begin{minipage}{0.96\textwidth}
  2604. \[
  2605. \begin{array}{lcl}
  2606. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2607. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2608. &\MID& \ADD{\Atm}{\Atm}\\
  2609. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2610. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2611. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2612. \end{array}
  2613. \]
  2614. \end{minipage}
  2615. }
  2616. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2617. \label{fig:c0-syntax}
  2618. \end{figure}
  2619. The definitional interpreter for \LangCVar{} is in the support code,
  2620. in the file \code{interp-Cvar.rkt}.
  2621. \fi}
  2622. {\if\edition\racketEd
  2623. \section{Uniquify Variables}
  2624. \label{sec:uniquify-Lvar}
  2625. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2626. programs in which every \key{let} binds a unique variable name. For
  2627. example, the \code{uniquify} pass should translate the program on the
  2628. left into the program on the right.
  2629. \begin{transformation}
  2630. \begin{lstlisting}
  2631. (let ([x 32])
  2632. (+ (let ([x 10]) x) x))
  2633. \end{lstlisting}
  2634. \compilesto
  2635. \begin{lstlisting}
  2636. (let ([x.1 32])
  2637. (+ (let ([x.2 10]) x.2) x.1))
  2638. \end{lstlisting}
  2639. \end{transformation}
  2640. The following is another example translation, this time of a program
  2641. with a \key{let} nested inside the initializing expression of another
  2642. \key{let}.
  2643. \begin{transformation}
  2644. \begin{lstlisting}
  2645. (let ([x (let ([x 4])
  2646. (+ x 1))])
  2647. (+ x 2))
  2648. \end{lstlisting}
  2649. \compilesto
  2650. \begin{lstlisting}
  2651. (let ([x.2 (let ([x.1 4])
  2652. (+ x.1 1))])
  2653. (+ x.2 2))
  2654. \end{lstlisting}
  2655. \end{transformation}
  2656. We recommend implementing \code{uniquify} by creating a structurally
  2657. recursive function named \code{uniquify-exp} that mostly just copies
  2658. an expression. However, when encountering a \key{let}, it should
  2659. generate a unique name for the variable and associate the old name
  2660. with the new name in an alist.\footnote{The Racket function
  2661. \code{gensym} is handy for generating unique variable names.} The
  2662. \code{uniquify-exp} function needs to access this alist when it gets
  2663. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2664. for the alist.
  2665. The skeleton of the \code{uniquify-exp} function is shown in
  2666. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2667. convenient to partially apply it to an alist and then apply it to
  2668. different expressions, as in the last case for primitive operations in
  2669. Figure~\ref{fig:uniquify-Lvar}. The
  2670. %
  2671. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2672. %
  2673. form of Racket is useful for transforming each element of a list to
  2674. produce a new list.\index{subject}{for/list}
  2675. \begin{figure}[tbp]
  2676. \begin{lstlisting}
  2677. (define (uniquify-exp env)
  2678. (lambda (e)
  2679. (match e
  2680. [(Var x) ___]
  2681. [(Int n) (Int n)]
  2682. [(Let x e body) ___]
  2683. [(Prim op es)
  2684. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2685. (define (uniquify p)
  2686. (match p
  2687. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2688. \end{lstlisting}
  2689. \caption{Skeleton for the \key{uniquify} pass.}
  2690. \label{fig:uniquify-Lvar}
  2691. \end{figure}
  2692. \begin{exercise}
  2693. \normalfont % I don't like the italics for exercises. -Jeremy
  2694. Complete the \code{uniquify} pass by filling in the blanks in
  2695. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2696. variables and for the \key{let} form in the file \code{compiler.rkt}
  2697. in the support code.
  2698. \end{exercise}
  2699. \begin{exercise}
  2700. \normalfont % I don't like the italics for exercises. -Jeremy
  2701. \label{ex:Lvar}
  2702. Create five \LangVar{} programs that exercise the most interesting
  2703. parts of the \key{uniquify} pass, that is, the programs should include
  2704. \key{let} forms, variables, and variables that shadow each other.
  2705. The five programs should be placed in the subdirectory named
  2706. \key{tests} and the file names should start with \code{var\_test\_}
  2707. followed by a unique integer and end with the file extension
  2708. \key{.rkt}.
  2709. %
  2710. The \key{run-tests.rkt} script in the support code checks whether the
  2711. output programs produce the same result as the input programs. The
  2712. script uses the \key{interp-tests} function
  2713. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2714. your \key{uniquify} pass on the example programs. The \code{passes}
  2715. parameter of \key{interp-tests} is a list that should have one entry
  2716. for each pass in your compiler. For now, define \code{passes} to
  2717. contain just one entry for \code{uniquify} as shown below.
  2718. \begin{lstlisting}
  2719. (define passes
  2720. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2721. \end{lstlisting}
  2722. Run the \key{run-tests.rkt} script in the support code to check
  2723. whether the output programs produce the same result as the input
  2724. programs.
  2725. \end{exercise}
  2726. \fi}
  2727. \section{Remove Complex Operands}
  2728. \label{sec:remove-complex-opera-Lvar}
  2729. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2730. into a restricted form in which the arguments of operations are atomic
  2731. expressions. Put another way, this pass removes complex
  2732. operands\index{subject}{complex operand}, such as the expression
  2733. \racket{\code{(- 10)}}\python{\code{-10}}
  2734. in the program below. This is accomplished by introducing a new
  2735. temporary variable, assigning the complex operand to the new
  2736. variable, and then using the new variable in place of the complex
  2737. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2738. right.
  2739. {\if\edition\racketEd
  2740. \begin{transformation}
  2741. % var_test_19.rkt
  2742. \begin{lstlisting}
  2743. (let ([x (+ 42 (- 10))])
  2744. (+ x 10))
  2745. \end{lstlisting}
  2746. \compilesto
  2747. \begin{lstlisting}
  2748. (let ([x (let ([tmp.1 (- 10)])
  2749. (+ 42 tmp.1))])
  2750. (+ x 10))
  2751. \end{lstlisting}
  2752. \end{transformation}
  2753. \fi}
  2754. {\if\edition\pythonEd
  2755. \begin{transformation}
  2756. \begin{lstlisting}
  2757. x = 42 + -10
  2758. print(x + 10)
  2759. \end{lstlisting}
  2760. \compilesto
  2761. \begin{lstlisting}
  2762. tmp_0 = -10
  2763. x = 42 + tmp_0
  2764. tmp_1 = x + 10
  2765. print(tmp_1)
  2766. \end{lstlisting}
  2767. \end{transformation}
  2768. \fi}
  2769. \begin{figure}[tp]
  2770. \centering
  2771. \fbox{
  2772. \begin{minipage}{0.96\textwidth}
  2773. {\if\edition\racketEd
  2774. \[
  2775. \begin{array}{rcl}
  2776. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2777. \Exp &::=& \Atm \MID \READ{} \\
  2778. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2779. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2780. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2781. \end{array}
  2782. \]
  2783. \fi}
  2784. {\if\edition\pythonEd
  2785. \[
  2786. \begin{array}{rcl}
  2787. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2788. \Exp{} &::=& \Atm \MID \READ{} \\
  2789. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2790. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2791. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2792. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2793. \end{array}
  2794. \]
  2795. \fi}
  2796. \end{minipage}
  2797. }
  2798. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2799. atomic expressions.}
  2800. \label{fig:Lvar-anf-syntax}
  2801. \end{figure}
  2802. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2803. of this pass, the language \LangVarANF{}. The only difference is that
  2804. operator arguments are restricted to be atomic expressions that are
  2805. defined by the \Atm{} non-terminal. In particular, integer constants
  2806. and variables are atomic.
  2807. The atomic expressions are pure (they do not cause side-effects or
  2808. depend on them) whereas complex expressions may have side effects,
  2809. such as \READ{}. A language with this separation between pure versus
  2810. side-effecting expressions is said to be in monadic normal
  2811. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2812. in \LangVarANF{}. An important invariant of the
  2813. \code{remove\_complex\_operands} pass is that the relative ordering
  2814. among complex expressions is not changed, but the relative ordering
  2815. between atomic expressions and complex expressions can change and
  2816. often does. The reason that these changes are behaviour preserving is
  2817. that the atomic expressions are pure.
  2818. Another well-known form for intermediate languages is the
  2819. \emph{administrative normal form}
  2820. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2821. \index{subject}{administrative normal form} \index{subject}{ANF}
  2822. %
  2823. The \LangVarANF{} language is not quite in ANF because we allow the
  2824. right-hand side of a \code{let} to be a complex expression.
  2825. {\if\edition\racketEd
  2826. We recommend implementing this pass with two mutually recursive
  2827. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2828. \code{rco\_atom} to subexpressions that need to become atomic and to
  2829. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2830. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2831. returns an expression. The \code{rco\_atom} function returns two
  2832. things: an atomic expression and an alist mapping temporary variables to
  2833. complex subexpressions. You can return multiple things from a function
  2834. using Racket's \key{values} form and you can receive multiple things
  2835. from a function call using the \key{define-values} form.
  2836. Also, the
  2837. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2838. form is useful for applying a function to each element of a list, in
  2839. the case where the function returns multiple values.
  2840. \index{subject}{for/lists}
  2841. \fi}
  2842. %
  2843. {\if\edition\pythonEd
  2844. %
  2845. We recommend implementing this pass with an auxiliary method named
  2846. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2847. Boolean that specifies whether the expression needs to become atomic
  2848. or not. The \code{rco\_exp} method should return a pair consisting of
  2849. the new expression and a list of pairs, associating new temporary
  2850. variables with their initializing expressions.
  2851. %
  2852. \fi}
  2853. {\if\edition\racketEd
  2854. Returning to the example program with the expression \code{(+ 42 (-
  2855. 10))}, the subexpression \code{(- 10)} should be processed using the
  2856. \code{rco\_atom} function because it is an argument of the \code{+} and
  2857. therefore needs to become atomic. The output of \code{rco\_atom}
  2858. applied to \code{(- 10)} is as follows.
  2859. \begin{transformation}
  2860. \begin{lstlisting}
  2861. (- 10)
  2862. \end{lstlisting}
  2863. \compilesto
  2864. \begin{lstlisting}
  2865. tmp.1
  2866. ((tmp.1 . (- 10)))
  2867. \end{lstlisting}
  2868. \end{transformation}
  2869. \fi}
  2870. %
  2871. {\if\edition\pythonEd
  2872. %
  2873. Returning to the example program with the expression \code{42 + -10},
  2874. the subexpression \code{-10} should be processed using the
  2875. \code{rco\_exp} function with \code{True} as the second argument
  2876. because \code{-10} is an argument of the \code{+} operator and
  2877. therefore needs to become atomic. The output of \code{rco\_exp}
  2878. applied to \code{-10} is as follows.
  2879. \begin{transformation}
  2880. \begin{lstlisting}
  2881. -10
  2882. \end{lstlisting}
  2883. \compilesto
  2884. \begin{lstlisting}
  2885. tmp_1
  2886. [(tmp_1, -10)]
  2887. \end{lstlisting}
  2888. \end{transformation}
  2889. %
  2890. \fi}
  2891. Take special care of programs such as the following that
  2892. %
  2893. \racket{bind a variable to an atomic expression}
  2894. %
  2895. \python{assign an atomic expression to a variable}.
  2896. %
  2897. You should leave such \racket{variable bindings}\python{assignments}
  2898. unchanged, as shown in the program on the right\\
  2899. %
  2900. {\if\edition\racketEd
  2901. \begin{transformation}
  2902. % var_test_20.rkt
  2903. \begin{lstlisting}
  2904. (let ([a 42])
  2905. (let ([b a])
  2906. b))
  2907. \end{lstlisting}
  2908. \compilesto
  2909. \begin{lstlisting}
  2910. (let ([a 42])
  2911. (let ([b a])
  2912. b))
  2913. \end{lstlisting}
  2914. \end{transformation}
  2915. \fi}
  2916. {\if\edition\pythonEd
  2917. \begin{transformation}
  2918. \begin{lstlisting}
  2919. a = 42
  2920. b = a
  2921. print(b)
  2922. \end{lstlisting}
  2923. \compilesto
  2924. \begin{lstlisting}
  2925. a = 42
  2926. b = a
  2927. print(b)
  2928. \end{lstlisting}
  2929. \end{transformation}
  2930. \fi}
  2931. %
  2932. \noindent A careless implementation might produce the following output with
  2933. unnecessary temporary variables.
  2934. \begin{center}
  2935. \begin{minipage}{0.4\textwidth}
  2936. {\if\edition\racketEd
  2937. \begin{lstlisting}
  2938. (let ([tmp.1 42])
  2939. (let ([a tmp.1])
  2940. (let ([tmp.2 a])
  2941. (let ([b tmp.2])
  2942. b))))
  2943. \end{lstlisting}
  2944. \fi}
  2945. {\if\edition\pythonEd
  2946. \begin{lstlisting}
  2947. tmp_1 = 42
  2948. a = tmp_1
  2949. tmp_2 = a
  2950. b = tmp_2
  2951. print(b)
  2952. \end{lstlisting}
  2953. \fi}
  2954. \end{minipage}
  2955. \end{center}
  2956. \begin{exercise}
  2957. \normalfont
  2958. {\if\edition\racketEd
  2959. Implement the \code{remove\_complex\_operands} function in
  2960. \code{compiler.rkt}.
  2961. %
  2962. Create three new \LangVar{} programs that exercise the interesting
  2963. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2964. regarding file names described in Exercise~\ref{ex:Lvar}.
  2965. %
  2966. In the \code{run-tests.rkt} script, add the following entry to the
  2967. list of \code{passes} and then run the script to test your compiler.
  2968. \begin{lstlisting}
  2969. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  2970. \end{lstlisting}
  2971. While debugging your compiler, it is often useful to see the
  2972. intermediate programs that are output from each pass. To print the
  2973. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2974. \code{interp-tests} in \code{run-tests.rkt}.
  2975. \fi}
  2976. %
  2977. {\if\edition\pythonEd
  2978. Implement the \code{remove\_complex\_operands} pass in
  2979. \code{compiler.py}, creating auxiliary functions for each
  2980. non-terminal in the grammar, i.e., \code{rco\_exp}
  2981. and \code{rco\_stmt}.
  2982. \fi}
  2983. \end{exercise}
  2984. {\if\edition\pythonEd
  2985. \begin{exercise}
  2986. \normalfont % I don't like the italics for exercises. -Jeremy
  2987. \label{ex:Lvar}
  2988. Create five \LangVar{} programs that exercise the most interesting
  2989. parts of the \code{remove\_complex\_operands} pass. The five programs
  2990. should be placed in the subdirectory named \key{tests} and the file
  2991. names should start with \code{var\_test\_} followed by a unique
  2992. integer and end with the file extension \key{.py}.
  2993. %% The \key{run-tests.rkt} script in the support code checks whether the
  2994. %% output programs produce the same result as the input programs. The
  2995. %% script uses the \key{interp-tests} function
  2996. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2997. %% your \key{uniquify} pass on the example programs. The \code{passes}
  2998. %% parameter of \key{interp-tests} is a list that should have one entry
  2999. %% for each pass in your compiler. For now, define \code{passes} to
  3000. %% contain just one entry for \code{uniquify} as shown below.
  3001. %% \begin{lstlisting}
  3002. %% (define passes
  3003. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3004. %% \end{lstlisting}
  3005. Run the \key{run-tests.py} script in the support code to check
  3006. whether the output programs produce the same result as the input
  3007. programs.
  3008. \end{exercise}
  3009. \fi}
  3010. {\if\edition\racketEd
  3011. \section{Explicate Control}
  3012. \label{sec:explicate-control-Lvar}
  3013. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3014. programs that make the order of execution explicit in their
  3015. syntax. For now this amounts to flattening \key{let} constructs into a
  3016. sequence of assignment statements. For example, consider the following
  3017. \LangVar{} program.\\
  3018. % var_test_11.rkt
  3019. \begin{minipage}{0.96\textwidth}
  3020. \begin{lstlisting}
  3021. (let ([y (let ([x 20])
  3022. (+ x (let ([x 22]) x)))])
  3023. y)
  3024. \end{lstlisting}
  3025. \end{minipage}\\
  3026. %
  3027. The output of the previous pass and of \code{explicate\_control} is
  3028. shown below. Recall that the right-hand-side of a \key{let} executes
  3029. before its body, so the order of evaluation for this program is to
  3030. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  3031. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  3032. output of \code{explicate\_control} makes this ordering explicit.
  3033. \begin{transformation}
  3034. \begin{lstlisting}
  3035. (let ([y (let ([x.1 20])
  3036. (let ([x.2 22])
  3037. (+ x.1 x.2)))])
  3038. y)
  3039. \end{lstlisting}
  3040. \compilesto
  3041. \begin{lstlisting}[language=C]
  3042. start:
  3043. x.1 = 20;
  3044. x.2 = 22;
  3045. y = (+ x.1 x.2);
  3046. return y;
  3047. \end{lstlisting}
  3048. \end{transformation}
  3049. \begin{figure}[tbp]
  3050. \begin{lstlisting}
  3051. (define (explicate_tail e)
  3052. (match e
  3053. [(Var x) ___]
  3054. [(Int n) (Return (Int n))]
  3055. [(Let x rhs body) ___]
  3056. [(Prim op es) ___]
  3057. [else (error "explicate_tail unhandled case" e)]))
  3058. (define (explicate_assign e x cont)
  3059. (match e
  3060. [(Var x) ___]
  3061. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3062. [(Let y rhs body) ___]
  3063. [(Prim op es) ___]
  3064. [else (error "explicate_assign unhandled case" e)]))
  3065. (define (explicate_control p)
  3066. (match p
  3067. [(Program info body) ___]))
  3068. \end{lstlisting}
  3069. \caption{Skeleton for the \code{explicate\_control} pass.}
  3070. \label{fig:explicate-control-Lvar}
  3071. \end{figure}
  3072. The organization of this pass depends on the notion of tail position
  3073. that we have alluded to earlier.
  3074. \begin{definition}
  3075. The following rules define when an expression is in \textbf{\emph{tail
  3076. position}}\index{subject}{tail position} for the language \LangVar{}.
  3077. \begin{enumerate}
  3078. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3079. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3080. \end{enumerate}
  3081. \end{definition}
  3082. We recommend implementing \code{explicate\_control} using two mutually
  3083. recursive functions, \code{explicate\_tail} and
  3084. \code{explicate\_assign}, as suggested in the skeleton code in
  3085. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3086. function should be applied to expressions in tail position whereas the
  3087. \code{explicate\_assign} should be applied to expressions that occur on
  3088. the right-hand-side of a \key{let}.
  3089. %
  3090. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3091. input and produces a \Tail{} in \LangCVar{} (see
  3092. Figure~\ref{fig:c0-syntax}).
  3093. %
  3094. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3095. the variable that it is to be assigned to, and a \Tail{} in
  3096. \LangCVar{} for the code that comes after the assignment. The
  3097. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3098. The \code{explicate\_assign} function is in accumulator-passing style:
  3099. the \code{cont} parameter is used for accumulating the output. This
  3100. accumulator-passing style plays an important role in how we generate
  3101. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3102. \begin{exercise}\normalfont
  3103. %
  3104. Implement the \code{explicate\_control} function in
  3105. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3106. exercise the code in \code{explicate\_control}.
  3107. %
  3108. In the \code{run-tests.rkt} script, add the following entry to the
  3109. list of \code{passes} and then run the script to test your compiler.
  3110. \begin{lstlisting}
  3111. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3112. \end{lstlisting}
  3113. \end{exercise}
  3114. \fi}
  3115. \section{Select Instructions}
  3116. \label{sec:select-Lvar}
  3117. \index{subject}{instruction selection}
  3118. In the \code{select\_instructions} pass we begin the work of
  3119. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3120. language of this pass is a variant of x86 that still uses variables,
  3121. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3122. non-terminal of the \LangXInt{} abstract syntax
  3123. (Figure~\ref{fig:x86-int-ast}).
  3124. \racket{We recommend implementing the
  3125. \code{select\_instructions} with three auxiliary functions, one for
  3126. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3127. $\Tail$.}
  3128. \python{We recommend implementing an auxiliary function
  3129. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3130. \racket{
  3131. The cases for $\Atm$ are straightforward; variables stay
  3132. the same and integer constants change to immediates:
  3133. $\INT{n}$ changes to $\IMM{n}$.}
  3134. We consider the cases for the $\Stmt$ non-terminal, starting with
  3135. arithmetic operations. For example, consider the addition operation
  3136. below, on the left side. There is an \key{addq} instruction in x86,
  3137. but it performs an in-place update. So we could move $\Arg_1$
  3138. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3139. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3140. $\Atm_1$ and $\Atm_2$ respectively.
  3141. \begin{transformation}
  3142. {\if\edition\racketEd
  3143. \begin{lstlisting}
  3144. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3145. \end{lstlisting}
  3146. \fi}
  3147. {\if\edition\pythonEd
  3148. \begin{lstlisting}
  3149. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3150. \end{lstlisting}
  3151. \fi}
  3152. \compilesto
  3153. \begin{lstlisting}
  3154. movq |$\Arg_1$|, |$\itm{var}$|
  3155. addq |$\Arg_2$|, |$\itm{var}$|
  3156. \end{lstlisting}
  3157. \end{transformation}
  3158. There are also cases that require special care to avoid generating
  3159. needlessly complicated code. For example, if one of the arguments of
  3160. the addition is the same variable as the left-hand side of the
  3161. assignment, as shown below, then there is no need for the extra move
  3162. instruction. The assignment statement can be translated into a single
  3163. \key{addq} instruction as follows.
  3164. \begin{transformation}
  3165. {\if\edition\racketEd
  3166. \begin{lstlisting}
  3167. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3168. \end{lstlisting}
  3169. \fi}
  3170. {\if\edition\pythonEd
  3171. \begin{lstlisting}
  3172. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3173. \end{lstlisting}
  3174. \fi}
  3175. \compilesto
  3176. \begin{lstlisting}
  3177. addq |$\Arg_1$|, |$\itm{var}$|
  3178. \end{lstlisting}
  3179. \end{transformation}
  3180. The \READOP{} operation does not have a direct counterpart in x86
  3181. assembly, so we provide this functionality with the function
  3182. \code{read\_int} in the file \code{runtime.c}, written in
  3183. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3184. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3185. system}, or simply the \emph{runtime} for short. When compiling your
  3186. generated x86 assembly code, you need to compile \code{runtime.c} to
  3187. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3188. \code{-c}) and link it into the executable. For our purposes of code
  3189. generation, all you need to do is translate an assignment of
  3190. \READOP{} into a call to the \code{read\_int} function followed by a
  3191. move from \code{rax} to the left-hand-side variable. (Recall that the
  3192. return value of a function goes into \code{rax}.)
  3193. \begin{transformation}
  3194. {\if\edition\racketEd
  3195. \begin{lstlisting}
  3196. |$\itm{var}$| = (read);
  3197. \end{lstlisting}
  3198. \fi}
  3199. {\if\edition\pythonEd
  3200. \begin{lstlisting}
  3201. |$\itm{var}$| = input_int();
  3202. \end{lstlisting}
  3203. \fi}
  3204. \compilesto
  3205. \begin{lstlisting}
  3206. callq read_int
  3207. movq %rax, |$\itm{var}$|
  3208. \end{lstlisting}
  3209. \end{transformation}
  3210. {\if\edition\pythonEd
  3211. %
  3212. Similarly, we translate the \code{print} operation, shown below, into
  3213. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3214. In x86, the first six arguments to functions are passed in registers,
  3215. with the first argument passed in register \code{rdi}. So we move the
  3216. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3217. \code{callq} instruction.
  3218. \begin{transformation}
  3219. \begin{lstlisting}
  3220. print(|$\Atm$|)
  3221. \end{lstlisting}
  3222. \compilesto
  3223. \begin{lstlisting}
  3224. movq |$\Arg$|, %rdi
  3225. callq print_int
  3226. \end{lstlisting}
  3227. \end{transformation}
  3228. %
  3229. \fi}
  3230. {\if\edition\racketEd
  3231. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3232. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3233. assignment to the \key{rax} register followed by a jump to the
  3234. conclusion of the program (so the conclusion needs to be labeled).
  3235. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3236. recursively and then append the resulting instructions.
  3237. \fi}
  3238. \begin{exercise}
  3239. \normalfont
  3240. {\if\edition\racketEd
  3241. Implement the \code{select\_instructions} pass in
  3242. \code{compiler.rkt}. Create three new example programs that are
  3243. designed to exercise all of the interesting cases in this pass.
  3244. %
  3245. In the \code{run-tests.rkt} script, add the following entry to the
  3246. list of \code{passes} and then run the script to test your compiler.
  3247. \begin{lstlisting}
  3248. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3249. \end{lstlisting}
  3250. \fi}
  3251. {\if\edition\pythonEd
  3252. Implement the \key{select\_instructions} pass in
  3253. \code{compiler.py}. Create three new example programs that are
  3254. designed to exercise all of the interesting cases in this pass.
  3255. Run the \code{run-tests.py} script to to check
  3256. whether the output programs produce the same result as the input
  3257. programs.
  3258. \fi}
  3259. \end{exercise}
  3260. \section{Assign Homes}
  3261. \label{sec:assign-Lvar}
  3262. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3263. \LangXVar{} programs that no longer use program variables.
  3264. Thus, the \key{assign-homes} pass is responsible for placing all of
  3265. the program variables in registers or on the stack. For runtime
  3266. efficiency, it is better to place variables in registers, but as there
  3267. are only 16 registers, some programs must necessarily resort to
  3268. placing some variables on the stack. In this chapter we focus on the
  3269. mechanics of placing variables on the stack. We study an algorithm for
  3270. placing variables in registers in
  3271. Chapter~\ref{ch:register-allocation-Lvar}.
  3272. Consider again the following \LangVar{} program from
  3273. Section~\ref{sec:remove-complex-opera-Lvar}.
  3274. % var_test_20.rkt
  3275. {\if\edition\racketEd
  3276. \begin{lstlisting}
  3277. (let ([a 42])
  3278. (let ([b a])
  3279. b))
  3280. \end{lstlisting}
  3281. \fi}
  3282. {\if\edition\pythonEd
  3283. \begin{lstlisting}
  3284. a = 42
  3285. b = a
  3286. print(b)
  3287. \end{lstlisting}
  3288. \fi}
  3289. %
  3290. The output of \code{select\_instructions} is shown below, on the left,
  3291. and the output of \code{assign\_homes} is on the right. In this
  3292. example, we assign variable \code{a} to stack location
  3293. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3294. \begin{transformation}
  3295. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3296. movq $42, a
  3297. movq a, b
  3298. movq b, %rax
  3299. \end{lstlisting}
  3300. \compilesto
  3301. %stack-space: 16
  3302. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3303. movq $42, -8(%rbp)
  3304. movq -8(%rbp), -16(%rbp)
  3305. movq -16(%rbp), %rax
  3306. \end{lstlisting}
  3307. \end{transformation}
  3308. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3309. \code{X86Program} node is an alist mapping all the variables in the
  3310. program to their types (for now just \code{Integer}). The
  3311. \code{assign\_homes} pass should replace all uses of those variables
  3312. with stack locations. As an aside, the \code{locals-types} entry is
  3313. computed by \code{type-check-Cvar} in the support code, which
  3314. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3315. which should be propagated to the \code{X86Program} node.}
  3316. %
  3317. \python{The \code{assign\_homes} pass should replace all uses of
  3318. variables with stack locations.}
  3319. %
  3320. In the process of assigning variables to stack locations, it is
  3321. convenient for you to compute and store the size of the frame (in
  3322. bytes) in%
  3323. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3324. %
  3325. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3326. which is needed later to generate the conclusion of the \code{main}
  3327. procedure. The x86-64 standard requires the frame size to be a
  3328. multiple of 16 bytes.\index{subject}{frame}
  3329. % TODO: store the number of variables instead? -Jeremy
  3330. \begin{exercise}\normalfont
  3331. Implement the \key{assign\_homes} pass in
  3332. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3333. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3334. grammar. We recommend that the auxiliary functions take an extra
  3335. parameter that maps variable names to homes (stack locations for now).
  3336. %
  3337. {\if\edition\racketEd
  3338. In the \code{run-tests.rkt} script, add the following entry to the
  3339. list of \code{passes} and then run the script to test your compiler.
  3340. \begin{lstlisting}
  3341. (list "assign homes" assign-homes interp_x86-0)
  3342. \end{lstlisting}
  3343. \fi}
  3344. {\if\edition\pythonEd
  3345. Run the \code{run-tests.py} script to to check
  3346. whether the output programs produce the same result as the input
  3347. programs.
  3348. \fi}
  3349. \end{exercise}
  3350. \section{Patch Instructions}
  3351. \label{sec:patch-s0}
  3352. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3353. \LangXInt{} by making sure that each instruction adheres to the
  3354. restriction that at most one argument of an instruction may be a
  3355. memory reference.
  3356. We return to the following example.\\
  3357. \begin{minipage}{0.5\textwidth}
  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. \end{minipage}\\
  3374. The \key{assign\_homes} pass produces the following translation. \\
  3375. \begin{minipage}{0.5\textwidth}
  3376. {\if\edition\racketEd
  3377. \begin{lstlisting}
  3378. movq $42, -8(%rbp)
  3379. movq -8(%rbp), -16(%rbp)
  3380. movq -16(%rbp), %rax
  3381. \end{lstlisting}
  3382. \fi}
  3383. {\if\edition\pythonEd
  3384. \begin{lstlisting}
  3385. movq 42, -8(%rbp)
  3386. movq -8(%rbp), -16(%rbp)
  3387. movq -16(%rbp), %rdi
  3388. callq print_int
  3389. \end{lstlisting}
  3390. \fi}
  3391. \end{minipage}\\
  3392. The second \key{movq} instruction is problematic because both
  3393. arguments are stack locations. We suggest fixing this problem by
  3394. moving from the source location to the register \key{rax} and then
  3395. from \key{rax} to the destination location, as follows.
  3396. \begin{lstlisting}
  3397. movq -8(%rbp), %rax
  3398. movq %rax, -16(%rbp)
  3399. \end{lstlisting}
  3400. \begin{exercise}
  3401. \normalfont Implement the \key{patch\_instructions} pass in
  3402. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3403. Create three new example programs that are
  3404. designed to exercise all of the interesting cases in this pass.
  3405. %
  3406. {\if\edition\racketEd
  3407. In the \code{run-tests.rkt} script, add the following entry to the
  3408. list of \code{passes} and then run the script to test your compiler.
  3409. \begin{lstlisting}
  3410. (list "patch instructions" patch_instructions interp_x86-0)
  3411. \end{lstlisting}
  3412. \fi}
  3413. {\if\edition\pythonEd
  3414. Run the \code{run-tests.py} script to to check
  3415. whether the output programs produce the same result as the input
  3416. programs.
  3417. \fi}
  3418. \end{exercise}
  3419. \section{Generate Prelude and Conclusion}
  3420. \label{sec:print-x86}
  3421. \index{subject}{prelude}\index{subject}{conclusion}
  3422. The last step of the compiler from \LangVar{} to x86 is to generate
  3423. the \code{main} function with a prelude and conclusion wrapped around
  3424. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3425. discussed in Section~\ref{sec:x86}.
  3426. When running on Mac OS X, your compiler should prefix an underscore to
  3427. all labels, e.g., changing \key{main} to \key{\_main}.
  3428. %
  3429. \racket{The Racket call \code{(system-type 'os)} is useful for
  3430. determining which operating system the compiler is running on. It
  3431. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3432. %
  3433. \python{The Python \code{platform} library includes a \code{system()}
  3434. function that returns \code{'Linux'}, \code{'Windows'}, or
  3435. \code{'Darwin'} (for Mac).}
  3436. \begin{exercise}\normalfont
  3437. %
  3438. Implement the \key{prelude\_and\_conclusion} pass in
  3439. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3440. %
  3441. {\if\edition\racketEd
  3442. In the \code{run-tests.rkt} script, add the following entry to the
  3443. list of \code{passes} and then run the script to test your compiler.
  3444. \begin{lstlisting}
  3445. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3446. \end{lstlisting}
  3447. %
  3448. Uncomment the call to the \key{compiler-tests} function
  3449. (Appendix~\ref{appendix:utilities}), which tests your complete
  3450. compiler by executing the generated x86 code. It translates the x86
  3451. AST that you produce into a string by invoking the \code{print-x86}
  3452. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3453. the provided \key{runtime.c} file to \key{runtime.o} using
  3454. \key{gcc}. Run the script to test your compiler.
  3455. %
  3456. \fi}
  3457. {\if\edition\pythonEd
  3458. %
  3459. Run the \code{run-tests.py} script to to check whether the output
  3460. programs produce the same result as the input programs. That script
  3461. translates the x86 AST that you produce into a string by invoking the
  3462. \code{repr} method that is implemented by the x86 AST classes in
  3463. \code{x86\_ast.py}.
  3464. %
  3465. \fi}
  3466. \end{exercise}
  3467. \section{Challenge: Partial Evaluator for \LangVar{}}
  3468. \label{sec:pe-Lvar}
  3469. \index{subject}{partial evaluation}
  3470. This section describes two optional challenge exercises that involve
  3471. adapting and improving the partial evaluator for \LangInt{} that was
  3472. introduced in Section~\ref{sec:partial-evaluation}.
  3473. \begin{exercise}\label{ex:pe-Lvar}
  3474. \normalfont
  3475. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3476. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3477. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3478. %
  3479. \racket{\key{let} binding}\python{assignment}
  3480. %
  3481. to the \LangInt{} language, so you will need to add cases for them in
  3482. the \code{pe\_exp}
  3483. %
  3484. \racket{function}
  3485. %
  3486. \python{and \code{pe\_stmt} functions}.
  3487. %
  3488. Once complete, add the partial evaluation pass to the front of your
  3489. compiler and make sure that your compiler still passes all of the
  3490. tests.
  3491. \end{exercise}
  3492. \begin{exercise}
  3493. \normalfont
  3494. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3495. \code{pe\_add} auxiliary functions with functions that know more about
  3496. arithmetic. For example, your partial evaluator should translate
  3497. {\if\edition\racketEd
  3498. \[
  3499. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3500. \code{(+ 2 (read))}
  3501. \]
  3502. \fi}
  3503. {\if\edition\pythonEd
  3504. \[
  3505. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3506. \code{2 + input\_int()}
  3507. \]
  3508. \fi}
  3509. To accomplish this, the \code{pe\_exp} function should produce output
  3510. in the form of the $\itm{residual}$ non-terminal of the following
  3511. grammar. The idea is that when processing an addition expression, we
  3512. can always produce either 1) an integer constant, 2) an addition
  3513. expression with an integer constant on the left-hand side but not the
  3514. right-hand side, or 3) or an addition expression in which neither
  3515. subexpression is a constant.
  3516. {\if\edition\racketEd
  3517. \[
  3518. \begin{array}{lcl}
  3519. \itm{inert} &::=& \Var
  3520. \MID \LP\key{read}\RP
  3521. \MID \LP\key{-} ~\Var\RP
  3522. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3523. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3524. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3525. \itm{residual} &::=& \Int
  3526. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3527. \MID \itm{inert}
  3528. \end{array}
  3529. \]
  3530. \fi}
  3531. {\if\edition\pythonEd
  3532. \[
  3533. \begin{array}{lcl}
  3534. \itm{inert} &::=& \Var
  3535. \MID \key{input\_int}\LP\RP
  3536. \MID \key{-} \Var
  3537. \MID \key{-} \key{input\_int}\LP\RP
  3538. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3539. \itm{residual} &::=& \Int
  3540. \MID \Int ~ \key{+} ~ \itm{inert}
  3541. \MID \itm{inert}
  3542. \end{array}
  3543. \]
  3544. \fi}
  3545. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3546. inputs are $\itm{residual}$ expressions and they should return
  3547. $\itm{residual}$ expressions. Once the improvements are complete,
  3548. make sure that your compiler still passes all of the tests. After
  3549. all, fast code is useless if it produces incorrect results!
  3550. \end{exercise}
  3551. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3552. \chapter{Register Allocation}
  3553. \label{ch:register-allocation-Lvar}
  3554. \index{subject}{register allocation}
  3555. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3556. stack. In this chapter we learn how to improve the performance of the
  3557. generated code by assigning some variables to registers. The CPU can
  3558. access a register in a single cycle, whereas accessing the stack can
  3559. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3560. serves as a running example. The source program is on the left and the
  3561. output of instruction selection is on the right. The program is almost
  3562. in the x86 assembly language but it still uses variables.
  3563. \begin{figure}
  3564. \begin{minipage}{0.45\textwidth}
  3565. Example \LangVar{} program:
  3566. % var_test_28.rkt
  3567. {\if\edition\racketEd
  3568. \begin{lstlisting}
  3569. (let ([v 1])
  3570. (let ([w 42])
  3571. (let ([x (+ v 7)])
  3572. (let ([y x])
  3573. (let ([z (+ x w)])
  3574. (+ z (- y)))))))
  3575. \end{lstlisting}
  3576. \fi}
  3577. {\if\edition\pythonEd
  3578. \begin{lstlisting}
  3579. v = 1
  3580. w = 42
  3581. x = v + 7
  3582. y = x
  3583. z = x + w
  3584. print(z + (- y))
  3585. \end{lstlisting}
  3586. \fi}
  3587. \end{minipage}
  3588. \begin{minipage}{0.45\textwidth}
  3589. After instruction selection:
  3590. {\if\edition\racketEd
  3591. \begin{lstlisting}
  3592. locals-types:
  3593. x : Integer, y : Integer,
  3594. z : Integer, t : Integer,
  3595. v : Integer, w : Integer
  3596. start:
  3597. movq $1, v
  3598. movq $42, w
  3599. movq v, x
  3600. addq $7, x
  3601. movq x, y
  3602. movq x, z
  3603. addq w, z
  3604. movq y, t
  3605. negq t
  3606. movq z, %rax
  3607. addq t, %rax
  3608. jmp conclusion
  3609. \end{lstlisting}
  3610. \fi}
  3611. {\if\edition\pythonEd
  3612. \begin{lstlisting}
  3613. movq $1, v
  3614. movq $42, w
  3615. movq v, x
  3616. addq $7, x
  3617. movq x, y
  3618. movq x, z
  3619. addq w, z
  3620. movq y, tmp_0
  3621. negq tmp_0
  3622. movq z, tmp_1
  3623. addq tmp_0, tmp_1
  3624. movq tmp_1, %rdi
  3625. callq print_int
  3626. \end{lstlisting}
  3627. \fi}
  3628. \end{minipage}
  3629. \caption{A running example for register allocation.}
  3630. \label{fig:reg-eg}
  3631. \end{figure}
  3632. The goal of register allocation is to fit as many variables into
  3633. registers as possible. Some programs have more variables than
  3634. registers so we cannot always map each variable to a different
  3635. register. Fortunately, it is common for different variables to be
  3636. needed during different periods of time during program execution, and
  3637. in such cases several variables can be mapped to the same register.
  3638. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3639. After the variable \code{x} is moved to \code{z} it is no longer
  3640. needed. Variable \code{z}, on the other hand, is used only after this
  3641. point, so \code{x} and \code{z} could share the same register. The
  3642. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3643. where a variable is needed. Once we have that information, we compute
  3644. which variables are needed at the same time, i.e., which ones
  3645. \emph{interfere} with each other, and represent this relation as an
  3646. undirected graph whose vertices are variables and edges indicate when
  3647. two variables interfere (Section~\ref{sec:build-interference}). We
  3648. then model register allocation as a graph coloring problem
  3649. (Section~\ref{sec:graph-coloring}).
  3650. If we run out of registers despite these efforts, we place the
  3651. remaining variables on the stack, similar to what we did in
  3652. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3653. assigning a variable to a stack location. The decision to spill a
  3654. variable is handled as part of the graph coloring process.
  3655. We make the simplifying assumption that each variable is assigned to
  3656. one location (a register or stack address). A more sophisticated
  3657. approach is to assign a variable to one or more locations in different
  3658. regions of the program. For example, if a variable is used many times
  3659. in short sequence and then only used again after many other
  3660. instructions, it could be more efficient to assign the variable to a
  3661. register during the initial sequence and then move it to the stack for
  3662. the rest of its lifetime. We refer the interested reader to
  3663. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3664. approach.
  3665. % discuss prioritizing variables based on how much they are used.
  3666. \section{Registers and Calling Conventions}
  3667. \label{sec:calling-conventions}
  3668. \index{subject}{calling conventions}
  3669. As we perform register allocation, we need to be aware of the
  3670. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3671. functions calls are performed in x86.
  3672. %
  3673. Even though \LangVar{} does not include programmer-defined functions,
  3674. our generated code includes a \code{main} function that is called by
  3675. the operating system and our generated code contains calls to the
  3676. \code{read\_int} function.
  3677. Function calls require coordination between two pieces of code that
  3678. may be written by different programmers or generated by different
  3679. compilers. Here we follow the System V calling conventions that are
  3680. used by the GNU C compiler on Linux and
  3681. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3682. %
  3683. The calling conventions include rules about how functions share the
  3684. use of registers. In particular, the caller is responsible for freeing
  3685. up some registers prior to the function call for use by the callee.
  3686. These are called the \emph{caller-saved registers}
  3687. \index{subject}{caller-saved registers}
  3688. and they are
  3689. \begin{lstlisting}
  3690. rax rcx rdx rsi rdi r8 r9 r10 r11
  3691. \end{lstlisting}
  3692. On the other hand, the callee is responsible for preserving the values
  3693. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3694. which are
  3695. \begin{lstlisting}
  3696. rsp rbp rbx r12 r13 r14 r15
  3697. \end{lstlisting}
  3698. We can think about this caller/callee convention from two points of
  3699. view, the caller view and the callee view:
  3700. \begin{itemize}
  3701. \item The caller should assume that all the caller-saved registers get
  3702. overwritten with arbitrary values by the callee. On the other hand,
  3703. the caller can safely assume that all the callee-saved registers
  3704. contain the same values after the call that they did before the
  3705. call.
  3706. \item The callee can freely use any of the caller-saved registers.
  3707. However, if the callee wants to use a callee-saved register, the
  3708. callee must arrange to put the original value back in the register
  3709. prior to returning to the caller. This can be accomplished by saving
  3710. the value to the stack in the prelude of the function and restoring
  3711. the value in the conclusion of the function.
  3712. \end{itemize}
  3713. In x86, registers are also used for passing arguments to a function
  3714. and for the return value. In particular, the first six arguments to a
  3715. function are passed in the following six registers, in this order.
  3716. \begin{lstlisting}
  3717. rdi rsi rdx rcx r8 r9
  3718. \end{lstlisting}
  3719. If there are more than six arguments, then the convention is to use
  3720. space on the frame of the caller for the rest of the
  3721. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3722. need more than six arguments.
  3723. %
  3724. \racket{For now, the only function we care about is \code{read\_int}
  3725. and it takes zero arguments.}
  3726. %
  3727. \python{For now, the only functions we care about are \code{read\_int}
  3728. and \code{print\_int}, which take zero and one argument, respectively.}
  3729. %
  3730. The register \code{rax} is used for the return value of a function.
  3731. The next question is how these calling conventions impact register
  3732. allocation. Consider the \LangVar{} program in
  3733. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3734. example from the caller point of view and then from the callee point
  3735. of view.
  3736. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3737. is in use during the second call to \READOP{}, so we need to make sure
  3738. that the value in \code{x} does not get accidentally wiped out by the
  3739. call to \READOP{}. One obvious approach is to save all the values in
  3740. caller-saved registers to the stack prior to each function call, and
  3741. restore them after each call. That way, if the register allocator
  3742. chooses to assign \code{x} to a caller-saved register, its value will
  3743. be preserved across the call to \READOP{}. However, saving and
  3744. restoring to the stack is relatively slow. If \code{x} is not used
  3745. many times, it may be better to assign \code{x} to a stack location in
  3746. the first place. Or better yet, if we can arrange for \code{x} to be
  3747. placed in a callee-saved register, then it won't need to be saved and
  3748. restored during function calls.
  3749. The approach that we recommend for variables that are in use during a
  3750. function call is to either assign them to callee-saved registers or to
  3751. spill them to the stack. On the other hand, for variables that are not
  3752. in use during a function call, we try the following alternatives in
  3753. order 1) look for an available caller-saved register (to leave room
  3754. for other variables in the callee-saved register), 2) look for a
  3755. callee-saved register, and 3) spill the variable to the stack.
  3756. It is straightforward to implement this approach in a graph coloring
  3757. register allocator. First, we know which variables are in use during
  3758. every function call because we compute that information for every
  3759. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3760. we build the interference graph
  3761. (Section~\ref{sec:build-interference}), we can place an edge between
  3762. each of these call-live variables and the caller-saved registers in
  3763. the interference graph. This will prevent the graph coloring algorithm
  3764. from assigning them to caller-saved registers.
  3765. Returning to the example in
  3766. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3767. generated x86 code on the right-hand side. Notice that variable
  3768. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3769. is already in a safe place during the second call to
  3770. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3771. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3772. live-after set of a \code{callq} instruction.
  3773. Next we analyze the example from the callee point of view, focusing on
  3774. the prelude and conclusion of the \code{main} function. As usual the
  3775. prelude begins with saving the \code{rbp} register to the stack and
  3776. setting the \code{rbp} to the current stack pointer. We now know why
  3777. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3778. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3779. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3780. (\code{x}). The other callee-saved registers are not saved in the
  3781. prelude because they are not used. The prelude subtracts 8 bytes from
  3782. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3783. conclusion, we see that \code{rbx} is restored from the stack with a
  3784. \code{popq} instruction.
  3785. \index{subject}{prelude}\index{subject}{conclusion}
  3786. \begin{figure}[tp]
  3787. \begin{minipage}{0.45\textwidth}
  3788. Example \LangVar{} program:
  3789. %var_test_14.rkt
  3790. {\if\edition\racketEd
  3791. \begin{lstlisting}
  3792. (let ([x (read)])
  3793. (let ([y (read)])
  3794. (+ (+ x y) 42)))
  3795. \end{lstlisting}
  3796. \fi}
  3797. {\if\edition\pythonEd
  3798. \begin{lstlisting}
  3799. x = input_int()
  3800. y = input_int()
  3801. print((x + y) + 42)
  3802. \end{lstlisting}
  3803. \fi}
  3804. \end{minipage}
  3805. \begin{minipage}{0.45\textwidth}
  3806. Generated x86 assembly:
  3807. {\if\edition\racketEd
  3808. \begin{lstlisting}
  3809. start:
  3810. callq read_int
  3811. movq %rax, %rbx
  3812. callq read_int
  3813. movq %rax, %rcx
  3814. addq %rcx, %rbx
  3815. movq %rbx, %rax
  3816. addq $42, %rax
  3817. jmp _conclusion
  3818. .globl main
  3819. main:
  3820. pushq %rbp
  3821. movq %rsp, %rbp
  3822. pushq %rbx
  3823. subq $8, %rsp
  3824. jmp start
  3825. conclusion:
  3826. addq $8, %rsp
  3827. popq %rbx
  3828. popq %rbp
  3829. retq
  3830. \end{lstlisting}
  3831. \fi}
  3832. {\if\edition\pythonEd
  3833. \begin{lstlisting}
  3834. .globl main
  3835. main:
  3836. pushq %rbp
  3837. movq %rsp, %rbp
  3838. pushq %rbx
  3839. subq $8, %rsp
  3840. callq read_int
  3841. movq %rax, %rbx
  3842. callq read_int
  3843. movq %rax, %rcx
  3844. movq %rbx, %rdx
  3845. addq %rcx, %rdx
  3846. movq %rdx, %rcx
  3847. addq $42, %rcx
  3848. movq %rcx, %rdi
  3849. callq print_int
  3850. addq $8, %rsp
  3851. popq %rbx
  3852. popq %rbp
  3853. retq
  3854. \end{lstlisting}
  3855. \fi}
  3856. \end{minipage}
  3857. \caption{An example with function calls.}
  3858. \label{fig:example-calling-conventions}
  3859. \end{figure}
  3860. %\clearpage
  3861. \section{Liveness Analysis}
  3862. \label{sec:liveness-analysis-Lvar}
  3863. \index{subject}{liveness analysis}
  3864. The \code{uncover\_live} \racket{pass}\python{function}
  3865. performs \emph{liveness analysis}, that
  3866. is, it discovers which variables are in-use in different regions of a
  3867. program.
  3868. %
  3869. A variable or register is \emph{live} at a program point if its
  3870. current value is used at some later point in the program. We refer to
  3871. variables, stack locations, and registers collectively as
  3872. \emph{locations}.
  3873. %
  3874. Consider the following code fragment in which there are two writes to
  3875. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3876. \begin{center}
  3877. \begin{minipage}{0.96\textwidth}
  3878. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3879. movq $5, a
  3880. movq $30, b
  3881. movq a, c
  3882. movq $10, b
  3883. addq b, c
  3884. \end{lstlisting}
  3885. \end{minipage}
  3886. \end{center}
  3887. The answer is no because \code{a} is live from line 1 to 3 and
  3888. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3889. line 2 is never used because it is overwritten (line 4) before the
  3890. next read (line 5).
  3891. The live locations can be computed by traversing the instruction
  3892. sequence back to front (i.e., backwards in execution order). Let
  3893. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3894. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3895. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3896. locations before instruction $I_k$.
  3897. \racket{We recommend representing these
  3898. sets with the Racket \code{set} data structure described in
  3899. Figure~\ref{fig:set}.}
  3900. \python{We recommend representing these sets with the Python
  3901. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3902. data structure.}
  3903. {\if\edition\racketEd
  3904. \begin{figure}[tp]
  3905. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3906. \small
  3907. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3908. A \emph{set} is an unordered collection of elements without duplicates.
  3909. Here are some of the operations defined on sets.
  3910. \index{subject}{set}
  3911. \begin{description}
  3912. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3913. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3914. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3915. difference of the two sets.
  3916. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3917. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3918. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3919. \end{description}
  3920. \end{tcolorbox}
  3921. %\end{wrapfigure}
  3922. \caption{The \code{set} data structure.}
  3923. \label{fig:set}
  3924. \end{figure}
  3925. \fi}
  3926. The live locations after an instruction are always the same as the
  3927. live locations before the next instruction.
  3928. \index{subject}{live-after} \index{subject}{live-before}
  3929. \begin{equation} \label{eq:live-after-before-next}
  3930. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3931. \end{equation}
  3932. To start things off, there are no live locations after the last
  3933. instruction, so
  3934. \begin{equation}\label{eq:live-last-empty}
  3935. L_{\mathsf{after}}(n) = \emptyset
  3936. \end{equation}
  3937. We then apply the following rule repeatedly, traversing the
  3938. instruction sequence back to front.
  3939. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3940. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3941. \end{equation}
  3942. where $W(k)$ are the locations written to by instruction $I_k$ and
  3943. $R(k)$ are the locations read by instruction $I_k$.
  3944. {\if\edition\racketEd
  3945. There is a special case for \code{jmp} instructions. The locations
  3946. that are live before a \code{jmp} should be the locations in
  3947. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3948. maintaining an alist named \code{label->live} that maps each label to
  3949. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3950. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3951. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3952. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3953. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3954. \fi}
  3955. Let us walk through the above example, applying these formulas
  3956. starting with the instruction on line 5. We collect the answers in
  3957. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3958. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3959. instruction (formula~\ref{eq:live-last-empty}). The
  3960. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3961. because it reads from variables \code{b} and \code{c}
  3962. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3963. \[
  3964. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3965. \]
  3966. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3967. the live-before set from line 5 to be the live-after set for this
  3968. instruction (formula~\ref{eq:live-after-before-next}).
  3969. \[
  3970. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3971. \]
  3972. This move instruction writes to \code{b} and does not read from any
  3973. variables, so we have the following live-before set
  3974. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3975. \[
  3976. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3977. \]
  3978. The live-before for instruction \code{movq a, c}
  3979. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3980. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3981. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3982. variable that is not live and does not read from a variable.
  3983. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3984. because it writes to variable \code{a}.
  3985. \begin{figure}[tbp]
  3986. \begin{minipage}{0.45\textwidth}
  3987. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3988. movq $5, a
  3989. movq $30, b
  3990. movq a, c
  3991. movq $10, b
  3992. addq b, c
  3993. \end{lstlisting}
  3994. \end{minipage}
  3995. \vrule\hspace{10pt}
  3996. \begin{minipage}{0.45\textwidth}
  3997. \begin{align*}
  3998. L_{\mathsf{before}}(1)= \emptyset,
  3999. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4000. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4001. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4002. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4003. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4004. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4005. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4006. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4007. L_{\mathsf{after}}(5)= \emptyset
  4008. \end{align*}
  4009. \end{minipage}
  4010. \caption{Example output of liveness analysis on a short example.}
  4011. \label{fig:liveness-example-0}
  4012. \end{figure}
  4013. \begin{exercise}\normalfont
  4014. Perform liveness analysis on the running example in
  4015. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4016. sets for each instruction. Compare your answers to the solution
  4017. shown in Figure~\ref{fig:live-eg}.
  4018. \end{exercise}
  4019. \begin{figure}[tp]
  4020. \hspace{20pt}
  4021. \begin{minipage}{0.45\textwidth}
  4022. {\if\edition\racketEd
  4023. \begin{lstlisting}
  4024. |$\{\ttm{rsp}\}$|
  4025. movq $1, v
  4026. |$\{\ttm{v},\ttm{rsp}\}$|
  4027. movq $42, w
  4028. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4029. movq v, x
  4030. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4031. addq $7, x
  4032. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4033. movq x, y
  4034. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4035. movq x, z
  4036. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4037. addq w, z
  4038. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4039. movq y, t
  4040. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4041. negq t
  4042. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4043. movq z, %rax
  4044. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4045. addq t, %rax
  4046. |$\{\ttm{rax},\ttm{rsp}\}$|
  4047. jmp conclusion
  4048. \end{lstlisting}
  4049. \fi}
  4050. {\if\edition\pythonEd
  4051. \begin{lstlisting}
  4052. movq $1, v
  4053. |$\{\ttm{v}\}$|
  4054. movq $42, w
  4055. |$\{\ttm{w}, \ttm{v}\}$|
  4056. movq v, x
  4057. |$\{\ttm{w}, \ttm{x}\}$|
  4058. addq $7, x
  4059. |$\{\ttm{w}, \ttm{x}\}$|
  4060. movq x, y
  4061. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4062. movq x, z
  4063. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4064. addq w, z
  4065. |$\{\ttm{y}, \ttm{z}\}$|
  4066. movq y, tmp_0
  4067. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4068. negq tmp_0
  4069. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4070. movq z, tmp_1
  4071. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4072. addq tmp_0, tmp_1
  4073. |$\{\ttm{tmp\_1}\}$|
  4074. movq tmp_1, %rdi
  4075. |$\{\ttm{rdi}\}$|
  4076. callq print_int
  4077. |$\{\}$|
  4078. \end{lstlisting}
  4079. \fi}
  4080. \end{minipage}
  4081. \caption{The running example annotated with live-after sets.}
  4082. \label{fig:live-eg}
  4083. \end{figure}
  4084. \begin{exercise}\normalfont
  4085. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4086. %
  4087. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4088. field of the \code{Block} structure.}
  4089. %
  4090. \python{Return a dictionary that maps each instruction to its
  4091. live-after set.}
  4092. %
  4093. \racket{We recommend creating an auxiliary function that takes a list
  4094. of instructions and an initial live-after set (typically empty) and
  4095. returns the list of live-after sets.}
  4096. %
  4097. We recommend creating auxiliary functions to 1) compute the set
  4098. of locations that appear in an \Arg{}, 2) compute the locations read
  4099. by an instruction (the $R$ function), and 3) the locations written by
  4100. an instruction (the $W$ function). The \code{callq} instruction should
  4101. include all of the caller-saved registers in its write-set $W$ because
  4102. the calling convention says that those registers may be written to
  4103. during the function call. Likewise, the \code{callq} instruction
  4104. should include the appropriate argument-passing registers in its
  4105. read-set $R$, depending on the arity of the function being
  4106. called. (This is why the abstract syntax for \code{callq} includes the
  4107. arity.)
  4108. \end{exercise}
  4109. %\clearpage
  4110. \section{Build the Interference Graph}
  4111. \label{sec:build-interference}
  4112. {\if\edition\racketEd
  4113. \begin{figure}[tp]
  4114. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4115. \small
  4116. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4117. A \emph{graph} is a collection of vertices and edges where each
  4118. edge connects two vertices. A graph is \emph{directed} if each
  4119. edge points from a source to a target. Otherwise the graph is
  4120. \emph{undirected}.
  4121. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4122. \begin{description}
  4123. %% We currently don't use directed graphs. We instead use
  4124. %% directed multi-graphs. -Jeremy
  4125. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4126. directed graph from a list of edges. Each edge is a list
  4127. containing the source and target vertex.
  4128. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4129. undirected graph from a list of edges. Each edge is represented by
  4130. a list containing two vertices.
  4131. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4132. inserts a vertex into the graph.
  4133. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4134. inserts an edge between the two vertices.
  4135. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4136. returns a sequence of vertices adjacent to the vertex.
  4137. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4138. returns a sequence of all vertices in the graph.
  4139. \end{description}
  4140. \end{tcolorbox}
  4141. %\end{wrapfigure}
  4142. \caption{The Racket \code{graph} package.}
  4143. \label{fig:graph}
  4144. \end{figure}
  4145. \fi}
  4146. Based on the liveness analysis, we know where each location is live.
  4147. However, during register allocation, we need to answer questions of
  4148. the specific form: are locations $u$ and $v$ live at the same time?
  4149. (And therefore cannot be assigned to the same register.) To make this
  4150. question more efficient to answer, we create an explicit data
  4151. structure, an \emph{interference graph}\index{subject}{interference
  4152. graph}. An interference graph is an undirected graph that has an
  4153. edge between two locations if they are live at the same time, that is,
  4154. if they interfere with each other.
  4155. %
  4156. \racket{We recommend using the Racket \code{graph} package
  4157. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4158. %
  4159. \python{We provide implementations of directed and undirected graph
  4160. data structures in the file \code{graph.py} of the support code.}
  4161. A straightforward way to compute the interference graph is to look at
  4162. the set of live locations between each instruction and add an edge to
  4163. the graph for every pair of variables in the same set. This approach
  4164. is less than ideal for two reasons. First, it can be expensive because
  4165. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4166. locations. Second, in the special case where two locations hold the
  4167. same value (because one was assigned to the other), they can be live
  4168. at the same time without interfering with each other.
  4169. A better way to compute the interference graph is to focus on
  4170. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4171. must not overwrite something in a live location. So for each
  4172. instruction, we create an edge between the locations being written to
  4173. and the live locations. (Except that one should not create self
  4174. edges.) Note that for the \key{callq} instruction, we consider all of
  4175. the caller-saved registers as being written to, so an edge is added
  4176. between every live variable and every caller-saved register. Also, for
  4177. \key{movq} there is the above-mentioned special case to deal with. If
  4178. a live variable $v$ is the same as the source of the \key{movq}, then
  4179. there is no need to add an edge between $v$ and the destination,
  4180. because they both hold the same value.
  4181. %
  4182. So we have the following two rules.
  4183. \begin{enumerate}
  4184. \item If instruction $I_k$ is a move instruction of the form
  4185. \key{movq} $s$\key{,} $d$, then for every $v \in
  4186. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4187. $(d,v)$.
  4188. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4189. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4190. $(d,v)$.
  4191. \end{enumerate}
  4192. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4193. the above rules to each instruction. We highlight a few of the
  4194. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4195. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4196. so \code{v} interferes with \code{rsp}.}
  4197. %
  4198. \python{The first instruction is \lstinline{movq $1, v} and the
  4199. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4200. no interference because $\ttm{v}$ is the destination of the move.}
  4201. %
  4202. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4203. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4204. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4205. %
  4206. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4207. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4208. $\ttm{x}$ interferes with \ttm{w}.}
  4209. %
  4210. \racket{The next instruction is \lstinline{movq x, y} and the
  4211. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4212. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4213. \ttm{x} because \ttm{x} is the source of the move and therefore
  4214. \ttm{x} and \ttm{y} hold the same value.}
  4215. %
  4216. \python{The next instruction is \lstinline{movq x, y} and the
  4217. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4218. applies, so \ttm{y} interferes with \ttm{w} but not
  4219. \ttm{x} because \ttm{x} is the source of the move and therefore
  4220. \ttm{x} and \ttm{y} hold the same value.}
  4221. %
  4222. Figure~\ref{fig:interference-results} lists the interference results
  4223. for all of the instructions and the resulting interference graph is
  4224. shown in Figure~\ref{fig:interfere}.
  4225. \begin{figure}[tbp]
  4226. \begin{quote}
  4227. {\if\edition\racketEd
  4228. \begin{tabular}{ll}
  4229. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4230. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4231. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4232. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4233. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4234. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4235. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4236. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4237. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4238. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4239. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4240. \lstinline!jmp conclusion!& no interference.
  4241. \end{tabular}
  4242. \fi}
  4243. {\if\edition\pythonEd
  4244. \begin{tabular}{ll}
  4245. \lstinline!movq $1, v!& no interference\\
  4246. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4247. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4248. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4249. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4250. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4251. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4252. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4253. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4254. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4255. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4256. \lstinline!movq tmp_1, %rdi! & no interference \\
  4257. \lstinline!callq print_int!& no interference.
  4258. \end{tabular}
  4259. \fi}
  4260. \end{quote}
  4261. \caption{Interference results for the running example.}
  4262. \label{fig:interference-results}
  4263. \end{figure}
  4264. \begin{figure}[tbp]
  4265. \large
  4266. {\if\edition\racketEd
  4267. \[
  4268. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4269. \node (rax) at (0,0) {$\ttm{rax}$};
  4270. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4271. \node (t1) at (0,2) {$\ttm{t}$};
  4272. \node (z) at (3,2) {$\ttm{z}$};
  4273. \node (x) at (6,2) {$\ttm{x}$};
  4274. \node (y) at (3,0) {$\ttm{y}$};
  4275. \node (w) at (6,0) {$\ttm{w}$};
  4276. \node (v) at (9,0) {$\ttm{v}$};
  4277. \draw (t1) to (rax);
  4278. \draw (t1) to (z);
  4279. \draw (z) to (y);
  4280. \draw (z) to (w);
  4281. \draw (x) to (w);
  4282. \draw (y) to (w);
  4283. \draw (v) to (w);
  4284. \draw (v) to (rsp);
  4285. \draw (w) to (rsp);
  4286. \draw (x) to (rsp);
  4287. \draw (y) to (rsp);
  4288. \path[-.,bend left=15] (z) edge node {} (rsp);
  4289. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4290. \draw (rax) to (rsp);
  4291. \end{tikzpicture}
  4292. \]
  4293. \fi}
  4294. {\if\edition\pythonEd
  4295. \[
  4296. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4297. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4298. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4299. \node (z) at (3,2) {$\ttm{z}$};
  4300. \node (x) at (6,2) {$\ttm{x}$};
  4301. \node (y) at (3,0) {$\ttm{y}$};
  4302. \node (w) at (6,0) {$\ttm{w}$};
  4303. \node (v) at (9,0) {$\ttm{v}$};
  4304. \draw (t0) to (t1);
  4305. \draw (t0) to (z);
  4306. \draw (z) to (y);
  4307. \draw (z) to (w);
  4308. \draw (x) to (w);
  4309. \draw (y) to (w);
  4310. \draw (v) to (w);
  4311. \end{tikzpicture}
  4312. \]
  4313. \fi}
  4314. \caption{The interference graph of the example program.}
  4315. \label{fig:interfere}
  4316. \end{figure}
  4317. %% Our next concern is to choose a data structure for representing the
  4318. %% interference graph. There are many choices for how to represent a
  4319. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4320. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4321. %% data structure is to study the algorithm that uses the data structure,
  4322. %% determine what operations need to be performed, and then choose the
  4323. %% data structure that provide the most efficient implementations of
  4324. %% those operations. Often times the choice of data structure can have an
  4325. %% effect on the time complexity of the algorithm, as it does here. If
  4326. %% you skim the next section, you will see that the register allocation
  4327. %% algorithm needs to ask the graph for all of its vertices and, given a
  4328. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4329. %% correct choice of graph representation is that of an adjacency
  4330. %% list. There are helper functions in \code{utilities.rkt} for
  4331. %% representing graphs using the adjacency list representation:
  4332. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4333. %% (Appendix~\ref{appendix:utilities}).
  4334. %% %
  4335. %% \margincomment{\footnotesize To do: change to use the
  4336. %% Racket graph library. \\ --Jeremy}
  4337. %% %
  4338. %% In particular, those functions use a hash table to map each vertex to
  4339. %% the set of adjacent vertices, and the sets are represented using
  4340. %% Racket's \key{set}, which is also a hash table.
  4341. \begin{exercise}\normalfont
  4342. \racket{Implement the compiler pass named \code{build\_interference} according
  4343. to the algorithm suggested above. We recommend using the Racket
  4344. \code{graph} package to create and inspect the interference graph.
  4345. The output graph of this pass should be stored in the $\itm{info}$ field of
  4346. the program, under the key \code{conflicts}.}
  4347. %
  4348. \python{Implement a function named \code{build\_interference}
  4349. according to the algorithm suggested above that
  4350. returns the interference graph.}
  4351. \end{exercise}
  4352. \section{Graph Coloring via Sudoku}
  4353. \label{sec:graph-coloring}
  4354. \index{subject}{graph coloring}
  4355. \index{subject}{Sudoku}
  4356. \index{subject}{color}
  4357. We come to the main event, mapping variables to registers and stack
  4358. locations. Variables that interfere with each other must be mapped to
  4359. different locations. In terms of the interference graph, this means
  4360. that adjacent vertices must be mapped to different locations. If we
  4361. think of locations as colors, the register allocation problem becomes
  4362. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4363. The reader may be more familiar with the graph coloring problem than he
  4364. or she realizes; the popular game of Sudoku is an instance of the
  4365. graph coloring problem. The following describes how to build a graph
  4366. out of an initial Sudoku board.
  4367. \begin{itemize}
  4368. \item There is one vertex in the graph for each Sudoku square.
  4369. \item There is an edge between two vertices if the corresponding squares
  4370. are in the same row, in the same column, or if the squares are in
  4371. the same $3\times 3$ region.
  4372. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4373. \item Based on the initial assignment of numbers to squares in the
  4374. Sudoku board, assign the corresponding colors to the corresponding
  4375. vertices in the graph.
  4376. \end{itemize}
  4377. If you can color the remaining vertices in the graph with the nine
  4378. colors, then you have also solved the corresponding game of Sudoku.
  4379. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4380. the corresponding graph with colored vertices. We map the Sudoku
  4381. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4382. sampling of the vertices (the colored ones) because showing edges for
  4383. all of the vertices would make the graph unreadable.
  4384. \begin{figure}[tbp]
  4385. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4386. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4387. \caption{A Sudoku game board and the corresponding colored graph.}
  4388. \label{fig:sudoku-graph}
  4389. \end{figure}
  4390. Some techniques for playing Sudoku correspond to heuristics used in
  4391. graph coloring algorithms. For example, one of the basic techniques
  4392. for Sudoku is called Pencil Marks. The idea is to use a process of
  4393. elimination to determine what numbers are no longer available for a
  4394. square and write down those numbers in the square (writing very
  4395. small). For example, if the number $1$ is assigned to a square, then
  4396. write the pencil mark $1$ in all the squares in the same row, column,
  4397. and region to indicate that $1$ is no longer an option for those other
  4398. squares.
  4399. %
  4400. The Pencil Marks technique corresponds to the notion of
  4401. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4402. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4403. are no longer available. In graph terminology, we have the following
  4404. definition:
  4405. \begin{equation*}
  4406. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4407. \text{ and } \mathrm{color}(v) = c \}
  4408. \end{equation*}
  4409. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4410. edge with $u$.
  4411. The Pencil Marks technique leads to a simple strategy for filling in
  4412. numbers: if there is a square with only one possible number left, then
  4413. choose that number! But what if there are no squares with only one
  4414. possibility left? One brute-force approach is to try them all: choose
  4415. the first one and if that ultimately leads to a solution, great. If
  4416. not, backtrack and choose the next possibility. One good thing about
  4417. Pencil Marks is that it reduces the degree of branching in the search
  4418. tree. Nevertheless, backtracking can be terribly time consuming. One
  4419. way to reduce the amount of backtracking is to use the
  4420. most-constrained-first heuristic (aka. minimum remaining
  4421. values)~\citep{Russell2003}. That is, when choosing a square, always
  4422. choose one with the fewest possibilities left (the vertex with the
  4423. highest saturation). The idea is that choosing highly constrained
  4424. squares earlier rather than later is better because later on there may
  4425. not be any possibilities left in the highly saturated squares.
  4426. However, register allocation is easier than Sudoku because the
  4427. register allocator can fall back to assigning variables to stack
  4428. locations when the registers run out. Thus, it makes sense to replace
  4429. backtracking with greedy search: make the best choice at the time and
  4430. keep going. We still wish to minimize the number of colors needed, so
  4431. we use the most-constrained-first heuristic in the greedy search.
  4432. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4433. algorithm for register allocation based on saturation and the
  4434. most-constrained-first heuristic. It is roughly equivalent to the
  4435. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4436. %,Gebremedhin:1999fk,Omari:2006uq
  4437. Just as in Sudoku, the algorithm represents colors with integers. The
  4438. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4439. for register allocation. The integers $k$ and larger correspond to
  4440. stack locations. The registers that are not used for register
  4441. allocation, such as \code{rax}, are assigned to negative integers. In
  4442. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4443. %% One might wonder why we include registers at all in the liveness
  4444. %% analysis and interference graph. For example, we never allocate a
  4445. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4446. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4447. %% to use register for passing arguments to functions, it will be
  4448. %% necessary for those registers to appear in the interference graph
  4449. %% because those registers will also be assigned to variables, and we
  4450. %% don't want those two uses to encroach on each other. Regarding
  4451. %% registers such as \code{rax} and \code{rsp} that are not used for
  4452. %% variables, we could omit them from the interference graph but that
  4453. %% would require adding special cases to our algorithm, which would
  4454. %% complicate the logic for little gain.
  4455. \begin{figure}[btp]
  4456. \centering
  4457. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4458. Algorithm: DSATUR
  4459. Input: a graph |$G$|
  4460. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4461. |$W \gets \mathrm{vertices}(G)$|
  4462. while |$W \neq \emptyset$| do
  4463. pick a vertex |$u$| from |$W$| with the highest saturation,
  4464. breaking ties randomly
  4465. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4466. |$\mathrm{color}[u] \gets c$|
  4467. |$W \gets W - \{u\}$|
  4468. \end{lstlisting}
  4469. \caption{The saturation-based greedy graph coloring algorithm.}
  4470. \label{fig:satur-algo}
  4471. \end{figure}
  4472. {\if\edition\racketEd
  4473. With the DSATUR algorithm in hand, let us return to the running
  4474. example and consider how to color the interference graph in
  4475. Figure~\ref{fig:interfere}.
  4476. %
  4477. We start by assigning the register nodes to their own color. For
  4478. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4479. assigned $-2$. The variables are not yet colored, so they are
  4480. annotated with a dash. We then update the saturation for vertices that
  4481. are adjacent to a register, obtaining the following annotated
  4482. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4483. it interferes with both \code{rax} and \code{rsp}.
  4484. \[
  4485. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4486. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4487. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4488. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4489. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4490. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4491. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4492. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4493. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4494. \draw (t1) to (rax);
  4495. \draw (t1) to (z);
  4496. \draw (z) to (y);
  4497. \draw (z) to (w);
  4498. \draw (x) to (w);
  4499. \draw (y) to (w);
  4500. \draw (v) to (w);
  4501. \draw (v) to (rsp);
  4502. \draw (w) to (rsp);
  4503. \draw (x) to (rsp);
  4504. \draw (y) to (rsp);
  4505. \path[-.,bend left=15] (z) edge node {} (rsp);
  4506. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4507. \draw (rax) to (rsp);
  4508. \end{tikzpicture}
  4509. \]
  4510. The algorithm says to select a maximally saturated vertex. So we pick
  4511. $\ttm{t}$ and color it with the first available integer, which is
  4512. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4513. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4514. \[
  4515. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4516. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4517. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4518. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4519. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4520. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4521. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4522. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4523. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4524. \draw (t1) to (rax);
  4525. \draw (t1) to (z);
  4526. \draw (z) to (y);
  4527. \draw (z) to (w);
  4528. \draw (x) to (w);
  4529. \draw (y) to (w);
  4530. \draw (v) to (w);
  4531. \draw (v) to (rsp);
  4532. \draw (w) to (rsp);
  4533. \draw (x) to (rsp);
  4534. \draw (y) to (rsp);
  4535. \path[-.,bend left=15] (z) edge node {} (rsp);
  4536. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4537. \draw (rax) to (rsp);
  4538. \end{tikzpicture}
  4539. \]
  4540. We repeat the process, selecting a maximally saturated vertex,
  4541. choosing is \code{z}, and color it with the first available number, which
  4542. is $1$. We add $1$ to the saturation for the neighboring vertices
  4543. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4544. \[
  4545. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4546. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4547. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4548. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4549. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4550. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4551. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4552. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4553. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4554. \draw (t1) to (rax);
  4555. \draw (t1) to (z);
  4556. \draw (z) to (y);
  4557. \draw (z) to (w);
  4558. \draw (x) to (w);
  4559. \draw (y) to (w);
  4560. \draw (v) to (w);
  4561. \draw (v) to (rsp);
  4562. \draw (w) to (rsp);
  4563. \draw (x) to (rsp);
  4564. \draw (y) to (rsp);
  4565. \path[-.,bend left=15] (z) edge node {} (rsp);
  4566. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4567. \draw (rax) to (rsp);
  4568. \end{tikzpicture}
  4569. \]
  4570. The most saturated vertices are now \code{w} and \code{y}. We color
  4571. \code{w} with the first available color, which is $0$.
  4572. \[
  4573. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4574. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4575. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4576. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4577. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4578. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4579. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4580. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4581. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4582. \draw (t1) to (rax);
  4583. \draw (t1) to (z);
  4584. \draw (z) to (y);
  4585. \draw (z) to (w);
  4586. \draw (x) to (w);
  4587. \draw (y) to (w);
  4588. \draw (v) to (w);
  4589. \draw (v) to (rsp);
  4590. \draw (w) to (rsp);
  4591. \draw (x) to (rsp);
  4592. \draw (y) to (rsp);
  4593. \path[-.,bend left=15] (z) edge node {} (rsp);
  4594. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4595. \draw (rax) to (rsp);
  4596. \end{tikzpicture}
  4597. \]
  4598. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4599. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4600. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4601. and \code{z}, whose colors are $0$ and $1$ respectively.
  4602. \[
  4603. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4604. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4605. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4606. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4607. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4608. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4609. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4610. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4611. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4612. \draw (t1) to (rax);
  4613. \draw (t1) to (z);
  4614. \draw (z) to (y);
  4615. \draw (z) to (w);
  4616. \draw (x) to (w);
  4617. \draw (y) to (w);
  4618. \draw (v) to (w);
  4619. \draw (v) to (rsp);
  4620. \draw (w) to (rsp);
  4621. \draw (x) to (rsp);
  4622. \draw (y) to (rsp);
  4623. \path[-.,bend left=15] (z) edge node {} (rsp);
  4624. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4625. \draw (rax) to (rsp);
  4626. \end{tikzpicture}
  4627. \]
  4628. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4629. \[
  4630. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4631. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4632. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4633. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4634. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4635. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4636. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4637. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4638. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4639. \draw (t1) to (rax);
  4640. \draw (t1) to (z);
  4641. \draw (z) to (y);
  4642. \draw (z) to (w);
  4643. \draw (x) to (w);
  4644. \draw (y) to (w);
  4645. \draw (v) to (w);
  4646. \draw (v) to (rsp);
  4647. \draw (w) to (rsp);
  4648. \draw (x) to (rsp);
  4649. \draw (y) to (rsp);
  4650. \path[-.,bend left=15] (z) edge node {} (rsp);
  4651. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4652. \draw (rax) to (rsp);
  4653. \end{tikzpicture}
  4654. \]
  4655. In the last step of the algorithm, we color \code{x} with $1$.
  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,2\}$};
  4660. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4661. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4662. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4663. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4664. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4665. \node (v) at (10,0) {$\ttm{v}:1,\{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. So we obtain the following coloring:
  4683. \[
  4684. \{
  4685. \ttm{rax} \mapsto -1,
  4686. \ttm{rsp} \mapsto -2,
  4687. \ttm{t} \mapsto 0,
  4688. \ttm{z} \mapsto 1,
  4689. \ttm{x} \mapsto 1,
  4690. \ttm{y} \mapsto 2,
  4691. \ttm{w} \mapsto 0,
  4692. \ttm{v} \mapsto 1
  4693. \}
  4694. \]
  4695. \fi}
  4696. %
  4697. {\if\edition\pythonEd
  4698. %
  4699. With the DSATUR algorithm in hand, let us return to the running
  4700. example and consider how to color the interference graph in
  4701. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4702. to indicate that it has not yet been assigned a color. The saturation
  4703. sets are also shown for each node; all of them start as the empty set.
  4704. (We do not include the register nodes in the graph below because there
  4705. were no interference edges involving registers in this program, but in
  4706. general there can be.)
  4707. %
  4708. \[
  4709. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4710. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4711. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4712. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4713. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4714. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4715. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4716. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4717. \draw (t0) to (t1);
  4718. \draw (t0) to (z);
  4719. \draw (z) to (y);
  4720. \draw (z) to (w);
  4721. \draw (x) to (w);
  4722. \draw (y) to (w);
  4723. \draw (v) to (w);
  4724. \end{tikzpicture}
  4725. \]
  4726. The algorithm says to select a maximally saturated vertex, but they
  4727. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4728. then color it with the first available integer, which is $0$. We mark
  4729. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4730. they interfere with $\ttm{tmp\_0}$.
  4731. \[
  4732. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4733. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4734. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4735. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4736. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4737. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4738. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4739. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4740. \draw (t0) to (t1);
  4741. \draw (t0) to (z);
  4742. \draw (z) to (y);
  4743. \draw (z) to (w);
  4744. \draw (x) to (w);
  4745. \draw (y) to (w);
  4746. \draw (v) to (w);
  4747. \end{tikzpicture}
  4748. \]
  4749. We repeat the process. The most saturated vertices are \code{z} and
  4750. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4751. available number, which is $1$. We add $1$ to the saturation for the
  4752. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4753. \[
  4754. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4755. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4756. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4757. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4758. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4759. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4760. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4761. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4762. \draw (t0) to (t1);
  4763. \draw (t0) to (z);
  4764. \draw (z) to (y);
  4765. \draw (z) to (w);
  4766. \draw (x) to (w);
  4767. \draw (y) to (w);
  4768. \draw (v) to (w);
  4769. \end{tikzpicture}
  4770. \]
  4771. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4772. \code{y}. We color \code{w} with the first available color, which
  4773. is $0$.
  4774. \[
  4775. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4776. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4777. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4778. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4779. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4780. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4781. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4782. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4783. \draw (t0) to (t1);
  4784. \draw (t0) to (z);
  4785. \draw (z) to (y);
  4786. \draw (z) to (w);
  4787. \draw (x) to (w);
  4788. \draw (y) to (w);
  4789. \draw (v) to (w);
  4790. \end{tikzpicture}
  4791. \]
  4792. Now \code{y} is the most saturated, so we color it with $2$.
  4793. \[
  4794. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4795. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4796. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4797. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4798. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4799. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4800. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4801. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4802. \draw (t0) to (t1);
  4803. \draw (t0) to (z);
  4804. \draw (z) to (y);
  4805. \draw (z) to (w);
  4806. \draw (x) to (w);
  4807. \draw (y) to (w);
  4808. \draw (v) to (w);
  4809. \end{tikzpicture}
  4810. \]
  4811. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4812. We choose to color \code{v} with $1$.
  4813. \[
  4814. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4815. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4816. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4817. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4818. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4819. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4820. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4821. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4822. \draw (t0) to (t1);
  4823. \draw (t0) to (z);
  4824. \draw (z) to (y);
  4825. \draw (z) to (w);
  4826. \draw (x) to (w);
  4827. \draw (y) to (w);
  4828. \draw (v) to (w);
  4829. \end{tikzpicture}
  4830. \]
  4831. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4832. \[
  4833. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4834. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4835. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4836. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4837. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4838. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4839. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4840. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4841. \draw (t0) to (t1);
  4842. \draw (t0) to (z);
  4843. \draw (z) to (y);
  4844. \draw (z) to (w);
  4845. \draw (x) to (w);
  4846. \draw (y) to (w);
  4847. \draw (v) to (w);
  4848. \end{tikzpicture}
  4849. \]
  4850. So we obtain the following coloring:
  4851. \[
  4852. \{ \ttm{tmp\_0} \mapsto 0,
  4853. \ttm{tmp\_1} \mapsto 1,
  4854. \ttm{z} \mapsto 1,
  4855. \ttm{x} \mapsto 1,
  4856. \ttm{y} \mapsto 2,
  4857. \ttm{w} \mapsto 0,
  4858. \ttm{v} \mapsto 1 \}
  4859. \]
  4860. \fi}
  4861. We recommend creating an auxiliary function named \code{color\_graph}
  4862. that takes an interference graph and a list of all the variables in
  4863. the program. This function should return a mapping of variables to
  4864. their colors (represented as natural numbers). By creating this helper
  4865. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4866. when we add support for functions.
  4867. To prioritize the processing of highly saturated nodes inside the
  4868. \code{color\_graph} function, we recommend using the priority queue
  4869. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4870. addition, you will need to maintain a mapping from variables to their
  4871. ``handles'' in the priority queue so that you can notify the priority
  4872. queue when their saturation changes.}
  4873. {\if\edition\racketEd
  4874. \begin{figure}[tp]
  4875. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4876. \small
  4877. \begin{tcolorbox}[title=Priority Queue]
  4878. A \emph{priority queue} is a collection of items in which the
  4879. removal of items is governed by priority. In a ``min'' queue,
  4880. lower priority items are removed first. An implementation is in
  4881. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4882. queue} \index{subject}{minimum priority queue}
  4883. \begin{description}
  4884. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4885. priority queue that uses the $\itm{cmp}$ predicate to determine
  4886. whether its first argument has lower or equal priority to its
  4887. second argument.
  4888. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4889. items in the queue.
  4890. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4891. the item into the queue and returns a handle for the item in the
  4892. queue.
  4893. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4894. the lowest priority.
  4895. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4896. notifies the queue that the priority has decreased for the item
  4897. associated with the given handle.
  4898. \end{description}
  4899. \end{tcolorbox}
  4900. %\end{wrapfigure}
  4901. \caption{The priority queue data structure.}
  4902. \label{fig:priority-queue}
  4903. \end{figure}
  4904. \fi}
  4905. With the coloring complete, we finalize the assignment of variables to
  4906. registers and stack locations. We map the first $k$ colors to the $k$
  4907. registers and the rest of the colors to stack locations. Suppose for
  4908. the moment that we have just one register to use for register
  4909. allocation, \key{rcx}. Then we have the following map from colors to
  4910. locations.
  4911. \[
  4912. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4913. \]
  4914. Composing this mapping with the coloring, we arrive at the following
  4915. assignment of variables to locations.
  4916. {\if\edition\racketEd
  4917. \begin{gather*}
  4918. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4919. \ttm{w} \mapsto \key{\%rcx}, \,
  4920. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4921. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4922. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4923. \ttm{t} \mapsto \key{\%rcx} \}
  4924. \end{gather*}
  4925. \fi}
  4926. {\if\edition\pythonEd
  4927. \begin{gather*}
  4928. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4929. \ttm{w} \mapsto \key{\%rcx}, \,
  4930. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4931. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4932. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4933. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4934. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4935. \end{gather*}
  4936. \fi}
  4937. Adapt the code from the \code{assign\_homes} pass
  4938. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  4939. assigned location. Applying the above assignment to our running
  4940. example, on the left, yields the program on the right.
  4941. % why frame size of 32? -JGS
  4942. \begin{center}
  4943. {\if\edition\racketEd
  4944. \begin{minipage}{0.3\textwidth}
  4945. \begin{lstlisting}
  4946. movq $1, v
  4947. movq $42, w
  4948. movq v, x
  4949. addq $7, x
  4950. movq x, y
  4951. movq x, z
  4952. addq w, z
  4953. movq y, t
  4954. negq t
  4955. movq z, %rax
  4956. addq t, %rax
  4957. jmp conclusion
  4958. \end{lstlisting}
  4959. \end{minipage}
  4960. $\Rightarrow\qquad$
  4961. \begin{minipage}{0.45\textwidth}
  4962. \begin{lstlisting}
  4963. movq $1, -8(%rbp)
  4964. movq $42, %rcx
  4965. movq -8(%rbp), -8(%rbp)
  4966. addq $7, -8(%rbp)
  4967. movq -8(%rbp), -16(%rbp)
  4968. movq -8(%rbp), -8(%rbp)
  4969. addq %rcx, -8(%rbp)
  4970. movq -16(%rbp), %rcx
  4971. negq %rcx
  4972. movq -8(%rbp), %rax
  4973. addq %rcx, %rax
  4974. jmp conclusion
  4975. \end{lstlisting}
  4976. \end{minipage}
  4977. \fi}
  4978. {\if\edition\pythonEd
  4979. \begin{minipage}{0.3\textwidth}
  4980. \begin{lstlisting}
  4981. movq $1, v
  4982. movq $42, w
  4983. movq v, x
  4984. addq $7, x
  4985. movq x, y
  4986. movq x, z
  4987. addq w, z
  4988. movq y, tmp_0
  4989. negq tmp_0
  4990. movq z, tmp_1
  4991. addq tmp_0, tmp_1
  4992. movq tmp_1, %rdi
  4993. callq print_int
  4994. \end{lstlisting}
  4995. \end{minipage}
  4996. $\Rightarrow\qquad$
  4997. \begin{minipage}{0.45\textwidth}
  4998. \begin{lstlisting}
  4999. movq $1, -8(%rbp)
  5000. movq $42, %rcx
  5001. movq -8(%rbp), -8(%rbp)
  5002. addq $7, -8(%rbp)
  5003. movq -8(%rbp), -16(%rbp)
  5004. movq -8(%rbp), -8(%rbp)
  5005. addq %rcx, -8(%rbp)
  5006. movq -16(%rbp), %rcx
  5007. negq %rcx
  5008. movq -8(%rbp), -8(%rbp)
  5009. addq %rcx, -8(%rbp)
  5010. movq -8(%rbp), %rdi
  5011. callq print_int
  5012. \end{lstlisting}
  5013. \end{minipage}
  5014. \fi}
  5015. \end{center}
  5016. \begin{exercise}\normalfont
  5017. %
  5018. Implement the compiler pass \code{allocate\_registers}.
  5019. %
  5020. Create five programs that exercise all aspects of the register
  5021. allocation algorithm, including spilling variables to the stack.
  5022. %
  5023. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  5024. \code{run-tests.rkt} script with the three new passes:
  5025. \code{uncover\_live}, \code{build\_interference}, and
  5026. \code{allocate\_registers}.
  5027. %
  5028. Temporarily remove the \code{print\_x86} pass from the list of passes
  5029. and the call to \code{compiler-tests}.
  5030. Run the script to test the register allocator.
  5031. }
  5032. %
  5033. \python{Run the \code{run-tests.py} script to to check whether the
  5034. output programs produce the same result as the input programs.}
  5035. \end{exercise}
  5036. \section{Patch Instructions}
  5037. \label{sec:patch-instructions}
  5038. The remaining step in the compilation to x86 is to ensure that the
  5039. instructions have at most one argument that is a memory access.
  5040. %
  5041. In the running example, the instruction \code{movq -8(\%rbp),
  5042. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5043. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5044. then move \code{rax} into \code{-16(\%rbp)}.
  5045. %
  5046. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5047. problematic, but they can simply be deleted. In general, we recommend
  5048. deleting all the trivial moves whose source and destination are the
  5049. same location.
  5050. %
  5051. The following is the output of \code{patch\_instructions} on the
  5052. running example.
  5053. \begin{center}
  5054. {\if\edition\racketEd
  5055. \begin{minipage}{0.4\textwidth}
  5056. \begin{lstlisting}
  5057. movq $1, -8(%rbp)
  5058. movq $42, %rcx
  5059. movq -8(%rbp), -8(%rbp)
  5060. addq $7, -8(%rbp)
  5061. movq -8(%rbp), -16(%rbp)
  5062. movq -8(%rbp), -8(%rbp)
  5063. addq %rcx, -8(%rbp)
  5064. movq -16(%rbp), %rcx
  5065. negq %rcx
  5066. movq -8(%rbp), %rax
  5067. addq %rcx, %rax
  5068. jmp conclusion
  5069. \end{lstlisting}
  5070. \end{minipage}
  5071. $\Rightarrow\qquad$
  5072. \begin{minipage}{0.45\textwidth}
  5073. \begin{lstlisting}
  5074. movq $1, -8(%rbp)
  5075. movq $42, %rcx
  5076. addq $7, -8(%rbp)
  5077. movq -8(%rbp), %rax
  5078. movq %rax, -16(%rbp)
  5079. addq %rcx, -8(%rbp)
  5080. movq -16(%rbp), %rcx
  5081. negq %rcx
  5082. movq -8(%rbp), %rax
  5083. addq %rcx, %rax
  5084. jmp conclusion
  5085. \end{lstlisting}
  5086. \end{minipage}
  5087. \fi}
  5088. {\if\edition\pythonEd
  5089. \begin{minipage}{0.4\textwidth}
  5090. \begin{lstlisting}
  5091. movq $1, -8(%rbp)
  5092. movq $42, %rcx
  5093. movq -8(%rbp), -8(%rbp)
  5094. addq $7, -8(%rbp)
  5095. movq -8(%rbp), -16(%rbp)
  5096. movq -8(%rbp), -8(%rbp)
  5097. addq %rcx, -8(%rbp)
  5098. movq -16(%rbp), %rcx
  5099. negq %rcx
  5100. movq -8(%rbp), -8(%rbp)
  5101. addq %rcx, -8(%rbp)
  5102. movq -8(%rbp), %rdi
  5103. callq print_int
  5104. \end{lstlisting}
  5105. \end{minipage}
  5106. $\Rightarrow\qquad$
  5107. \begin{minipage}{0.45\textwidth}
  5108. \begin{lstlisting}
  5109. movq $1, -8(%rbp)
  5110. movq $42, %rcx
  5111. addq $7, -8(%rbp)
  5112. movq -8(%rbp), %rax
  5113. movq %rax, -16(%rbp)
  5114. addq %rcx, -8(%rbp)
  5115. movq -16(%rbp), %rcx
  5116. negq %rcx
  5117. addq %rcx, -8(%rbp)
  5118. movq -8(%rbp), %rdi
  5119. callq print_int
  5120. \end{lstlisting}
  5121. \end{minipage}
  5122. \fi}
  5123. \end{center}
  5124. \begin{exercise}\normalfont
  5125. %
  5126. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5127. %
  5128. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5129. %in the \code{run-tests.rkt} script.
  5130. %
  5131. Run the script to test the \code{patch\_instructions} pass.
  5132. \end{exercise}
  5133. \section{Prelude and Conclusion}
  5134. \label{sec:print-x86-reg-alloc}
  5135. \index{subject}{calling conventions}
  5136. \index{subject}{prelude}\index{subject}{conclusion}
  5137. Recall that this pass generates the prelude and conclusion
  5138. instructions to satisfy the x86 calling conventions
  5139. (Section~\ref{sec:calling-conventions}). With the addition of the
  5140. register allocator, the callee-saved registers used by the register
  5141. allocator must be saved in the prelude and restored in the conclusion.
  5142. In the \code{allocate\_registers} pass,
  5143. %
  5144. \racket{add an entry to the \itm{info}
  5145. of \code{X86Program} named \code{used\_callee}}
  5146. %
  5147. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5148. %
  5149. that stores the set of callee-saved registers that were assigned to
  5150. variables. The \code{prelude\_and\_conclusion} pass can then access
  5151. this information to decide which callee-saved registers need to be
  5152. saved and restored.
  5153. %
  5154. When calculating the size of the frame to adjust the \code{rsp} in the
  5155. prelude, make sure to take into account the space used for saving the
  5156. callee-saved registers. Also, don't forget that the frame needs to be
  5157. a multiple of 16 bytes!
  5158. \racket{An overview of all of the passes involved in register
  5159. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5160. {\if\edition\racketEd
  5161. \begin{figure}[tbp]
  5162. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5163. \node (Lvar) at (0,2) {\large \LangVar{}};
  5164. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5165. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5166. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5167. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5168. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5169. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5170. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5171. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5172. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5173. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5174. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5175. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5176. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5177. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5178. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5179. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5180. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5181. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5182. \end{tikzpicture}
  5183. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5184. \label{fig:reg-alloc-passes}
  5185. \end{figure}
  5186. \fi}
  5187. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5188. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5189. use of registers and the stack, we limit the register allocator for
  5190. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5191. the prelude\index{subject}{prelude} of the \code{main} function, we
  5192. push \code{rbx} onto the stack because it is a callee-saved register
  5193. and it was assigned to variable by the register allocator. We
  5194. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5195. reserve space for the one spilled variable. After that subtraction,
  5196. the \code{rsp} is aligned to 16 bytes.
  5197. Moving on to the program proper, we see how the registers were
  5198. allocated.
  5199. %
  5200. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5201. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5202. %
  5203. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5204. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5205. were assigned to \code{rbx}.}
  5206. %
  5207. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5208. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5209. callee-save register \code{rbx} onto the stack. The spilled variables
  5210. must be placed lower on the stack than the saved callee-save
  5211. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5212. \code{-16(\%rbp)}.
  5213. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5214. done in the prelude. We move the stack pointer up by \code{8} bytes
  5215. (the room for spilled variables), then we pop the old values of
  5216. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5217. \code{retq} to return control to the operating system.
  5218. \begin{figure}[tbp]
  5219. % var_test_28.rkt
  5220. % (use-minimal-set-of-registers! #t)
  5221. % and only rbx rcx
  5222. % tmp 0 rbx
  5223. % z 1 rcx
  5224. % y 0 rbx
  5225. % w 2 16(%rbp)
  5226. % v 0 rbx
  5227. % x 0 rbx
  5228. {\if\edition\racketEd
  5229. \begin{lstlisting}
  5230. start:
  5231. movq $1, %rbx
  5232. movq $42, -16(%rbp)
  5233. addq $7, %rbx
  5234. movq %rbx, %rcx
  5235. addq -16(%rbp), %rcx
  5236. negq %rbx
  5237. movq %rcx, %rax
  5238. addq %rbx, %rax
  5239. jmp conclusion
  5240. .globl main
  5241. main:
  5242. pushq %rbp
  5243. movq %rsp, %rbp
  5244. pushq %rbx
  5245. subq $8, %rsp
  5246. jmp start
  5247. conclusion:
  5248. addq $8, %rsp
  5249. popq %rbx
  5250. popq %rbp
  5251. retq
  5252. \end{lstlisting}
  5253. \fi}
  5254. {\if\edition\pythonEd
  5255. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5256. \begin{lstlisting}
  5257. .globl main
  5258. main:
  5259. pushq %rbp
  5260. movq %rsp, %rbp
  5261. pushq %rbx
  5262. subq $8, %rsp
  5263. movq $1, %rcx
  5264. movq $42, %rbx
  5265. addq $7, %rcx
  5266. movq %rcx, -16(%rbp)
  5267. addq %rbx, -16(%rbp)
  5268. negq %rcx
  5269. movq -16(%rbp), %rbx
  5270. addq %rcx, %rbx
  5271. movq %rbx, %rdi
  5272. callq print_int
  5273. addq $8, %rsp
  5274. popq %rbx
  5275. popq %rbp
  5276. retq
  5277. \end{lstlisting}
  5278. \fi}
  5279. \caption{The x86 output from the running example
  5280. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5281. and \code{rcx}.}
  5282. \label{fig:running-example-x86}
  5283. \end{figure}
  5284. \begin{exercise}\normalfont
  5285. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5286. %
  5287. \racket{
  5288. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5289. list of passes and the call to \code{compiler-tests}.}
  5290. %
  5291. Run the script to test the complete compiler for \LangVar{} that
  5292. performs register allocation.
  5293. \end{exercise}
  5294. \section{Challenge: Move Biasing}
  5295. \label{sec:move-biasing}
  5296. \index{subject}{move biasing}
  5297. This section describes an enhancement to the register allocator,
  5298. called move biasing, for students who are looking for an extra
  5299. challenge.
  5300. {\if\edition\racketEd
  5301. To motivate the need for move biasing we return to the running example
  5302. but this time use all of the general purpose registers. So we have
  5303. the following mapping of color numbers to registers.
  5304. \[
  5305. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5306. \]
  5307. Using the same assignment of variables to color numbers that was
  5308. produced by the register allocator described in the last section, we
  5309. get the following program.
  5310. \begin{center}
  5311. \begin{minipage}{0.3\textwidth}
  5312. \begin{lstlisting}
  5313. movq $1, v
  5314. movq $42, w
  5315. movq v, x
  5316. addq $7, x
  5317. movq x, y
  5318. movq x, z
  5319. addq w, z
  5320. movq y, t
  5321. negq t
  5322. movq z, %rax
  5323. addq t, %rax
  5324. jmp conclusion
  5325. \end{lstlisting}
  5326. \end{minipage}
  5327. $\Rightarrow\qquad$
  5328. \begin{minipage}{0.45\textwidth}
  5329. \begin{lstlisting}
  5330. movq $1, %rdx
  5331. movq $42, %rcx
  5332. movq %rdx, %rdx
  5333. addq $7, %rdx
  5334. movq %rdx, %rsi
  5335. movq %rdx, %rdx
  5336. addq %rcx, %rdx
  5337. movq %rsi, %rcx
  5338. negq %rcx
  5339. movq %rdx, %rax
  5340. addq %rcx, %rax
  5341. jmp conclusion
  5342. \end{lstlisting}
  5343. \end{minipage}
  5344. \end{center}
  5345. In the above output code there are two \key{movq} instructions that
  5346. can be removed because their source and target are the same. However,
  5347. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5348. register, we could instead remove three \key{movq} instructions. We
  5349. can accomplish this by taking into account which variables appear in
  5350. \key{movq} instructions with which other variables.
  5351. \fi}
  5352. {\if\edition\pythonEd
  5353. %
  5354. To motivate the need for move biasing we return to the running example
  5355. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5356. remove three trivial move instructions from the running
  5357. example. However, we could remove another trivial move if we were able
  5358. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5359. We say that two variables $p$ and $q$ are \emph{move
  5360. related}\index{subject}{move related} if they participate together in
  5361. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5362. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5363. when there are multiple variables with the same saturation, prefer
  5364. variables that can be assigned to a color that is the same as the
  5365. color of a move related variable. Furthermore, when the register
  5366. allocator chooses a color for a variable, it should prefer a color
  5367. that has already been used for a move-related variable (assuming that
  5368. they do not interfere). Of course, this preference should not override
  5369. the preference for registers over stack locations. So this preference
  5370. should be used as a tie breaker when choosing between registers or
  5371. when choosing between stack locations.
  5372. We recommend representing the move relationships in a graph, similar
  5373. to how we represented interference. The following is the \emph{move
  5374. graph} for our running example.
  5375. {\if\edition\racketEd
  5376. \[
  5377. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5378. \node (rax) at (0,0) {$\ttm{rax}$};
  5379. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5380. \node (t) at (0,2) {$\ttm{t}$};
  5381. \node (z) at (3,2) {$\ttm{z}$};
  5382. \node (x) at (6,2) {$\ttm{x}$};
  5383. \node (y) at (3,0) {$\ttm{y}$};
  5384. \node (w) at (6,0) {$\ttm{w}$};
  5385. \node (v) at (9,0) {$\ttm{v}$};
  5386. \draw (v) to (x);
  5387. \draw (x) to (y);
  5388. \draw (x) to (z);
  5389. \draw (y) to (t);
  5390. \end{tikzpicture}
  5391. \]
  5392. \fi}
  5393. %
  5394. {\if\edition\pythonEd
  5395. \[
  5396. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5397. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5398. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5399. \node (z) at (3,2) {$\ttm{z}$};
  5400. \node (x) at (6,2) {$\ttm{x}$};
  5401. \node (y) at (3,0) {$\ttm{y}$};
  5402. \node (w) at (6,0) {$\ttm{w}$};
  5403. \node (v) at (9,0) {$\ttm{v}$};
  5404. \draw (y) to (t0);
  5405. \draw (z) to (x);
  5406. \draw (z) to (t1);
  5407. \draw (x) to (y);
  5408. \draw (x) to (v);
  5409. \end{tikzpicture}
  5410. \]
  5411. \fi}
  5412. {\if\edition\racketEd
  5413. Now we replay the graph coloring, pausing to see the coloring of
  5414. \code{y}. Recall the following configuration. The most saturated vertices
  5415. were \code{w} and \code{y}.
  5416. \[
  5417. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5418. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5419. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5420. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5421. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5422. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5423. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5424. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5425. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5426. \draw (t1) to (rax);
  5427. \draw (t1) to (z);
  5428. \draw (z) to (y);
  5429. \draw (z) to (w);
  5430. \draw (x) to (w);
  5431. \draw (y) to (w);
  5432. \draw (v) to (w);
  5433. \draw (v) to (rsp);
  5434. \draw (w) to (rsp);
  5435. \draw (x) to (rsp);
  5436. \draw (y) to (rsp);
  5437. \path[-.,bend left=15] (z) edge node {} (rsp);
  5438. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5439. \draw (rax) to (rsp);
  5440. \end{tikzpicture}
  5441. \]
  5442. %
  5443. Last time we chose to color \code{w} with $0$. But this time we see
  5444. that \code{w} is not move related to any vertex, but \code{y} is move
  5445. related to \code{t}. So we choose to color \code{y} the same color as
  5446. \code{t}, $0$.
  5447. \[
  5448. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5449. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5450. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5451. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5452. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5453. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5454. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5455. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5456. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5457. \draw (t1) to (rax);
  5458. \draw (t1) to (z);
  5459. \draw (z) to (y);
  5460. \draw (z) to (w);
  5461. \draw (x) to (w);
  5462. \draw (y) to (w);
  5463. \draw (v) to (w);
  5464. \draw (v) to (rsp);
  5465. \draw (w) to (rsp);
  5466. \draw (x) to (rsp);
  5467. \draw (y) to (rsp);
  5468. \path[-.,bend left=15] (z) edge node {} (rsp);
  5469. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5470. \draw (rax) to (rsp);
  5471. \end{tikzpicture}
  5472. \]
  5473. Now \code{w} is the most saturated, so we color it $2$.
  5474. \[
  5475. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5476. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5477. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5478. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5479. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5480. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5481. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5482. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5483. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5484. \draw (t1) to (rax);
  5485. \draw (t1) to (z);
  5486. \draw (z) to (y);
  5487. \draw (z) to (w);
  5488. \draw (x) to (w);
  5489. \draw (y) to (w);
  5490. \draw (v) to (w);
  5491. \draw (v) to (rsp);
  5492. \draw (w) to (rsp);
  5493. \draw (x) to (rsp);
  5494. \draw (y) to (rsp);
  5495. \path[-.,bend left=15] (z) edge node {} (rsp);
  5496. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5497. \draw (rax) to (rsp);
  5498. \end{tikzpicture}
  5499. \]
  5500. At this point, vertices \code{x} and \code{v} are most saturated, but
  5501. \code{x} is move related to \code{y} and \code{z}, so we color
  5502. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5503. \[
  5504. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5505. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5506. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5507. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5508. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5509. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5510. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5511. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5512. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5513. \draw (t1) to (rax);
  5514. \draw (t) to (z);
  5515. \draw (z) to (y);
  5516. \draw (z) to (w);
  5517. \draw (x) to (w);
  5518. \draw (y) to (w);
  5519. \draw (v) to (w);
  5520. \draw (v) to (rsp);
  5521. \draw (w) to (rsp);
  5522. \draw (x) to (rsp);
  5523. \draw (y) to (rsp);
  5524. \path[-.,bend left=15] (z) edge node {} (rsp);
  5525. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5526. \draw (rax) to (rsp);
  5527. \end{tikzpicture}
  5528. \]
  5529. \fi}
  5530. %
  5531. {\if\edition\pythonEd
  5532. Now we replay the graph coloring, pausing before the coloring of
  5533. \code{w}. Recall the following configuration. The most saturated vertices
  5534. were \code{tmp\_1}, \code{w}, and \code{y}.
  5535. \[
  5536. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5537. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5538. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5539. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5540. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5541. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5542. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5543. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5544. \draw (t0) to (t1);
  5545. \draw (t0) to (z);
  5546. \draw (z) to (y);
  5547. \draw (z) to (w);
  5548. \draw (x) to (w);
  5549. \draw (y) to (w);
  5550. \draw (v) to (w);
  5551. \end{tikzpicture}
  5552. \]
  5553. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5554. or \code{y}, but note that \code{w} is not move related to any
  5555. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5556. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5557. \code{y} and color it $0$, we can delete another move instruction.
  5558. \[
  5559. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5560. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5561. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5562. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5563. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5564. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5565. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5566. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5567. \draw (t0) to (t1);
  5568. \draw (t0) to (z);
  5569. \draw (z) to (y);
  5570. \draw (z) to (w);
  5571. \draw (x) to (w);
  5572. \draw (y) to (w);
  5573. \draw (v) to (w);
  5574. \end{tikzpicture}
  5575. \]
  5576. Now \code{w} is the most saturated, so we color it $2$.
  5577. \[
  5578. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5579. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5580. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5581. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5582. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5583. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5584. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5585. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5586. \draw (t0) to (t1);
  5587. \draw (t0) to (z);
  5588. \draw (z) to (y);
  5589. \draw (z) to (w);
  5590. \draw (x) to (w);
  5591. \draw (y) to (w);
  5592. \draw (v) to (w);
  5593. \end{tikzpicture}
  5594. \]
  5595. To finish the coloring, \code{x} and \code{v} get $0$ and
  5596. \code{tmp\_1} gets $1$.
  5597. \[
  5598. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5599. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5600. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5601. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5602. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5603. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5604. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5605. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5606. \draw (t0) to (t1);
  5607. \draw (t0) to (z);
  5608. \draw (z) to (y);
  5609. \draw (z) to (w);
  5610. \draw (x) to (w);
  5611. \draw (y) to (w);
  5612. \draw (v) to (w);
  5613. \end{tikzpicture}
  5614. \]
  5615. \fi}
  5616. So we have the following assignment of variables to registers.
  5617. {\if\edition\racketEd
  5618. \begin{gather*}
  5619. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5620. \ttm{w} \mapsto \key{\%rsi}, \,
  5621. \ttm{x} \mapsto \key{\%rcx}, \,
  5622. \ttm{y} \mapsto \key{\%rcx}, \,
  5623. \ttm{z} \mapsto \key{\%rdx}, \,
  5624. \ttm{t} \mapsto \key{\%rcx} \}
  5625. \end{gather*}
  5626. \fi}
  5627. {\if\edition\pythonEd
  5628. \begin{gather*}
  5629. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5630. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5631. \ttm{x} \mapsto \key{\%rcx}, \,
  5632. \ttm{y} \mapsto \key{\%rcx}, \\
  5633. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5634. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5635. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5636. \end{gather*}
  5637. \fi}
  5638. We apply this register assignment to the running example, on the left,
  5639. to obtain the code in the middle. The \code{patch\_instructions} then
  5640. deletes the trivial moves to obtain the code on the right.
  5641. {\if\edition\racketEd
  5642. \begin{minipage}{0.25\textwidth}
  5643. \begin{lstlisting}
  5644. movq $1, v
  5645. movq $42, w
  5646. movq v, x
  5647. addq $7, x
  5648. movq x, y
  5649. movq x, z
  5650. addq w, z
  5651. movq y, t
  5652. negq t
  5653. movq z, %rax
  5654. addq t, %rax
  5655. jmp conclusion
  5656. \end{lstlisting}
  5657. \end{minipage}
  5658. $\Rightarrow\qquad$
  5659. \begin{minipage}{0.25\textwidth}
  5660. \begin{lstlisting}
  5661. movq $1, %rcx
  5662. movq $42, %rsi
  5663. movq %rcx, %rcx
  5664. addq $7, %rcx
  5665. movq %rcx, %rcx
  5666. movq %rcx, %rdx
  5667. addq %rsi, %rdx
  5668. movq %rcx, %rcx
  5669. negq %rcx
  5670. movq %rdx, %rax
  5671. addq %rcx, %rax
  5672. jmp conclusion
  5673. \end{lstlisting}
  5674. \end{minipage}
  5675. $\Rightarrow\qquad$
  5676. \begin{minipage}{0.25\textwidth}
  5677. \begin{lstlisting}
  5678. movq $1, %rcx
  5679. movq $42, %rsi
  5680. addq $7, %rcx
  5681. movq %rcx, %rdx
  5682. addq %rsi, %rdx
  5683. negq %rcx
  5684. movq %rdx, %rax
  5685. addq %rcx, %rax
  5686. jmp conclusion
  5687. \end{lstlisting}
  5688. \end{minipage}
  5689. \fi}
  5690. {\if\edition\pythonEd
  5691. \begin{minipage}{0.20\textwidth}
  5692. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5693. movq $1, v
  5694. movq $42, w
  5695. movq v, x
  5696. addq $7, x
  5697. movq x, y
  5698. movq x, z
  5699. addq w, z
  5700. movq y, tmp_0
  5701. negq tmp_0
  5702. movq z, tmp_1
  5703. addq tmp_0, tmp_1
  5704. movq tmp_1, %rdi
  5705. callq _print_int
  5706. \end{lstlisting}
  5707. \end{minipage}
  5708. ${\Rightarrow\qquad}$
  5709. \begin{minipage}{0.30\textwidth}
  5710. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5711. movq $1, %rcx
  5712. movq $42, -16(%rbp)
  5713. movq %rcx, %rcx
  5714. addq $7, %rcx
  5715. movq %rcx, %rcx
  5716. movq %rcx, -8(%rbp)
  5717. addq -16(%rbp), -8(%rbp)
  5718. movq %rcx, %rcx
  5719. negq %rcx
  5720. movq -8(%rbp), -8(%rbp)
  5721. addq %rcx, -8(%rbp)
  5722. movq -8(%rbp), %rdi
  5723. callq _print_int
  5724. \end{lstlisting}
  5725. \end{minipage}
  5726. ${\Rightarrow\qquad}$
  5727. \begin{minipage}{0.20\textwidth}
  5728. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5729. movq $1, %rcx
  5730. movq $42, -16(%rbp)
  5731. addq $7, %rcx
  5732. movq %rcx, -8(%rbp)
  5733. movq -16(%rbp), %rax
  5734. addq %rax, -8(%rbp)
  5735. negq %rcx
  5736. addq %rcx, -8(%rbp)
  5737. movq -8(%rbp), %rdi
  5738. callq print_int
  5739. \end{lstlisting}
  5740. \end{minipage}
  5741. \fi}
  5742. \begin{exercise}\normalfont
  5743. Change your implementation of \code{allocate\_registers} to take move
  5744. biasing into account. Create two new tests that include at least one
  5745. opportunity for move biasing and visually inspect the output x86
  5746. programs to make sure that your move biasing is working properly. Make
  5747. sure that your compiler still passes all of the tests.
  5748. \end{exercise}
  5749. %To do: another neat challenge would be to do
  5750. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5751. %% \subsection{Output of the Running Example}
  5752. %% \label{sec:reg-alloc-output}
  5753. % challenge: prioritize variables based on execution frequencies
  5754. % and the number of uses of a variable
  5755. % challenge: enhance the coloring algorithm using Chaitin's
  5756. % approach of prioritizing high-degree variables
  5757. % by removing low-degree variables (coloring them later)
  5758. % from the interference graph
  5759. \section{Further Reading}
  5760. \label{sec:register-allocation-further-reading}
  5761. Early register allocation algorithms were developed for Fortran
  5762. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5763. of graph coloring began in the late 1970s and early 1980s with the
  5764. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5765. algorithm is based on the following observation of
  5766. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5767. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5768. $v$ removed is also $k$ colorable. To see why, suppose that the
  5769. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5770. different colors, but since there are less than $k$ neighbors, there
  5771. will be one or more colors left over to use for coloring $v$ in $G$.
  5772. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5773. less than $k$ from the graph and recursively colors the rest of the
  5774. graph. Upon returning from the recursion, it colors $v$ with one of
  5775. the available colors and returns. \citet{Chaitin:1982vn} augments
  5776. this algorithm to handle spilling as follows. If there are no vertices
  5777. of degree lower than $k$ then pick a vertex at random, spill it,
  5778. remove it from the graph, and proceed recursively to color the rest of
  5779. the graph.
  5780. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5781. move-related and that don't interfere with each other, a process
  5782. called \emph{coalescing}. While coalescing decreases the number of
  5783. moves, it can make the graph more difficult to
  5784. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5785. which two variables are merged only if they have fewer than $k$
  5786. neighbors of high degree. \citet{George:1996aa} observe that
  5787. conservative coalescing is sometimes too conservative and make it more
  5788. aggressive by iterating the coalescing with the removal of low-degree
  5789. vertices.
  5790. %
  5791. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5792. also propose \emph{biased coloring} in which a variable is assigned to
  5793. the same color as another move-related variable if possible, as
  5794. discussed in Section~\ref{sec:move-biasing}.
  5795. %
  5796. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5797. performs coalescing, graph coloring, and spill code insertion until
  5798. all variables have been assigned a location.
  5799. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5800. spills variables that don't have to be: a high-degree variable can be
  5801. colorable if many of its neighbors are assigned the same color.
  5802. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5803. high-degree vertex is not immediately spilled. Instead the decision is
  5804. deferred until after the recursive call, at which point it is apparent
  5805. whether there is actually an available color or not. We observe that
  5806. this algorithm is equivalent to the smallest-last ordering
  5807. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5808. be registers and the rest to be stack locations.
  5809. %% biased coloring
  5810. Earlier editions of the compiler course at Indiana University
  5811. \citep{Dybvig:2010aa} were based on the algorithm of
  5812. \citet{Briggs:1994kx}.
  5813. The smallest-last ordering algorithm is one of many \emph{greedy}
  5814. coloring algorithms. A greedy coloring algorithm visits all the
  5815. vertices in a particular order and assigns each one the first
  5816. available color. An \emph{offline} greedy algorithm chooses the
  5817. ordering up-front, prior to assigning colors. The algorithm of
  5818. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5819. ordering does not depend on the colors assigned. Other orderings are
  5820. possible. For example, \citet{Chow:1984ys} order variables according
  5821. to an estimate of runtime cost.
  5822. An \emph{online} greedy coloring algorithm uses information about the
  5823. current assignment of colors to influence the order in which the
  5824. remaining vertices are colored. The saturation-based algorithm
  5825. described in this chapter is one such algorithm. We choose to use
  5826. saturation-based coloring because it is fun to introduce graph
  5827. coloring via Sudoku!
  5828. A register allocator may choose to map each variable to just one
  5829. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5830. variable to one or more locations. The later can be achieved by
  5831. \emph{live range splitting}, where a variable is replaced by several
  5832. variables that each handle part of its live
  5833. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5834. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5835. %% replacement algorithm, bottom-up local
  5836. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5837. %% Cooper: top-down (priority bassed), bottom-up
  5838. %% top-down
  5839. %% order variables by priority (estimated cost)
  5840. %% caveat: split variables into two groups:
  5841. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5842. %% color the constrained ones first
  5843. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5844. %% cite J. Cocke for an algorithm that colors variables
  5845. %% in a high-degree first ordering
  5846. %Register Allocation via Usage Counts, Freiburghouse CACM
  5847. \citet{Palsberg:2007si} observe that many of the interference graphs
  5848. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5849. that is, every cycle with four or more edges has an edge which is not
  5850. part of the cycle but which connects two vertices on the cycle. Such
  5851. graphs can be optimally colored by the greedy algorithm with a vertex
  5852. ordering determined by maximum cardinality search.
  5853. In situations where compile time is of utmost importance, such as in
  5854. just-in-time compilers, graph coloring algorithms can be too expensive
  5855. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5856. appropriate.
  5857. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5858. \chapter{Booleans and Conditionals}
  5859. \label{ch:Lif}
  5860. \index{subject}{Boolean}
  5861. \index{subject}{control flow}
  5862. \index{subject}{conditional expression}
  5863. The \LangInt{} and \LangVar{} languages only have a single kind of
  5864. value, the integers. In this chapter we add a second kind of value,
  5865. the Booleans, to create the \LangIf{} language. The Boolean values
  5866. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5867. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5868. language includes several operations that involve Booleans (\key{and},
  5869. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5870. \key{if} expression \python{and statement}. With the addition of
  5871. \key{if}, programs can have non-trivial control flow which
  5872. %
  5873. \racket{impacts \code{explicate\_control} and liveness analysis}
  5874. %
  5875. \python{impacts liveness analysis and motivates a new pass named
  5876. \code{explicate\_control}}.
  5877. %
  5878. Also, because we now have two kinds of values, we need to handle
  5879. programs that apply an operation to the wrong kind of value, such as
  5880. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5881. There are two language design options for such situations. One option
  5882. is to signal an error and the other is to provide a wider
  5883. interpretation of the operation. \racket{The Racket
  5884. language}\python{Python} uses a mixture of these two options,
  5885. depending on the operation and the kind of value. For example, the
  5886. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5887. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5888. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5889. %
  5890. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5891. in Racket because \code{car} expects a pair.}
  5892. %
  5893. \python{On the other hand, \code{1[0]} results in a run-time error
  5894. in Python because an ``\code{int} object is not subscriptable''.}
  5895. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5896. design choices as \racket{Racket}\python{Python}, except much of the
  5897. error detection happens at compile time instead of run
  5898. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5899. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5900. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5901. Racket}\python{MyPy} reports a compile-time error
  5902. %
  5903. \racket{because Racket expects the type of the argument to be of the form
  5904. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5905. %
  5906. \python{stating that a ``value of type \code{int} is not indexable''.}
  5907. The \LangIf{} language performs type checking during compilation like
  5908. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5909. alternative choice, that is, a dynamically typed language like
  5910. \racket{Racket}\python{Python}.
  5911. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5912. for some operations we are more restrictive, for example, rejecting
  5913. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5914. This chapter is organized as follows. We begin by defining the syntax
  5915. and interpreter for the \LangIf{} language
  5916. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5917. checking and define a type checker for \LangIf{}
  5918. (Section~\ref{sec:type-check-Lif}).
  5919. %
  5920. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5921. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5922. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5923. %
  5924. The remaining sections of this chapter discuss how the addition of
  5925. Booleans and conditional control flow to the language requires changes
  5926. to the existing compiler passes and the addition of new ones. In
  5927. particular, we introduce the \code{shrink} pass to translates some
  5928. operators into others, thereby reducing the number of operators that
  5929. need to be handled in later passes.
  5930. %
  5931. The main event of this chapter is the \code{explicate\_control} pass
  5932. that is responsible for translating \code{if}'s into conditional
  5933. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  5934. %
  5935. Regarding register allocation, there is the interesting question of
  5936. how to handle conditional \code{goto}'s during liveness analysis.
  5937. \section{The \LangIf{} Language}
  5938. \label{sec:lang-if}
  5939. The concrete syntax of the \LangIf{} language is defined in
  5940. Figure~\ref{fig:Lif-concrete-syntax} and the abstract syntax is defined
  5941. in Figure~\ref{fig:Lif-syntax}. The \LangIf{} language includes all of
  5942. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5943. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5944. operators to include
  5945. \begin{enumerate}
  5946. \item subtraction on integers,
  5947. \item the logical operators \key{and}, \key{or}, and \key{not},
  5948. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5949. for comparing integers or Booleans for equality, and
  5950. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5951. comparing integers.
  5952. \end{enumerate}
  5953. \racket{We reorganize the abstract syntax for the primitive
  5954. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  5955. rule for all of them. This means that the grammar no longer checks
  5956. whether the arity of an operators matches the number of
  5957. arguments. That responsibility is moved to the type checker for
  5958. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  5959. \newcommand{\LifGrammarRacket}{
  5960. \begin{array}{lcl}
  5961. \Type &::=& \key{Boolean} \\
  5962. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5963. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5964. \Exp &::=& \CSUB{\Exp}{\Exp} \MID \itm{bool}
  5965. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5966. \MID (\key{not}\;\Exp) \\
  5967. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  5968. \end{array}
  5969. }
  5970. \newcommand{\LifAST}{
  5971. \begin{array}{lcl}
  5972. \Type &::=& \key{Boolean} \\
  5973. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5974. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5975. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  5976. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  5977. \end{array}
  5978. }
  5979. \newcommand{\LintOpAST}{
  5980. \begin{array}{rcl}
  5981. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  5982. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  5983. \end{array}
  5984. }
  5985. \newcommand{\LifGrammarPython}{
  5986. \begin{array}{rcl}
  5987. \itm{binaryop} &::= & \key{and} \MID \key{or} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5988. \itm{unaryop} &::= & \key{not} \\
  5989. \Exp &::=& \TRUE \MID \FALSE \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5990. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  5991. \end{array}
  5992. }
  5993. \newcommand{\LifASTPython}{
  5994. \begin{array}{lcl}
  5995. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  5996. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  5997. \itm{unaryop} &::=& \code{Not()} \\
  5998. \itm{bool} &::=& \code{True} \MID \code{False} \\
  5999. \Exp &::=& \CMP{\Exp}{\itm{cmp}}{\Exp}
  6000. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6001. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6002. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6003. \end{array}
  6004. }
  6005. \begin{figure}[tp]
  6006. \centering
  6007. \fbox{
  6008. \begin{minipage}{0.96\textwidth}
  6009. {\if\edition\racketEd
  6010. \[
  6011. \begin{array}{l}
  6012. \gray{\LintGrammarRacket{}} \\ \hline
  6013. \gray{\LvarGrammarRacket{}} \\ \hline
  6014. \LifGrammarRacket{} \\
  6015. \begin{array}{lcl}
  6016. \LangIfM{} &::=& \Exp
  6017. \end{array}
  6018. \end{array}
  6019. \]
  6020. \fi}
  6021. {\if\edition\pythonEd
  6022. \[
  6023. \begin{array}{l}
  6024. \gray{\LintGrammarPython} \\ \hline
  6025. \gray{\LvarGrammarPython} \\ \hline
  6026. \LifGrammarPython \\
  6027. \begin{array}{rcl}
  6028. \LangIfM{} &::=& \Stmt^{*}
  6029. \end{array}
  6030. \end{array}
  6031. \]
  6032. \fi}
  6033. \end{minipage}
  6034. }
  6035. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6036. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6037. \label{fig:Lif-concrete-syntax}
  6038. \end{figure}
  6039. \begin{figure}[tp]
  6040. \centering
  6041. \fbox{
  6042. \begin{minipage}{0.96\textwidth}
  6043. {\if\edition\racketEd
  6044. \[
  6045. \begin{array}{l}
  6046. \gray{\LintOpAST} \\ \hline
  6047. \gray{\LvarAST{}} \\ \hline
  6048. \LifAST{} \\
  6049. \begin{array}{lcl}
  6050. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6051. \end{array}
  6052. \end{array}
  6053. \]
  6054. \fi}
  6055. {\if\edition\pythonEd
  6056. \[
  6057. \begin{array}{l}
  6058. \gray{\LintASTPython} \\ \hline
  6059. \gray{\LvarASTPython} \\ \hline
  6060. \LifASTPython \\
  6061. \begin{array}{lcl}
  6062. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6063. \end{array}
  6064. \end{array}
  6065. \]
  6066. \fi}
  6067. \end{minipage}
  6068. }
  6069. \caption{The abstract syntax of \LangIf{}.}
  6070. \label{fig:Lif-syntax}
  6071. \end{figure}
  6072. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6073. which inherits from the interpreter for \LangVar{}
  6074. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6075. evaluate to the corresponding Boolean values. The conditional
  6076. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6077. and then either evaluates $e_2$ or $e_3$ depending on whether
  6078. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6079. \code{and}, \code{or}, and \code{not} behave according to propositional logic,
  6080. but note that the \code{and} and \code{or} operations are
  6081. short-circuiting.
  6082. %
  6083. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6084. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6085. %
  6086. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6087. evaluated if $e_1$ evaluates to \TRUE{}.
  6088. \racket{With the increase in the number of primitive operations, the
  6089. interpreter would become repetitive without some care. We refactor
  6090. the case for \code{Prim}, moving the code that differs with each
  6091. operation into the \code{interp\_op} method shown in in
  6092. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6093. \code{or} operations separately because of their short-circuiting
  6094. behavior.}
  6095. \begin{figure}[tbp]
  6096. {\if\edition\racketEd
  6097. \begin{lstlisting}
  6098. (define interp_Lif_class
  6099. (class interp_Lvar_class
  6100. (super-new)
  6101. (define/public (interp_op op) ...)
  6102. (define/override ((interp_exp env) e)
  6103. (define recur (interp_exp env))
  6104. (match e
  6105. [(Bool b) b]
  6106. [(If cnd thn els)
  6107. (match (recur cnd)
  6108. [#t (recur thn)]
  6109. [#f (recur els)])]
  6110. [(Prim 'and (list e1 e2))
  6111. (match (recur e1)
  6112. [#t (match (recur e2) [#t #t] [#f #f])]
  6113. [#f #f])]
  6114. [(Prim 'or (list e1 e2))
  6115. (define v1 (recur e1))
  6116. (match v1
  6117. [#t #t]
  6118. [#f (match (recur e2) [#t #t] [#f #f])])]
  6119. [(Prim op args)
  6120. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6121. [else ((super interp_exp env) e)]))
  6122. ))
  6123. (define (interp_Lif p)
  6124. (send (new interp_Lif_class) interp_program p))
  6125. \end{lstlisting}
  6126. \fi}
  6127. {\if\edition\pythonEd
  6128. \begin{lstlisting}
  6129. class InterpLif(InterpLvar):
  6130. def interp_exp(self, e, env):
  6131. match e:
  6132. case IfExp(test, body, orelse):
  6133. if self.interp_exp(test, env):
  6134. return self.interp_exp(body, env)
  6135. else:
  6136. return self.interp_exp(orelse, env)
  6137. case BinOp(left, Sub(), right):
  6138. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6139. case UnaryOp(Not(), v):
  6140. return not self.interp_exp(v, env)
  6141. case BoolOp(And(), values):
  6142. if self.interp_exp(values[0], env):
  6143. return self.interp_exp(values[1], env)
  6144. else:
  6145. return False
  6146. case BoolOp(Or(), values):
  6147. if self.interp_exp(values[0], env):
  6148. return True
  6149. else:
  6150. return self.interp_exp(values[1], env)
  6151. case Compare(left, [cmp], [right]):
  6152. l = self.interp_exp(left, env)
  6153. r = self.interp_exp(right, env)
  6154. return self.interp_cmp(cmp)(l, r)
  6155. case _:
  6156. return super().interp_exp(e, env)
  6157. def interp_stmts(self, ss, env):
  6158. if len(ss) == 0:
  6159. return
  6160. match ss[0]:
  6161. case If(test, body, orelse):
  6162. if self.interp_exp(test, env):
  6163. return self.interp_stmts(body + ss[1:], env)
  6164. else:
  6165. return self.interp_stmts(orelse + ss[1:], env)
  6166. case _:
  6167. return super().interp_stmts(ss, env)
  6168. ...
  6169. \end{lstlisting}
  6170. \fi}
  6171. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6172. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6173. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6174. \label{fig:interp-Lif}
  6175. \end{figure}
  6176. {\if\edition\racketEd
  6177. \begin{figure}[tbp]
  6178. \begin{lstlisting}
  6179. (define/public (interp_op op)
  6180. (match op
  6181. ['+ fx+]
  6182. ['- fx-]
  6183. ['read read-fixnum]
  6184. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6185. ['eq? (lambda (v1 v2)
  6186. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6187. (and (boolean? v1) (boolean? v2))
  6188. (and (vector? v1) (vector? v2)))
  6189. (eq? v1 v2)]))]
  6190. ['< (lambda (v1 v2)
  6191. (cond [(and (fixnum? v1) (fixnum? v2))
  6192. (< v1 v2)]))]
  6193. ['<= (lambda (v1 v2)
  6194. (cond [(and (fixnum? v1) (fixnum? v2))
  6195. (<= v1 v2)]))]
  6196. ['> (lambda (v1 v2)
  6197. (cond [(and (fixnum? v1) (fixnum? v2))
  6198. (> v1 v2)]))]
  6199. ['>= (lambda (v1 v2)
  6200. (cond [(and (fixnum? v1) (fixnum? v2))
  6201. (>= v1 v2)]))]
  6202. [else (error 'interp_op "unknown operator")]))
  6203. \end{lstlisting}
  6204. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6205. \label{fig:interp-op-Lif}
  6206. \end{figure}
  6207. \fi}
  6208. {\if\edition\pythonEd
  6209. \begin{figure}
  6210. \begin{lstlisting}
  6211. class InterpLif(InterpLvar):
  6212. ...
  6213. def interp_cmp(self, cmp):
  6214. match cmp:
  6215. case Lt():
  6216. return lambda x, y: x < y
  6217. case LtE():
  6218. return lambda x, y: x <= y
  6219. case Gt():
  6220. return lambda x, y: x > y
  6221. case GtE():
  6222. return lambda x, y: x >= y
  6223. case Eq():
  6224. return lambda x, y: x == y
  6225. case NotEq():
  6226. return lambda x, y: x != y
  6227. \end{lstlisting}
  6228. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6229. \label{fig:interp-cmp-Lif}
  6230. \end{figure}
  6231. \fi}
  6232. \section{Type Checking \LangIf{} Programs}
  6233. \label{sec:type-check-Lif}
  6234. \index{subject}{type checking}
  6235. \index{subject}{semantic analysis}
  6236. It is helpful to think about type checking in two complementary
  6237. ways. A type checker predicts the type of value that will be produced
  6238. by each expression in the program. For \LangIf{}, we have just two types,
  6239. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6240. {\if\edition\racketEd
  6241. \begin{lstlisting}
  6242. (+ 10 (- (+ 12 20)))
  6243. \end{lstlisting}
  6244. \fi}
  6245. {\if\edition\pythonEd
  6246. \begin{lstlisting}
  6247. 10 + -(12 + 20)
  6248. \end{lstlisting}
  6249. \fi}
  6250. \noindent produces a value of type \INTTY{} while
  6251. {\if\edition\racketEd
  6252. \begin{lstlisting}
  6253. (and (not #f) #t)
  6254. \end{lstlisting}
  6255. \fi}
  6256. {\if\edition\pythonEd
  6257. \begin{lstlisting}
  6258. (not False) and True
  6259. \end{lstlisting}
  6260. \fi}
  6261. \noindent produces a value of type \BOOLTY{}.
  6262. A second way to think about type checking is that it enforces a set of
  6263. rules about which operators can be applied to which kinds of
  6264. values. For example, our type checker for \LangIf{} signals an error
  6265. for the below expression {\if\edition\racketEd
  6266. \begin{lstlisting}
  6267. (not (+ 10 (- (+ 12 20))))
  6268. \end{lstlisting}
  6269. \fi}
  6270. {\if\edition\pythonEd
  6271. \begin{lstlisting}
  6272. not (10 + -(12 + 20))
  6273. \end{lstlisting}
  6274. \fi}
  6275. The subexpression
  6276. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6277. has type \INTTY{} but the type checker enforces the rule that the argument of
  6278. \code{not} must be an expression of type \BOOLTY{}.
  6279. We implement type checking using classes and methods because they
  6280. provide the open recursion needed to reuse code as we extend the type
  6281. checker in later chapters, analogous to the use of classes and methods
  6282. for the interpreters (Section~\ref{sec:extensible-interp}).
  6283. We separate the type checker for the \LangVar{} subset into its own
  6284. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6285. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6286. from the type checker for \LangVar{}. These type checkers are in the
  6287. files
  6288. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6289. and
  6290. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6291. of the support code.
  6292. %
  6293. Each type checker is a structurally recursive function over the AST.
  6294. Given an input expression \code{e}, the type checker either signals an
  6295. error or returns \racket{an expression and} its type (\INTTY{} or
  6296. \BOOLTY{}).
  6297. %
  6298. \racket{It returns an expression because there are situations in which
  6299. we want to change or update the expression.}
  6300. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6301. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6302. \INTTY{}. To handle variables, the type checker uses the environment
  6303. \code{env} to map variables to types.
  6304. %
  6305. \racket{Consider the case for \key{let}. We type check the
  6306. initializing expression to obtain its type \key{T} and then
  6307. associate type \code{T} with the variable \code{x} in the
  6308. environment used to type check the body of the \key{let}. Thus,
  6309. when the type checker encounters a use of variable \code{x}, it can
  6310. find its type in the environment.}
  6311. %
  6312. \python{Consider the case for assignment. We type check the
  6313. initializing expression to obtain its type \key{t}. If the variable
  6314. \code{lhs.id} is already in the environment because there was a
  6315. prior assignment, we check that this initializer has the same type
  6316. as the prior one. If this is the first assignment to the variable,
  6317. we associate type \code{t} with the variable \code{lhs.id} in the
  6318. environment. Thus, when the type checker encounters a use of
  6319. variable \code{x}, it can find its type in the environment.}
  6320. %
  6321. \racket{Regarding primitive operators, we recursively analyze the
  6322. arguments and then invoke \code{type\_check\_op} to check whether
  6323. the argument types are allowed.}
  6324. %
  6325. \python{Regarding addition and negation, we recursively analyze the
  6326. arguments, check that they have type \INT{}, and return \INT{}.}
  6327. \racket{Several auxiliary methods are used in the type checker. The
  6328. method \code{operator-types} defines a dictionary that maps the
  6329. operator names to their parameter and return types. The
  6330. \code{type-equal?} method determines whether two types are equal,
  6331. which for now simply dispatches to \code{equal?} (deep
  6332. equality). The \code{check-type-equal?} method triggers an error if
  6333. the two types are not equal. The \code{type-check-op} method looks
  6334. up the operator in the \code{operator-types} dictionary and then
  6335. checks whether the argument types are equal to the parameter types.
  6336. The result is the return type of the operator.}
  6337. %
  6338. \python{The auxiliary method \code{check\_type\_equal} method triggers
  6339. an error if the two types are not equal.}
  6340. \begin{figure}[tbp]
  6341. {\if\edition\racketEd
  6342. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6343. (define type-check-Lvar_class
  6344. (class object%
  6345. (super-new)
  6346. (define/public (operator-types)
  6347. '((+ . ((Integer Integer) . Integer))
  6348. (- . ((Integer) . Integer))
  6349. (read . (() . Integer))))
  6350. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6351. (define/public (check-type-equal? t1 t2 e)
  6352. (unless (type-equal? t1 t2)
  6353. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6354. (define/public (type-check-op op arg-types e)
  6355. (match (dict-ref (operator-types) op)
  6356. [`(,param-types . ,return-type)
  6357. (for ([at arg-types] [pt param-types])
  6358. (check-type-equal? at pt e))
  6359. return-type]
  6360. [else (error 'type-check-op "unrecognized ~a" op)]))
  6361. (define/public (type-check-exp env)
  6362. (lambda (e)
  6363. (match e
  6364. [(Int n) (values (Int n) 'Integer)]
  6365. [(Var x) (values (Var x) (dict-ref env x))]
  6366. [(Let x e body)
  6367. (define-values (e^ Te) ((type-check-exp env) e))
  6368. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6369. (values (Let x e^ b) Tb)]
  6370. [(Prim op es)
  6371. (define-values (new-es ts)
  6372. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6373. (values (Prim op new-es) (type-check-op op ts e))]
  6374. [else (error 'type-check-exp "couldn't match" e)])))
  6375. (define/public (type-check-program e)
  6376. (match e
  6377. [(Program info body)
  6378. (define-values (body^ Tb) ((type-check-exp '()) body))
  6379. (check-type-equal? Tb 'Integer body)
  6380. (Program info body^)]
  6381. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6382. ))
  6383. (define (type-check-Lvar p)
  6384. (send (new type-check-Lvar_class) type-check-program p))
  6385. \end{lstlisting}
  6386. \fi}
  6387. {\if\edition\pythonEd
  6388. \begin{lstlisting}
  6389. class TypeCheckLvar:
  6390. def check_type_equal(self, t1, t2, e):
  6391. if t1 != t2:
  6392. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6393. raise Exception(msg)
  6394. def type_check_exp(self, e, env):
  6395. match e:
  6396. case BinOp(left, Add(), right):
  6397. l = self.type_check_exp(left, env)
  6398. check_type_equal(l, int, left)
  6399. r = self.type_check_exp(right, env)
  6400. check_type_equal(r, int, right)
  6401. return int
  6402. case UnaryOp(USub(), v):
  6403. t = self.type_check_exp(v, env)
  6404. check_type_equal(t, int, v)
  6405. return int
  6406. case Name(id):
  6407. return env[id]
  6408. case Constant(value) if isinstance(value, int):
  6409. return int
  6410. case Call(Name('input_int'), []):
  6411. return int
  6412. def type_check_stmts(self, ss, env):
  6413. if len(ss) == 0:
  6414. return
  6415. match ss[0]:
  6416. case Assign([lhs], value):
  6417. t = self.type_check_exp(value, env)
  6418. if lhs.id in env:
  6419. check_type_equal(env[lhs.id], t, value)
  6420. else:
  6421. env[lhs.id] = t
  6422. return self.type_check_stmts(ss[1:], env)
  6423. case Expr(Call(Name('print'), [arg])):
  6424. t = self.type_check_exp(arg, env)
  6425. check_type_equal(t, int, arg)
  6426. return self.type_check_stmts(ss[1:], env)
  6427. case Expr(value):
  6428. self.type_check_exp(value, env)
  6429. return self.type_check_stmts(ss[1:], env)
  6430. def type_check_P(self, p):
  6431. match p:
  6432. case Module(body):
  6433. self.type_check_stmts(body, {})
  6434. \end{lstlisting}
  6435. \fi}
  6436. \caption{Type checker for the \LangVar{} language.}
  6437. \label{fig:type-check-Lvar}
  6438. \end{figure}
  6439. \begin{figure}[tbp]
  6440. {\if\edition\racketEd
  6441. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6442. (define type-check-Lif_class
  6443. (class type-check-Lvar_class
  6444. (super-new)
  6445. (inherit check-type-equal?)
  6446. (define/override (operator-types)
  6447. (append '((- . ((Integer Integer) . Integer))
  6448. (and . ((Boolean Boolean) . Boolean))
  6449. (or . ((Boolean Boolean) . Boolean))
  6450. (< . ((Integer Integer) . Boolean))
  6451. (<= . ((Integer Integer) . Boolean))
  6452. (> . ((Integer Integer) . Boolean))
  6453. (>= . ((Integer Integer) . Boolean))
  6454. (not . ((Boolean) . Boolean))
  6455. )
  6456. (super operator-types)))
  6457. (define/override (type-check-exp env)
  6458. (lambda (e)
  6459. (match e
  6460. [(Bool b) (values (Bool b) 'Boolean)]
  6461. [(Prim 'eq? (list e1 e2))
  6462. (define-values (e1^ T1) ((type-check-exp env) e1))
  6463. (define-values (e2^ T2) ((type-check-exp env) e2))
  6464. (check-type-equal? T1 T2 e)
  6465. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6466. [(If cnd thn els)
  6467. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6468. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6469. (define-values (els^ Te) ((type-check-exp env) els))
  6470. (check-type-equal? Tc 'Boolean e)
  6471. (check-type-equal? Tt Te e)
  6472. (values (If cnd^ thn^ els^) Te)]
  6473. [else ((super type-check-exp env) e)])))
  6474. ))
  6475. (define (type-check-Lif p)
  6476. (send (new type-check-Lif_class) type-check-program p))
  6477. \end{lstlisting}
  6478. \fi}
  6479. {\if\edition\pythonEd
  6480. \begin{lstlisting}
  6481. class TypeCheckLif(TypeCheckLvar):
  6482. def type_check_exp(self, e, env):
  6483. match e:
  6484. case Constant(value) if isinstance(value, bool):
  6485. return bool
  6486. case BinOp(left, Sub(), right):
  6487. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6488. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6489. return int
  6490. case UnaryOp(Not(), v):
  6491. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6492. return bool
  6493. case BoolOp(op, values):
  6494. left = values[0] ; right = values[1]
  6495. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6496. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6497. return bool
  6498. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6499. or isinstance(cmp, NotEq):
  6500. l = self.type_check_exp(left, env)
  6501. r = self.type_check_exp(right, env)
  6502. check_type_equal(l, r, e)
  6503. return bool
  6504. case Compare(left, [cmp], [right]):
  6505. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6506. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6507. return bool
  6508. case IfExp(test, body, orelse):
  6509. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6510. b = self.type_check_exp(body, env)
  6511. o = self.type_check_exp(orelse, env)
  6512. check_type_equal(b, o, e)
  6513. return b
  6514. case _:
  6515. return super().type_check_exp(e, env)
  6516. def type_check_stmts(self, ss, env):
  6517. if len(ss) == 0:
  6518. return
  6519. match ss[0]:
  6520. case If(test, body, orelse):
  6521. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6522. b = self.type_check_stmts(body, env)
  6523. o = self.type_check_stmts(orelse, env)
  6524. check_type_equal(b, o, ss[0])
  6525. return self.type_check_stmts(ss[1:], env)
  6526. case _:
  6527. return super().type_check_stmts(ss, env)
  6528. \end{lstlisting}
  6529. \fi}
  6530. \caption{Type checker for the \LangIf{} language.}
  6531. \label{fig:type-check-Lif}
  6532. \end{figure}
  6533. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6534. checker for \LangIf{}.
  6535. %
  6536. The type of a Boolean constant is \BOOLTY{}.
  6537. %
  6538. \racket{The \code{operator-types} function adds dictionary entries for
  6539. the other new operators.}
  6540. %
  6541. \python{Subtraction requires its arguments to be of type \INTTY{} and produces
  6542. an \INTTY{}. Negation requires its argument to be a \BOOLTY{} and
  6543. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6544. %
  6545. The equality operators requires the two arguments to have the same
  6546. type.
  6547. %
  6548. \python{The other comparisons (less-than, etc.) require their
  6549. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6550. %
  6551. The condition of an \code{if} must
  6552. be of \BOOLTY{} type and the two branches must have the same type.
  6553. \begin{exercise}\normalfont
  6554. Create 10 new test programs in \LangIf{}. Half of the programs should
  6555. have a type error. For those programs, create an empty file with the
  6556. same base name but with file extension \code{.tyerr}. For example, if
  6557. the test
  6558. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6559. is expected to error, then create
  6560. an empty file named \code{cond\_test\_14.tyerr}.
  6561. %
  6562. \racket{This indicates to \code{interp-tests} and
  6563. \code{compiler-tests} that a type error is expected. }
  6564. %
  6565. \racket{This indicates to the \code{run-tests.rkt} scripts that a type
  6566. error is expected.}
  6567. %
  6568. The other half of the test programs should not have type errors.
  6569. %
  6570. \racket{In the \code{run-tests.rkt} script, change the second argument
  6571. of \code{interp-tests} and \code{compiler-tests} to
  6572. \code{type-check-Lif}, which causes the type checker to run prior to
  6573. the compiler passes. Temporarily change the \code{passes} to an
  6574. empty list and run the script, thereby checking that the new test
  6575. programs either type check or not as intended.}
  6576. %
  6577. Run the test script to check that these test programs type check as
  6578. expected.
  6579. \end{exercise}
  6580. \clearpage
  6581. \section{The \LangCIf{} Intermediate Language}
  6582. \label{sec:Cif}
  6583. {\if\edition\racketEd
  6584. %
  6585. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6586. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6587. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6588. language adds logical and comparison operators to the \Exp{}
  6589. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6590. non-terminal.
  6591. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6592. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6593. statement is a comparison operation and the branches are \code{goto}
  6594. statements, making it straightforward to compile \code{if} statements
  6595. to x86.
  6596. %
  6597. \fi}
  6598. %
  6599. {\if\edition\pythonEd
  6600. %
  6601. The output of \key{explicate\_control} is a language similar to the
  6602. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6603. \code{goto} statements, so we name it \LangCIf{}. The
  6604. concrete syntax for \LangCIf{} is defined in
  6605. Figure~\ref{fig:c1-concrete-syntax}
  6606. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6607. %
  6608. The \LangCIf{} language supports the same operators as \LangIf{} but
  6609. the arguments of operators are restricted to atomic expressions. The
  6610. \LangCIf{} language does not include \code{if} expressions but it does
  6611. include a restricted form of \code{if} statment. The condition must be
  6612. a comparison and the two branches may only contain \code{goto}
  6613. statements. These restrictions make it easier to translate \code{if}
  6614. statements to x86.
  6615. %
  6616. \fi}
  6617. %
  6618. The \key{CProgram} construct contains
  6619. %
  6620. \racket{an alist}\python{a dictionary}
  6621. %
  6622. mapping labels to $\Tail$ expressions, which can be return statements,
  6623. an assignment statement followed by a $\Tail$ expression, a
  6624. \code{goto}, or a conditional \code{goto}.
  6625. \begin{figure}[tbp]
  6626. \fbox{
  6627. \begin{minipage}{0.96\textwidth}
  6628. \small
  6629. \[
  6630. \begin{array}{lcl}
  6631. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  6632. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6633. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} \MID \key{(-}~\Atm~\Atm\key{)} } \\
  6634. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6635. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  6636. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  6637. \MID \key{goto}~\itm{label}\key{;}\\
  6638. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  6639. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  6640. \end{array}
  6641. \]
  6642. \end{minipage}
  6643. }
  6644. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6645. \label{fig:c1-concrete-syntax}
  6646. \end{figure}
  6647. \begin{figure}[tp]
  6648. \fbox{
  6649. \begin{minipage}{0.96\textwidth}
  6650. \small
  6651. {\if\edition\racketEd
  6652. \[
  6653. \begin{array}{lcl}
  6654. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  6655. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6656. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  6657. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6658. &\MID& \UNIOP{\key{'not}}{\Atm}
  6659. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6660. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  6661. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  6662. \MID \GOTO{\itm{label}} \\
  6663. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  6664. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  6665. \end{array}
  6666. \]
  6667. \fi}
  6668. {\if\edition\pythonEd
  6669. \[
  6670. \begin{array}{lcl}
  6671. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6672. \Exp &::= & \Atm \MID \READ{} \\
  6673. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6674. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6675. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  6676. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  6677. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6678. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6679. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6680. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  6681. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{*}, \ldots \RC}
  6682. \end{array}
  6683. \]
  6684. \fi}
  6685. \end{minipage}
  6686. }
  6687. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6688. (Figure~\ref{fig:c0-syntax})}.}
  6689. \label{fig:c1-syntax}
  6690. \end{figure}
  6691. \section{The \LangXIf{} Language}
  6692. \label{sec:x86-if}
  6693. \index{subject}{x86} To implement the new logical operations, the comparison
  6694. operations, and the \key{if} expression, we need to delve further into
  6695. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6696. define the concrete and abstract syntax for the \LangXIf{} subset
  6697. of x86, which includes instructions for logical operations,
  6698. comparisons, and \racket{conditional} jumps.
  6699. One challenge is that x86 does not provide an instruction that
  6700. directly implements logical negation (\code{not} in \LangIf{} and
  6701. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6702. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6703. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6704. bit of its arguments, and writes the results into its second argument.
  6705. Recall the truth table for exclusive-or:
  6706. \begin{center}
  6707. \begin{tabular}{l|cc}
  6708. & 0 & 1 \\ \hline
  6709. 0 & 0 & 1 \\
  6710. 1 & 1 & 0
  6711. \end{tabular}
  6712. \end{center}
  6713. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6714. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6715. for the bit $1$, the result is the opposite of the second bit. Thus,
  6716. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6717. the first argument as follows, where $\Arg$ is the translation of
  6718. $\Atm$.
  6719. \[
  6720. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6721. \qquad\Rightarrow\qquad
  6722. \begin{array}{l}
  6723. \key{movq}~ \Arg\key{,} \Var\\
  6724. \key{xorq}~ \key{\$1,} \Var
  6725. \end{array}
  6726. \]
  6727. \begin{figure}[tp]
  6728. \fbox{
  6729. \begin{minipage}{0.96\textwidth}
  6730. \[
  6731. \begin{array}{lcl}
  6732. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6733. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6734. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6735. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6736. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6737. \key{subq} \; \Arg\key{,} \Arg \MID
  6738. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6739. && \gray{ \key{callq} \; \itm{label} \MID
  6740. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6741. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6742. \MID \key{xorq}~\Arg\key{,}~\Arg
  6743. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6744. && \key{set}cc~\Arg
  6745. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6746. \MID \key{j}cc~\itm{label}
  6747. \\
  6748. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6749. & & \gray{ \key{main:} \; \Instr\ldots }
  6750. \end{array}
  6751. \]
  6752. \end{minipage}
  6753. }
  6754. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6755. \label{fig:x86-1-concrete}
  6756. \end{figure}
  6757. \begin{figure}[tp]
  6758. \fbox{
  6759. \begin{minipage}{0.98\textwidth}
  6760. \small
  6761. {\if\edition\racketEd
  6762. \[
  6763. \begin{array}{lcl}
  6764. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6765. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6766. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6767. \MID \BYTEREG{\itm{bytereg}} \\
  6768. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6769. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6770. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6771. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6772. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6773. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6774. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6775. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6776. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6777. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6778. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6779. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6780. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6781. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6782. \end{array}
  6783. \]
  6784. \fi}
  6785. %
  6786. {\if\edition\pythonEd
  6787. \[
  6788. \begin{array}{lcl}
  6789. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6790. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6791. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6792. \MID \BYTEREG{\itm{bytereg}} \\
  6793. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6794. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6795. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6796. &\MID& \gray{ \BININSTR{\code{movq}}{\Arg}{\Arg}
  6797. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6798. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6799. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6800. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6801. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6802. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6803. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6804. &\MID& \JMPIF{\key{'}\itm{cc}\key{'}}{\itm{label}} \\
  6805. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6806. \end{array}
  6807. \]
  6808. \fi}
  6809. \end{minipage}
  6810. }
  6811. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6812. \label{fig:x86-1}
  6813. \end{figure}
  6814. Next we consider the x86 instructions that are relevant for compiling
  6815. the comparison operations. The \key{cmpq} instruction compares its two
  6816. arguments to determine whether one argument is less than, equal, or
  6817. greater than the other argument. The \key{cmpq} instruction is unusual
  6818. regarding the order of its arguments and where the result is
  6819. placed. The argument order is backwards: if you want to test whether
  6820. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6821. \key{cmpq} is placed in the special EFLAGS register. This register
  6822. cannot be accessed directly but it can be queried by a number of
  6823. instructions, including the \key{set} instruction. The instruction
  6824. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6825. depending on whether the comparison comes out according to the
  6826. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6827. for less-or-equal, \key{g} for greater, \key{ge} for
  6828. greater-or-equal). The \key{set} instruction has a quirk in
  6829. that its destination argument must be single byte register, such as
  6830. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6831. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6832. instruction can be used to move from a single byte register to a
  6833. normal 64-bit register. The abstract syntax for the \code{set}
  6834. instruction differs from the concrete syntax in that it separates the
  6835. instruction name from the condition code.
  6836. \python{The x86 instructions for jumping are relevant to the
  6837. compilation of \key{if} expressions.}
  6838. %
  6839. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6840. counter to the address of the instruction after the specified
  6841. label.}
  6842. %
  6843. \racket{The x86 instruction for conditional jump is relevant to the
  6844. compilation of \key{if} expressions.}
  6845. %
  6846. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6847. counter to point to the instruction after \itm{label} depending on
  6848. whether the result in the EFLAGS register matches the condition code
  6849. \itm{cc}, otherwise the jump instruction falls through to the next
  6850. instruction. Like the abstract syntax for \code{set}, the abstract
  6851. syntax for conditional jump separates the instruction name from the
  6852. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6853. to \code{jle foo}. Because the conditional jump instruction relies on
  6854. the EFLAGS register, it is common for it to be immediately preceded by
  6855. a \key{cmpq} instruction to set the EFLAGS register.
  6856. \section{Shrink the \LangIf{} Language}
  6857. \label{sec:shrink-Lif}
  6858. The \LangIf{} language includes several features that are easily
  6859. expressible with other features. For example, \code{and} and \code{or}
  6860. are expressible using \code{if} as follows.
  6861. \begin{align*}
  6862. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6863. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6864. \end{align*}
  6865. By performing these translations in the front-end of the compiler, the
  6866. later passes of the compiler do not need to deal with these features,
  6867. making the passes shorter.
  6868. %% For example, subtraction is
  6869. %% expressible using addition and negation.
  6870. %% \[
  6871. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6872. %% \]
  6873. %% Several of the comparison operations are expressible using less-than
  6874. %% and logical negation.
  6875. %% \[
  6876. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6877. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6878. %% \]
  6879. %% The \key{let} is needed in the above translation to ensure that
  6880. %% expression $e_1$ is evaluated before $e_2$.
  6881. On the other hand, sometimes translations reduce the efficiency of the
  6882. generated code by increasing the number of instructions. For example,
  6883. expressing subtraction in terms of negation
  6884. \[
  6885. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6886. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6887. \]
  6888. produces code with two x86 instructions (\code{negq} and \code{addq})
  6889. instead of just one (\code{subq}).
  6890. %% However,
  6891. %% these differences typically do not affect the number of accesses to
  6892. %% memory, which is the primary factor that determines execution time on
  6893. %% modern computer architectures.
  6894. \begin{exercise}\normalfont
  6895. %
  6896. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6897. the language by translating them to \code{if} expressions in \LangIf{}.
  6898. %
  6899. Create four test programs that involve these operators.
  6900. %
  6901. {\if\edition\racketEd
  6902. In the \code{run-tests.rkt} script, add the following entry for
  6903. \code{shrink} to the list of passes (it should be the only pass at
  6904. this point).
  6905. \begin{lstlisting}
  6906. (list "shrink" shrink interp_Lif type-check-Lif)
  6907. \end{lstlisting}
  6908. This instructs \code{interp-tests} to run the intepreter
  6909. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  6910. output of \code{shrink}.
  6911. \fi}
  6912. %
  6913. Run the script to test your compiler on all the test programs.
  6914. \end{exercise}
  6915. {\if\edition\racketEd
  6916. \section{Uniquify Variables}
  6917. \label{sec:uniquify-Lif}
  6918. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6919. \code{if} expressions.
  6920. \begin{exercise}\normalfont
  6921. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6922. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6923. \begin{lstlisting}
  6924. (list "uniquify" uniquify interp_Lif type_check_Lif)
  6925. \end{lstlisting}
  6926. Run the script to test your compiler.
  6927. \end{exercise}
  6928. \fi}
  6929. \section{Remove Complex Operands}
  6930. \label{sec:remove-complex-opera-Lif}
  6931. The output language of \code{remove\_complex\_operands} is
  6932. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  6933. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  6934. but the \code{if} expression is not. All three sub-expressions of an
  6935. \code{if} are allowed to be complex expressions but the operands of
  6936. \code{not} and the comparisons must be atomic.
  6937. %
  6938. \python{We add a new language form, the \code{Let} expression, to aid
  6939. in the translation of \code{if} expressions. When we recursively
  6940. process the two branches of the \code{if}, we generate temporary
  6941. variables and their initializing expressions. However, these
  6942. expressions may contain side effects and should only be executed
  6943. when the condition of the \code{if} is true (for the ``then''
  6944. branch) or false (for the ``else'' branch). The \code{Let} provides
  6945. a way to initialize the temporary variables within the two branches
  6946. of the \code{if} expression. In general, the $\LET{x}{e_1}{e_2}$
  6947. form assigns the result of $e_1$ to the variable $x$, an then
  6948. evaluates $e_2$, which may reference $x$.}
  6949. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  6950. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  6951. according to whether the output needs to be \Exp{} or \Atm{} as
  6952. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  6953. particularly important to \textbf{not} replace its condition with a
  6954. temporary variable because that would interfere with the generation of
  6955. high-quality output in the \code{explicate\_control} pass.
  6956. \begin{figure}[tp]
  6957. \centering
  6958. \fbox{
  6959. \begin{minipage}{0.96\textwidth}
  6960. {\if\edition\racketEd
  6961. \[
  6962. \begin{array}{rcl}
  6963. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  6964. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6965. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6966. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6967. &\MID& \UNIOP{\key{not}}{\Atm} \\
  6968. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6969. R^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Exp}
  6970. \end{array}
  6971. \]
  6972. \fi}
  6973. {\if\edition\pythonEd
  6974. \[
  6975. \begin{array}{rcl}
  6976. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  6977. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6978. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  6979. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6980. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  6981. \Exp &::=& \Atm \MID \READ{} \\
  6982. &\MID& \BINOP{\itm{binaryop}}{\Atm}{\Atm} \MID \UNIOP{\key{unaryop}}{\Atm} \\
  6983. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6984. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  6985. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6986. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  6987. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  6988. \end{array}
  6989. \]
  6990. \fi}
  6991. \end{minipage}
  6992. }
  6993. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  6994. \label{fig:Lif-anf-syntax}
  6995. \end{figure}
  6996. \begin{exercise}\normalfont
  6997. %
  6998. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  6999. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7000. %
  7001. Create three new \LangIf{} programs that exercise the interesting
  7002. code in this pass.
  7003. %
  7004. {\if\edition\racketEd
  7005. In the \code{run-tests.rkt} script, add the following entry to the
  7006. list of \code{passes} and then run the script to test your compiler.
  7007. \begin{lstlisting}
  7008. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  7009. \end{lstlisting}
  7010. \fi}
  7011. \end{exercise}
  7012. \section{Explicate Control}
  7013. \label{sec:explicate-control-Lif}
  7014. \racket{Recall that the purpose of \code{explicate\_control} is to
  7015. make the order of evaluation explicit in the syntax of the program.
  7016. With the addition of \key{if} this get more interesting.}
  7017. %
  7018. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7019. %
  7020. The main challenge to overcome is that the condition of an \key{if}
  7021. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7022. condition must be a comparison.
  7023. As a motivating example, consider the following program that has an
  7024. \key{if} expression nested in the condition of another \key{if}.%
  7025. \python{\footnote{Programmers rarely write nested \code{if}
  7026. expressions, but it is not uncommon for the condition of an
  7027. \code{if} statement to be a call of a function that also contains an
  7028. \code{if} statement. When such a function is inlined, the result is
  7029. a nested \code{if} that requires the techniques discussed in this
  7030. section.}}
  7031. % cond_test_41.rkt, if_lt_eq.py
  7032. \begin{center}
  7033. \begin{minipage}{0.96\textwidth}
  7034. {\if\edition\racketEd
  7035. \begin{lstlisting}
  7036. (let ([x (read)])
  7037. (let ([y (read)])
  7038. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7039. (+ y 2)
  7040. (+ y 10))))
  7041. \end{lstlisting}
  7042. \fi}
  7043. {\if\edition\pythonEd
  7044. \begin{lstlisting}
  7045. x = input_int()
  7046. y = input_int()
  7047. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7048. \end{lstlisting}
  7049. \fi}
  7050. \end{minipage}
  7051. \end{center}
  7052. %
  7053. The naive way to compile \key{if} and the comparison operations would
  7054. be to handle each of them in isolation, regardless of their context.
  7055. Each comparison would be translated into a \key{cmpq} instruction
  7056. followed by a couple instructions to move the result from the EFLAGS
  7057. register into a general purpose register or stack location. Each
  7058. \key{if} would be translated into a \key{cmpq} instruction followed by
  7059. a conditional jump. The generated code for the inner \key{if} in the
  7060. above example would be as follows.
  7061. \begin{center}
  7062. \begin{minipage}{0.96\textwidth}
  7063. \begin{lstlisting}
  7064. cmpq $1, x
  7065. setl %al
  7066. movzbq %al, tmp
  7067. cmpq $1, tmp
  7068. je then_branch_1
  7069. jmp else_branch_1
  7070. \end{lstlisting}
  7071. \end{minipage}
  7072. \end{center}
  7073. However, if we take context into account we can do better and reduce
  7074. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7075. Our goal will be to compile \key{if} expressions so that the relevant
  7076. comparison instruction appears directly before the conditional jump.
  7077. For example, we want to generate the following code for the inner
  7078. \code{if}.
  7079. \begin{center}
  7080. \begin{minipage}{0.96\textwidth}
  7081. \begin{lstlisting}
  7082. cmpq $1, x
  7083. jl then_branch_1
  7084. jmp else_branch_1
  7085. \end{lstlisting}
  7086. \end{minipage}
  7087. \end{center}
  7088. One way to achieve this is to reorganize the code at the level of
  7089. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7090. the following code.
  7091. \begin{center}
  7092. \begin{minipage}{0.96\textwidth}
  7093. {\if\edition\racketEd
  7094. \begin{lstlisting}
  7095. (let ([x (read)])
  7096. (let ([y (read)])
  7097. (if (< x 1)
  7098. (if (eq? x 0)
  7099. (+ y 2)
  7100. (+ y 10))
  7101. (if (eq? x 2)
  7102. (+ y 2)
  7103. (+ y 10)))))
  7104. \end{lstlisting}
  7105. \fi}
  7106. {\if\edition\pythonEd
  7107. \begin{lstlisting}
  7108. x = input_int()
  7109. y = intput_int()
  7110. print(((y + 2) if x == 0 else (y + 10)) \
  7111. if (x < 1) \
  7112. else ((y + 2) if (x == 2) else (y + 10)))
  7113. \end{lstlisting}
  7114. \fi}
  7115. \end{minipage}
  7116. \end{center}
  7117. Unfortunately, this approach duplicates the two branches from the
  7118. outer \code{if} and a compiler must never duplicate code! After all,
  7119. the two branches could have been very large expressions.
  7120. We need a way to perform the above transformation but without
  7121. duplicating code. That is, we need a way for different parts of a
  7122. program to refer to the same piece of code.
  7123. %
  7124. Put another way, we need to move away from abstract syntax
  7125. \emph{trees} and instead use \emph{graphs}.
  7126. %
  7127. At the level of x86 assembly this is straightforward because we can
  7128. label the code for each branch and insert jumps in all the places that
  7129. need to execute the branch.
  7130. %
  7131. Likewise, our language \LangCIf{} provides the ability to label a
  7132. sequence of code and to jump to a label via \code{goto}.
  7133. %
  7134. %% In particular, we use a standard program representation called a
  7135. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7136. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7137. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7138. %% edge represents a jump to another block.
  7139. %
  7140. %% The nice thing about the output of \code{explicate\_control} is that
  7141. %% there are no unnecessary comparisons and every comparison is part of a
  7142. %% conditional jump.
  7143. %% The down-side of this output is that it includes
  7144. %% trivial blocks, such as the blocks labeled \code{block92} through
  7145. %% \code{block95}, that only jump to another block. We discuss a solution
  7146. %% to this problem in Section~\ref{sec:opt-jumps}.
  7147. {\if\edition\racketEd
  7148. %
  7149. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7150. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7151. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7152. former function translates expressions in tail position whereas the
  7153. later function translates expressions on the right-hand-side of a
  7154. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7155. have a new kind of position to deal with: the predicate position of
  7156. the \key{if}. We need another function, \code{explicate\_pred}, that
  7157. decides how to compile an \key{if} by analyzing its predicate. So
  7158. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7159. tails for the then-branch and else-branch and outputs a tail. In the
  7160. following paragraphs we discuss specific cases in the
  7161. \code{explicate\_tail}, \code{explicate\_assign}, and
  7162. \code{explicate\_pred} functions.
  7163. %
  7164. \fi}
  7165. %
  7166. {\if\edition\pythonEd
  7167. %
  7168. We recommend implementing \code{explicate\_control} using the
  7169. following four auxiliary functions.
  7170. \begin{description}
  7171. \item[\code{explicate\_effect}] generates code for expressions as
  7172. statements, so their result is ignored and only their side effects
  7173. matter.
  7174. \item[\code{explicate\_assign}] generates code for expressions
  7175. on the right-hand side of an assignment.
  7176. \item[\code{explicate\_pred}] generates code for an \code{if}
  7177. expression or statement by analyzing the condition expression.
  7178. \item[\code{explicate\_stmt}] generates code for statements.
  7179. \end{description}
  7180. These four functions should build the dictionary of basic blocks. The
  7181. following auxiliary function can be used to create a new basic block
  7182. from a list of statements. It returns a \code{goto} statement that
  7183. jumps to the new basic block.
  7184. \begin{center}
  7185. \begin{minipage}{\textwidth}
  7186. \begin{lstlisting}
  7187. def create_block(stmts, basic_blocks):
  7188. label = label_name(generate_name('block'))
  7189. basic_blocks[label] = stmts
  7190. return Goto(label)
  7191. \end{lstlisting}
  7192. \end{minipage}
  7193. \end{center}
  7194. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7195. \code{explicate\_control} pass.
  7196. The \code{explicate\_effect} function has three parameters: 1) the
  7197. expression to be compiled, 2) the already-compiled code for this
  7198. expression's \emph{continuation}, that is, the list of statements that
  7199. should execute after this expression, and 3) the dictionary of
  7200. generated basic blocks. The \code{explicate\_effect} function returns
  7201. a list of \LangCIf{} statements and it may add to the dictionary of
  7202. basic blocks.
  7203. %
  7204. Let's consider a few of the cases for the expression to be compiled.
  7205. If the expression to be compiled is a constant, then it can be
  7206. discarded because it has no side effects. If it's a \CREAD{}, then it
  7207. has a side-effect and should be preserved. So the exprssion should be
  7208. translated into a statement using the \code{Expr} AST class. If the
  7209. expression to be compiled is an \code{if} expression, we translate the
  7210. two branches using \code{explicate\_effect} and then translate the
  7211. condition expression using \code{explicate\_pred}, which generates
  7212. code for the entire \code{if}.
  7213. The \code{explicate\_assign} function has four parameters: 1) the
  7214. right-hand-side of the assignment, 2) the left-hand-side of the
  7215. assignment (the variable), 3) the continuation, and 4) the dictionary
  7216. of basic blocks. The \code{explicate\_assign} function returns a list
  7217. of \LangCIf{} statements and it may add to the dictionary of basic
  7218. blocks.
  7219. When the right-hand-side is an \code{if} expression, there is some
  7220. work to do. In particular, the two branches should be translated using
  7221. \code{explicate\_assign} and the condition expression should be
  7222. translated using \code{explicate\_pred}. Otherwise we can simply
  7223. generate an assignment statement, with the given left and right-hand
  7224. sides, concatenated with its continuation.
  7225. \begin{figure}[tbp]
  7226. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7227. def explicate_effect(e, cont, basic_blocks):
  7228. match e:
  7229. case IfExp(test, body, orelse):
  7230. ...
  7231. case Call(func, args):
  7232. ...
  7233. case Let(var, rhs, body):
  7234. ...
  7235. case _:
  7236. ...
  7237. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7238. match rhs:
  7239. case IfExp(test, body, orelse):
  7240. ...
  7241. case Let(var, rhs, body):
  7242. ...
  7243. case _:
  7244. return [Assign([lhs], rhs)] + cont
  7245. def explicate_pred(cnd, thn, els, basic_blocks):
  7246. match cnd:
  7247. case Compare(left, [op], [right]):
  7248. goto_thn = create_block(thn, basic_blocks)
  7249. goto_els = create_block(els, basic_blocks)
  7250. return [If(cnd, [goto_thn], [goto_els])]
  7251. case Constant(True):
  7252. return thn;
  7253. case Constant(False):
  7254. return els;
  7255. case UnaryOp(Not(), operand):
  7256. ...
  7257. case IfExp(test, body, orelse):
  7258. ...
  7259. case Let(var, rhs, body):
  7260. ...
  7261. case _:
  7262. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7263. [create_block(els, basic_blocks)],
  7264. [create_block(thn, basic_blocks)])]
  7265. def explicate_stmt(s, cont, basic_blocks):
  7266. match s:
  7267. case Assign([lhs], rhs):
  7268. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7269. case Expr(value):
  7270. return explicate_effect(value, cont, basic_blocks)
  7271. case If(test, body, orelse):
  7272. ...
  7273. def explicate_control(p):
  7274. match p:
  7275. case Module(body):
  7276. new_body = [Return(Constant(0))]
  7277. basic_blocks = {}
  7278. for s in reversed(body):
  7279. new_body = explicate_stmt(s, new_body, basic_blocks)
  7280. basic_blocks[label_name('start')] = new_body
  7281. return CProgram(basic_blocks)
  7282. \end{lstlisting}
  7283. \caption{Skeleton for the \code{explicate\_control} pass.}
  7284. \label{fig:explicate-control-Lif}
  7285. \end{figure}
  7286. \fi}
  7287. {\if\edition\racketEd
  7288. %
  7289. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7290. additional cases for Boolean constants and \key{if}. The cases for
  7291. \code{if} should recursively compile the two branches using either
  7292. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7293. cases should then invoke \code{explicate\_pred} on the condition
  7294. expression, passing in the generated code for the two branches. For
  7295. example, consider the following program with an \code{if} in tail
  7296. position.
  7297. \begin{lstlisting}
  7298. (let ([x (read)])
  7299. (if (eq? x 0) 42 777))
  7300. \end{lstlisting}
  7301. The two branches are recursively compiled to \code{return 42;} and
  7302. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7303. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7304. used as the result for \code{explicate\_tail}.
  7305. Next let us consider a program with an \code{if} on the right-hand
  7306. side of a \code{let}.
  7307. \begin{lstlisting}
  7308. (let ([y (read)])
  7309. (let ([x (if (eq? y 0) 40 777)])
  7310. (+ x 2)))
  7311. \end{lstlisting}
  7312. Note that the body of the inner \code{let} will have already been
  7313. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7314. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7315. to recursively process both branches of the \code{if}, so we generate
  7316. the following block using an auxiliary function named \code{create\_block}.
  7317. \begin{lstlisting}
  7318. block_6:
  7319. return (+ x 2)
  7320. \end{lstlisting}
  7321. and use \code{goto block\_6;} as the \code{cont} argument for
  7322. compiling the branches. So the two branches compile to
  7323. \begin{lstlisting}
  7324. x = 40;
  7325. goto block_6;
  7326. \end{lstlisting}
  7327. and
  7328. \begin{lstlisting}
  7329. x = 777;
  7330. goto block_6;
  7331. \end{lstlisting}
  7332. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7333. 0)} and the above code for the branches.
  7334. \fi}
  7335. {\if\edition\racketEd
  7336. \begin{figure}[tbp]
  7337. \begin{lstlisting}
  7338. (define (explicate_pred cnd thn els)
  7339. (match cnd
  7340. [(Var x) ___]
  7341. [(Let x rhs body) ___]
  7342. [(Prim 'not (list e)) ___]
  7343. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7344. (IfStmt (Prim op es) (create_block thn)
  7345. (create_block els))]
  7346. [(Bool b) (if b thn els)]
  7347. [(If cnd^ thn^ els^) ___]
  7348. [else (error "explicate_pred unhandled case" cnd)]))
  7349. \end{lstlisting}
  7350. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7351. \label{fig:explicate-pred}
  7352. \end{figure}
  7353. \fi}
  7354. \racket{The skeleton for the \code{explicate\_pred} function is given
  7355. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7356. 1) \code{cnd}, the condition expression of the \code{if},
  7357. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7358. and 3) \code{els}, the code generated by
  7359. explicate for the ``else'' branch. The \code{explicate\_pred}
  7360. function should match on \code{cnd} with a case for
  7361. every kind of expression that can have type \code{Boolean}.}
  7362. %
  7363. \python{The \code{explicate\_pred} function has four parameters: 1)
  7364. the condition expession, 2) the generated statements for the
  7365. ``then'' branch, 3) the generated statements for the ``else''
  7366. branch, and 4) the dictionary of basic blocks. The
  7367. \code{explicate\_pred} function returns a list of \LangCIf{}
  7368. statements and it may add to the dictionary of basic blocks.}
  7369. Consider the case for comparison operators. We translate the
  7370. comparison to an \code{if} statement whose branches are \code{goto}
  7371. statements created by applying \code{create\_block} to the code
  7372. generated for the \code{thn} and \code{els} branches. Let us
  7373. illustrate this translation with an example. Returning
  7374. to the program with an \code{if} expression in tail position,
  7375. we invoke \code{explicate\_pred} on its condition \code{(eq? x 0)}
  7376. which happens to be a comparison operator.
  7377. \begin{lstlisting}
  7378. (let ([x (read)])
  7379. (if (eq? x 0) 42 777))
  7380. \end{lstlisting}
  7381. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7382. statements, from which we now create the following blocks.
  7383. \begin{center}
  7384. \begin{minipage}{\textwidth}
  7385. \begin{lstlisting}
  7386. block_1:
  7387. return 42;
  7388. block_2:
  7389. return 777;
  7390. \end{lstlisting}
  7391. \end{minipage}
  7392. \end{center}
  7393. %
  7394. So \code{explicate\_pred} compiles the comparison \code{(eq? x 0)}
  7395. to the following \code{if} statement.
  7396. %
  7397. \begin{center}
  7398. \begin{minipage}{\textwidth}
  7399. \begin{lstlisting}
  7400. if (eq? x 0)
  7401. goto block_1;
  7402. else
  7403. goto block_2;
  7404. \end{lstlisting}
  7405. \end{minipage}
  7406. \end{center}
  7407. Next consider the case for Boolean constants. We perform a kind of
  7408. partial evaluation\index{subject}{partial evaluation} and output
  7409. either the \code{thn} or \code{els} branch depending on whether the
  7410. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7411. following program.
  7412. \begin{center}
  7413. \begin{minipage}{\textwidth}
  7414. \begin{lstlisting}
  7415. (if #t 42 777)
  7416. \end{lstlisting}
  7417. \end{minipage}
  7418. \end{center}
  7419. %
  7420. Again, the two branches \code{42} and \code{777} were compiled to
  7421. \code{return} statements, so \code{explicate\_pred} compiles the
  7422. constant \code{\#t} to the code for the ``then'' branch.
  7423. \begin{center}
  7424. \begin{minipage}{\textwidth}
  7425. \begin{lstlisting}
  7426. return 42;
  7427. \end{lstlisting}
  7428. \end{minipage}
  7429. \end{center}
  7430. %
  7431. This case demonstrates that we sometimes discard the \code{thn} or
  7432. \code{els} blocks that are input to \code{explicate\_pred}.
  7433. The case for \key{if} expressions in \code{explicate\_pred} is
  7434. particularly illuminating because it deals with the challenges we
  7435. discussed above regarding nested \key{if} expressions
  7436. (Figure~\ref{fig:explicate-control-s1-38}). The
  7437. \racket{\lstinline{thn^}}\python{\code{body}} and
  7438. \racket{\lstinline{els^}}\python{\code{orlese}} branches of the
  7439. \key{if} inherit their context from the current one, that is,
  7440. predicate context. So you should recursively apply
  7441. \code{explicate\_pred} to the
  7442. \racket{\lstinline{thn^}}\python{\code{body}} and
  7443. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7444. those recursive calls, pass \code{thn} and \code{els} as the extra
  7445. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7446. inside each recursive call. As discussed above, to avoid duplicating
  7447. code, we need to add them to the dictionary of basic blocks so that we
  7448. can instead refer to them by name and execute them with a \key{goto}.
  7449. {\if\edition\pythonEd
  7450. %
  7451. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7452. three parameters: 1) the statement to be compiled, 2) the code for its
  7453. continuation, and 3) the dictionary of basic blocks. The
  7454. \code{explicate\_stmt} returns a list of statements and it may add to
  7455. the dictionary of basic blocks. The cases for assignment and an
  7456. expression-statement are given in full in the skeleton code: they
  7457. simply dispatch to \code{explicate\_assign} and
  7458. \code{explicate\_effect}, respectively. The case for \code{if}
  7459. statements is not given, and is similar to the case for \code{if}
  7460. expressions.
  7461. The \code{explicate\_control} function itself is given in
  7462. Figure~\ref{fig:explicate-control-Lif}. It applies
  7463. \code{explicate\_stmt} to each statement in the program, from back to
  7464. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7465. used as the continuation parameter in the next call to
  7466. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7467. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7468. the dictionary of basic blocks, labeling it as the ``start'' block.
  7469. %
  7470. \fi}
  7471. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7472. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7473. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7474. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7475. %% results from the two recursive calls. We complete the case for
  7476. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7477. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7478. %% the result $B_5$.
  7479. %% \[
  7480. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7481. %% \quad\Rightarrow\quad
  7482. %% B_5
  7483. %% \]
  7484. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7485. %% inherit the current context, so they are in tail position. Thus, the
  7486. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7487. %% \code{explicate\_tail}.
  7488. %% %
  7489. %% We need to pass $B_0$ as the accumulator argument for both of these
  7490. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7491. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7492. %% to the control-flow graph and obtain a promised goto $G_0$.
  7493. %% %
  7494. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7495. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7496. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7497. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7498. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7499. %% \[
  7500. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7501. %% \]
  7502. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7503. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7504. %% should not be confused with the labels for the blocks that appear in
  7505. %% the generated code. We initially construct unlabeled blocks; we only
  7506. %% attach labels to blocks when we add them to the control-flow graph, as
  7507. %% we see in the next case.
  7508. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7509. %% function. The context of the \key{if} is an assignment to some
  7510. %% variable $x$ and then the control continues to some promised block
  7511. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7512. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7513. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7514. %% branches of the \key{if} inherit the current context, so they are in
  7515. %% assignment positions. Let $B_2$ be the result of applying
  7516. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7517. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7518. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7519. %% the result of applying \code{explicate\_pred} to the predicate
  7520. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7521. %% translates to the promise $B_4$.
  7522. %% \[
  7523. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7524. %% \]
  7525. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7526. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7527. \code{remove\_complex\_operands} pass and then the
  7528. \code{explicate\_control} pass on the example program. We walk through
  7529. the output program.
  7530. %
  7531. Following the order of evaluation in the output of
  7532. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7533. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7534. in the predicate of the inner \key{if}. In the output of
  7535. \code{explicate\_control}, in the
  7536. block labeled \code{start}, are two assignment statements followed by a
  7537. \code{if} statement that branches to \code{block\_8} or
  7538. \code{block\_9}. The blocks associated with those labels contain the
  7539. translations of the code
  7540. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7541. and
  7542. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7543. respectively. In particular, we start \code{block\_8} with the
  7544. comparison
  7545. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7546. and then branch to \code{block\_4} or \code{block\_5}.
  7547. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7548. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7549. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7550. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7551. and go directly to \code{block\_2} and \code{block\_3},
  7552. which we investigate in Section~\ref{sec:opt-jumps}.
  7553. Getting back to the example, \code{block\_2} and \code{block\_3},
  7554. corresponds to the two branches of the outer \key{if}, i.e.,
  7555. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7556. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7557. %
  7558. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7559. %
  7560. \python{The \code{block\_1} corresponds to the \code{print} statment
  7561. at the end of the program.}
  7562. \begin{figure}[tbp]
  7563. {\if\edition\racketEd
  7564. \begin{tabular}{lll}
  7565. \begin{minipage}{0.4\textwidth}
  7566. % cond_test_41.rkt
  7567. \begin{lstlisting}
  7568. (let ([x (read)])
  7569. (let ([y (read)])
  7570. (if (if (< x 1)
  7571. (eq? x 0)
  7572. (eq? x 2))
  7573. (+ y 2)
  7574. (+ y 10))))
  7575. \end{lstlisting}
  7576. \end{minipage}
  7577. &
  7578. $\Rightarrow$
  7579. &
  7580. \begin{minipage}{0.55\textwidth}
  7581. \begin{lstlisting}
  7582. start:
  7583. x = (read);
  7584. y = (read);
  7585. if (< x 1)
  7586. goto block_8;
  7587. else
  7588. goto block_9;
  7589. block_8:
  7590. if (eq? x 0)
  7591. goto block_4;
  7592. else
  7593. goto block_5;
  7594. block_9:
  7595. if (eq? x 2)
  7596. goto block_6;
  7597. else
  7598. goto block_7;
  7599. block_4:
  7600. goto block_2;
  7601. block_5:
  7602. goto block_3;
  7603. block_6:
  7604. goto block_2;
  7605. block_7:
  7606. goto block_3;
  7607. block_2:
  7608. return (+ y 2);
  7609. block_3:
  7610. return (+ y 10);
  7611. \end{lstlisting}
  7612. \end{minipage}
  7613. \end{tabular}
  7614. \fi}
  7615. {\if\edition\pythonEd
  7616. \begin{tabular}{lll}
  7617. \begin{minipage}{0.4\textwidth}
  7618. % cond_test_41.rkt
  7619. \begin{lstlisting}
  7620. x = input_int()
  7621. y = input_int()
  7622. print(y + 2 \
  7623. if (x == 0 \
  7624. if x < 1 \
  7625. else x == 2) \
  7626. else y + 10)
  7627. \end{lstlisting}
  7628. \end{minipage}
  7629. &
  7630. $\Rightarrow$
  7631. &
  7632. \begin{minipage}{0.55\textwidth}
  7633. \begin{lstlisting}
  7634. start:
  7635. x = input_int()
  7636. y = input_int()
  7637. if x < 1:
  7638. goto block_8
  7639. else:
  7640. goto block_9
  7641. block_8:
  7642. if x == 0:
  7643. goto block_4
  7644. else:
  7645. goto block_5
  7646. block_9:
  7647. if x == 2:
  7648. goto block_6
  7649. else:
  7650. goto block_7
  7651. block_4:
  7652. goto block_2
  7653. block_5:
  7654. goto block_3
  7655. block_6:
  7656. goto block_2
  7657. block_7:
  7658. goto block_3
  7659. block_2:
  7660. tmp_0 = y + 2
  7661. goto block_1
  7662. block_3:
  7663. tmp_0 = y + 10
  7664. goto block_1
  7665. block_1:
  7666. print(tmp_0)
  7667. return 0
  7668. \end{lstlisting}
  7669. \end{minipage}
  7670. \end{tabular}
  7671. \fi}
  7672. \caption{Translation from \LangIf{} to \LangCIf{}
  7673. via the \code{explicate\_control}.}
  7674. \label{fig:explicate-control-s1-38}
  7675. \end{figure}
  7676. {\if\edition\racketEd
  7677. The way in which the \code{shrink} pass transforms logical operations
  7678. such as \code{and} and \code{or} can impact the quality of code
  7679. generated by \code{explicate\_control}. For example, consider the
  7680. following program.
  7681. % cond_test_21.rkt, and_eq_input.py
  7682. \begin{lstlisting}
  7683. (if (and (eq? (read) 0) (eq? (read) 1))
  7684. 0
  7685. 42)
  7686. \end{lstlisting}
  7687. The \code{and} operation should transform into something that the
  7688. \code{explicate\_pred} function can still analyze and descend through to
  7689. reach the underlying \code{eq?} conditions. Ideally, your
  7690. \code{explicate\_control} pass should generate code similar to the
  7691. following for the above program.
  7692. \begin{center}
  7693. \begin{lstlisting}
  7694. start:
  7695. tmp1 = (read);
  7696. if (eq? tmp1 0) goto block40;
  7697. else goto block39;
  7698. block40:
  7699. tmp2 = (read);
  7700. if (eq? tmp2 1) goto block38;
  7701. else goto block39;
  7702. block38:
  7703. return 0;
  7704. block39:
  7705. return 42;
  7706. \end{lstlisting}
  7707. \end{center}
  7708. \fi}
  7709. \begin{exercise}\normalfont
  7710. \racket{
  7711. Implement the pass \code{explicate\_control} by adding the cases for
  7712. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7713. \code{explicate\_assign} functions. Implement the auxiliary function
  7714. \code{explicate\_pred} for predicate contexts.}
  7715. \python{Implement \code{explicate\_control} pass with its
  7716. four auxiliary functions.}
  7717. %
  7718. Create test cases that exercise all of the new cases in the code for
  7719. this pass.
  7720. %
  7721. {\if\edition\racketEd
  7722. Add the following entry to the list of \code{passes} in
  7723. \code{run-tests.rkt} and then run this script to test your compiler.
  7724. \begin{lstlisting}
  7725. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7726. \end{lstlisting}
  7727. \fi}
  7728. \end{exercise}
  7729. \clearpage
  7730. \section{Select Instructions}
  7731. \label{sec:select-Lif}
  7732. \index{subject}{instruction selection}
  7733. The \code{select\_instructions} pass translates \LangCIf{} to
  7734. \LangXIfVar{}.
  7735. %
  7736. \racket{Recall that we implement this pass using three auxiliary
  7737. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7738. $\Tail$.}
  7739. %
  7740. \racket{For $\Atm$, we have new cases for the Booleans.}
  7741. %
  7742. \python{We begin with the Boolean constants.}
  7743. We take the usual approach of encoding them as integers.
  7744. \[
  7745. \TRUE{} \quad\Rightarrow\quad \key{1}
  7746. \qquad\qquad
  7747. \FALSE{} \quad\Rightarrow\quad \key{0}
  7748. \]
  7749. For translating statements, we discuss a couple cases. The \code{not}
  7750. operation can be implemented in terms of \code{xorq} as we discussed
  7751. at the beginning of this section. Given an assignment, if the
  7752. left-hand side variable is the same as the argument of \code{not},
  7753. then just the \code{xorq} instruction suffices.
  7754. \[
  7755. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7756. \quad\Rightarrow\quad
  7757. \key{xorq}~\key{\$}1\key{,}~\Var
  7758. \]
  7759. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7760. semantics of x86. In the following translation, let $\Arg$ be the
  7761. result of translating $\Atm$ to x86.
  7762. \[
  7763. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7764. \quad\Rightarrow\quad
  7765. \begin{array}{l}
  7766. \key{movq}~\Arg\key{,}~\Var\\
  7767. \key{xorq}~\key{\$}1\key{,}~\Var
  7768. \end{array}
  7769. \]
  7770. Next consider the cases for equality. Translating this operation to
  7771. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7772. instruction discussed above. We recommend translating an assignment
  7773. with an equality on the right-hand side into a sequence of three
  7774. instructions. \\
  7775. \begin{tabular}{lll}
  7776. \begin{minipage}{0.4\textwidth}
  7777. \begin{lstlisting}
  7778. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7779. \end{lstlisting}
  7780. \end{minipage}
  7781. &
  7782. $\Rightarrow$
  7783. &
  7784. \begin{minipage}{0.4\textwidth}
  7785. \begin{lstlisting}
  7786. cmpq |$\Arg_2$|, |$\Arg_1$|
  7787. sete %al
  7788. movzbq %al, |$\Var$|
  7789. \end{lstlisting}
  7790. \end{minipage}
  7791. \end{tabular} \\
  7792. The translations for the other comparison operators are similar to the
  7793. above but use different suffixes for the \code{set} instruction.
  7794. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7795. \key{goto} and \key{if} statements. Both are straightforward to
  7796. translate to x86.}
  7797. %
  7798. A \key{goto} statement becomes a jump instruction.
  7799. \[
  7800. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7801. \]
  7802. %
  7803. An \key{if} statement becomes a compare instruction followed by a
  7804. conditional jump (for the ``then'' branch) and the fall-through is to
  7805. a regular jump (for the ``else'' branch).\\
  7806. \begin{tabular}{lll}
  7807. \begin{minipage}{0.4\textwidth}
  7808. \begin{lstlisting}
  7809. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7810. goto |$\ell_1$||$\racket{\key{;}}$|
  7811. else|$\python{\key{:}}$|
  7812. goto |$\ell_2$||$\racket{\key{;}}$|
  7813. \end{lstlisting}
  7814. \end{minipage}
  7815. &
  7816. $\Rightarrow$
  7817. &
  7818. \begin{minipage}{0.4\textwidth}
  7819. \begin{lstlisting}
  7820. cmpq |$\Arg_2$|, |$\Arg_1$|
  7821. je |$\ell_1$|
  7822. jmp |$\ell_2$|
  7823. \end{lstlisting}
  7824. \end{minipage}
  7825. \end{tabular} \\
  7826. Again, the translations for the other comparison operators are similar to the
  7827. above but use different suffixes for the conditional jump instruction.
  7828. \python{Regarding the \key{return} statement, we recommend treating it
  7829. as an assignment to the \key{rax} register followed by a jump to the
  7830. conclusion of the \code{main} function.}
  7831. \begin{exercise}\normalfont
  7832. Expand your \code{select\_instructions} pass to handle the new
  7833. features of the \LangIf{} language.
  7834. %
  7835. {\if\edition\racketEd
  7836. Add the following entry to the list of \code{passes} in
  7837. \code{run-tests.rkt}
  7838. \begin{lstlisting}
  7839. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  7840. \end{lstlisting}
  7841. \fi}
  7842. %
  7843. Run the script to test your compiler on all the test programs.
  7844. \end{exercise}
  7845. \section{Register Allocation}
  7846. \label{sec:register-allocation-Lif}
  7847. \index{subject}{register allocation}
  7848. The changes required for \LangIf{} affect liveness analysis, building the
  7849. interference graph, and assigning homes, but the graph coloring
  7850. algorithm itself does not change.
  7851. \subsection{Liveness Analysis}
  7852. \label{sec:liveness-analysis-Lif}
  7853. \index{subject}{liveness analysis}
  7854. Recall that for \LangVar{} we implemented liveness analysis for a
  7855. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  7856. the addition of \key{if} expressions to \LangIf{},
  7857. \code{explicate\_control} produces many basic blocks.
  7858. %% We recommend that you create a new auxiliary function named
  7859. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  7860. %% control-flow graph.
  7861. The first question is: what order should we process the basic blocks?
  7862. Recall that to perform liveness analysis on a basic block we need to
  7863. know the live-after set for the last instruction in the block. If a
  7864. basic block has no successors (i.e. contains no jumps to other
  7865. blocks), then it has an empty live-after set and we can immediately
  7866. apply liveness analysis to it. If a basic block has some successors,
  7867. then we need to complete liveness analysis on those blocks
  7868. first. These ordering contraints are the reverse of a
  7869. \emph{topological order}\index{subject}{topological order} on a graph
  7870. representation of the program. In particular, the \emph{control flow
  7871. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  7872. of a program has a node for each basic block and an edge for each jump
  7873. from one block to another. It is straightforward to generate a CFG
  7874. from the dictionary of basic blocks. One then transposes the CFG and
  7875. applies the topological sort algorithm.
  7876. %
  7877. %
  7878. \racket{We recommend using the \code{tsort} and \code{transpose}
  7879. functions of the Racket \code{graph} package to accomplish this.}
  7880. %
  7881. \python{We provide implementations of \code{topological\_sort} and
  7882. \code{transpose} in the file \code{graph.py} of the support code.}
  7883. %
  7884. As an aside, a topological ordering is only guaranteed to exist if the
  7885. graph does not contain any cycles. This is the case for the
  7886. control-flow graphs that we generate from \LangIf{} programs.
  7887. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  7888. and learn how to handle cycles in the control-flow graph.
  7889. \racket{You'll need to construct a directed graph to represent the
  7890. control-flow graph. Do not use the \code{directed-graph} of the
  7891. \code{graph} package because that only allows at most one edge
  7892. between each pair of vertices, but a control-flow graph may have
  7893. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  7894. file in the support code implements a graph representation that
  7895. allows multiple edges between a pair of vertices.}
  7896. {\if\edition\racketEd
  7897. The next question is how to analyze jump instructions. Recall that in
  7898. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  7899. \code{label->live} that maps each label to the set of live locations
  7900. at the beginning of its block. We use \code{label->live} to determine
  7901. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  7902. that we have many basic blocks, \code{label->live} needs to be updated
  7903. as we process the blocks. In particular, after performing liveness
  7904. analysis on a block, we take the live-before set of its first
  7905. instruction and associate that with the block's label in the
  7906. \code{label->live}.
  7907. \fi}
  7908. %
  7909. {\if\edition\pythonEd
  7910. %
  7911. The next question is how to analyze jump instructions. The locations
  7912. that are live before a \code{jmp} should be the locations in
  7913. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  7914. maintaining a dictionary named \code{live\_before\_block} that maps each
  7915. label to the $L_{\mathtt{before}}$ for the first instruction in its
  7916. block. After performing liveness analysis on each block, we take the
  7917. live-before set of its first instruction and associate that with the
  7918. block's label in the \code{live\_before\_block} dictionary.
  7919. %
  7920. \fi}
  7921. In \LangXIfVar{} we also have the conditional jump
  7922. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  7923. this instruction is particularly interesting because, during
  7924. compilation, we do not know which way a conditional jump will go. So
  7925. we do not know whether to use the live-before set for the following
  7926. instruction or the live-before set for the block associated with the
  7927. $\itm{label}$. However, there is no harm to the correctness of the
  7928. generated code if we classify more locations as live than the ones
  7929. that are truly live during one particular execution of the
  7930. instruction. Thus, we can take the union of the live-before sets from
  7931. the following instruction and from the mapping for $\itm{label}$ in
  7932. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  7933. The auxiliary functions for computing the variables in an
  7934. instruction's argument and for computing the variables read-from ($R$)
  7935. or written-to ($W$) by an instruction need to be updated to handle the
  7936. new kinds of arguments and instructions in \LangXIfVar{}.
  7937. \begin{exercise}\normalfont
  7938. {\if\edition\racketEd
  7939. %
  7940. Update the \code{uncover\_live} pass to apply liveness analysis to
  7941. every basic block in the program.
  7942. %
  7943. Add the following entry to the list of \code{passes} in the
  7944. \code{run-tests.rkt} script.
  7945. \begin{lstlisting}
  7946. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  7947. \end{lstlisting}
  7948. \fi}
  7949. {\if\edition\pythonEd
  7950. %
  7951. Update the \code{uncover\_live} function to perform liveness analysis,
  7952. in reverse topological order, on all of the basic blocks in the
  7953. program.
  7954. %
  7955. \fi}
  7956. % Check that the live-after sets that you generate for
  7957. % example X matches the following... -Jeremy
  7958. \end{exercise}
  7959. \subsection{Build the Interference Graph}
  7960. \label{sec:build-interference-Lif}
  7961. Many of the new instructions in \LangXIfVar{} can be handled in the
  7962. same way as the instructions in \LangXVar{}. Thus, if your code was
  7963. already quite general, it will not need to be changed to handle the
  7964. new instructions. If you code is not general enough, we recommend that
  7965. you change your code to be more general. For example, you can factor
  7966. out the computing of the the read and write sets for each kind of
  7967. instruction into auxiliary functions.
  7968. Note that the \key{movzbq} instruction requires some special care,
  7969. similar to the \key{movq} instruction. See rule number 1 in
  7970. Section~\ref{sec:build-interference}.
  7971. \begin{exercise}\normalfont
  7972. Update the \code{build\_interference} pass for \LangXIfVar{}.
  7973. {\if\edition\racketEd
  7974. Add the following entries to the list of \code{passes} in the
  7975. \code{run-tests.rkt} script.
  7976. \begin{lstlisting}
  7977. (list "build_interference" build_interference interp-pseudo-x86-1)
  7978. (list "allocate_registers" allocate_registers interp-x86-1)
  7979. \end{lstlisting}
  7980. \fi}
  7981. % Check that the interference graph that you generate for
  7982. % example X matches the following graph G... -Jeremy
  7983. \end{exercise}
  7984. \section{Patch Instructions}
  7985. The new instructions \key{cmpq} and \key{movzbq} have some special
  7986. restrictions that need to be handled in the \code{patch\_instructions}
  7987. pass.
  7988. %
  7989. The second argument of the \key{cmpq} instruction must not be an
  7990. immediate value (such as an integer). So if you are comparing two
  7991. immediates, we recommend inserting a \key{movq} instruction to put the
  7992. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  7993. one memory reference.
  7994. %
  7995. The second argument of the \key{movzbq} must be a register.
  7996. \begin{exercise}\normalfont
  7997. %
  7998. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  7999. %
  8000. {\if\edition\racketEd
  8001. Add the following entry to the list of \code{passes} in
  8002. \code{run-tests.rkt} and then run this script to test your compiler.
  8003. \begin{lstlisting}
  8004. (list "patch_instructions" patch_instructions interp-x86-1)
  8005. \end{lstlisting}
  8006. \fi}
  8007. \end{exercise}
  8008. {\if\edition\pythonEd
  8009. \section{Prelude and Conclusion}
  8010. \label{sec:prelude-conclusion-cond}
  8011. The generation of the \code{main} function with its prelude and
  8012. conclusion must change to accomodate how the program now consists of
  8013. one or more basic blocks. After the prelude in \code{main}, jump to
  8014. the \code{start} block. Place the conclusion in a basic block labelled
  8015. with \code{conclusion}.
  8016. \fi}
  8017. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8018. \LangIf{} translated to x86, showing the results of
  8019. \code{explicate\_control}, \code{select\_instructions}, and the final
  8020. x86 assembly.
  8021. \begin{figure}[tbp]
  8022. {\if\edition\racketEd
  8023. \begin{tabular}{lll}
  8024. \begin{minipage}{0.4\textwidth}
  8025. % cond_test_20.rkt, eq_input.py
  8026. \begin{lstlisting}
  8027. (if (eq? (read) 1) 42 0)
  8028. \end{lstlisting}
  8029. $\Downarrow$
  8030. \begin{lstlisting}
  8031. start:
  8032. tmp7951 = (read);
  8033. if (eq? tmp7951 1)
  8034. goto block7952;
  8035. else
  8036. goto block7953;
  8037. block7952:
  8038. return 42;
  8039. block7953:
  8040. return 0;
  8041. \end{lstlisting}
  8042. $\Downarrow$
  8043. \begin{lstlisting}
  8044. start:
  8045. callq read_int
  8046. movq %rax, tmp7951
  8047. cmpq $1, tmp7951
  8048. je block7952
  8049. jmp block7953
  8050. block7953:
  8051. movq $0, %rax
  8052. jmp conclusion
  8053. block7952:
  8054. movq $42, %rax
  8055. jmp conclusion
  8056. \end{lstlisting}
  8057. \end{minipage}
  8058. &
  8059. $\Rightarrow\qquad$
  8060. \begin{minipage}{0.4\textwidth}
  8061. \begin{lstlisting}
  8062. start:
  8063. callq read_int
  8064. movq %rax, %rcx
  8065. cmpq $1, %rcx
  8066. je block7952
  8067. jmp block7953
  8068. block7953:
  8069. movq $0, %rax
  8070. jmp conclusion
  8071. block7952:
  8072. movq $42, %rax
  8073. jmp conclusion
  8074. .globl main
  8075. main:
  8076. pushq %rbp
  8077. movq %rsp, %rbp
  8078. pushq %r13
  8079. pushq %r12
  8080. pushq %rbx
  8081. pushq %r14
  8082. subq $0, %rsp
  8083. jmp start
  8084. conclusion:
  8085. addq $0, %rsp
  8086. popq %r14
  8087. popq %rbx
  8088. popq %r12
  8089. popq %r13
  8090. popq %rbp
  8091. retq
  8092. \end{lstlisting}
  8093. \end{minipage}
  8094. \end{tabular}
  8095. \fi}
  8096. {\if\edition\pythonEd
  8097. \begin{tabular}{lll}
  8098. \begin{minipage}{0.4\textwidth}
  8099. % cond_test_20.rkt, eq_input.py
  8100. \begin{lstlisting}
  8101. print(42 if input_int() == 1 else 0)
  8102. \end{lstlisting}
  8103. $\Downarrow$
  8104. \begin{lstlisting}
  8105. start:
  8106. tmp_0 = input_int()
  8107. if tmp_0 == 1:
  8108. goto block_3
  8109. else:
  8110. goto block_4
  8111. block_3:
  8112. tmp_1 = 42
  8113. goto block_2
  8114. block_4:
  8115. tmp_1 = 0
  8116. goto block_2
  8117. block_2:
  8118. print(tmp_1)
  8119. return 0
  8120. \end{lstlisting}
  8121. $\Downarrow$
  8122. \begin{lstlisting}
  8123. start:
  8124. callq read_int
  8125. movq %rax, tmp_0
  8126. cmpq 1, tmp_0
  8127. je block_3
  8128. jmp block_4
  8129. block_3:
  8130. movq 42, tmp_1
  8131. jmp block_2
  8132. block_4:
  8133. movq 0, tmp_1
  8134. jmp block_2
  8135. block_2:
  8136. movq tmp_1, %rdi
  8137. callq print_int
  8138. movq 0, %rax
  8139. jmp conclusion
  8140. \end{lstlisting}
  8141. \end{minipage}
  8142. &
  8143. $\Rightarrow\qquad$
  8144. \begin{minipage}{0.4\textwidth}
  8145. \begin{lstlisting}
  8146. .globl main
  8147. main:
  8148. pushq %rbp
  8149. movq %rsp, %rbp
  8150. subq $0, %rsp
  8151. jmp start
  8152. start:
  8153. callq read_int
  8154. movq %rax, %rcx
  8155. cmpq $1, %rcx
  8156. je block_3
  8157. jmp block_4
  8158. block_3:
  8159. movq $42, %rcx
  8160. jmp block_2
  8161. block_4:
  8162. movq $0, %rcx
  8163. jmp block_2
  8164. block_2:
  8165. movq %rcx, %rdi
  8166. callq print_int
  8167. movq $0, %rax
  8168. jmp conclusion
  8169. conclusion:
  8170. addq $0, %rsp
  8171. popq %rbp
  8172. retq
  8173. \end{lstlisting}
  8174. \end{minipage}
  8175. \end{tabular}
  8176. \fi}
  8177. \caption{Example compilation of an \key{if} expression to x86, showing
  8178. the results of \code{explicate\_control},
  8179. \code{select\_instructions}, and the final x86 assembly code. }
  8180. \label{fig:if-example-x86}
  8181. \end{figure}
  8182. \begin{figure}[tbp]
  8183. {\if\edition\racketEd
  8184. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8185. \node (Lif) at (0,2) {\large \LangIf{}};
  8186. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8187. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8188. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8189. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8190. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8191. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8192. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8193. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8194. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8195. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8196. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8197. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8198. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8199. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8200. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8201. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8202. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8203. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8204. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8205. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8206. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8207. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8208. \end{tikzpicture}
  8209. \fi}
  8210. {\if\edition\pythonEd
  8211. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8212. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8213. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8214. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8215. \node (C-1) at (3,0) {\large \LangCIf{}};
  8216. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8217. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8218. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8219. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8220. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8221. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8222. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8223. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8224. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8225. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8226. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8227. \end{tikzpicture}
  8228. \fi}
  8229. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8230. \label{fig:Lif-passes}
  8231. \end{figure}
  8232. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8233. compilation of \LangIf{}.
  8234. \section{Challenge: Optimize Blocks and Remove Jumps}
  8235. \label{sec:opt-jumps}
  8236. We discuss two optional challenges that involve optimizing the
  8237. control-flow of the program.
  8238. \subsection{Optimize Blocks}
  8239. The algorithm for \code{explicate\_control} that we discussed in
  8240. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8241. blocks. It does so in two different ways.
  8242. %
  8243. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8244. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8245. a new basic block from a single \code{goto} statement, whereas we
  8246. could have simply returned the \code{goto} statement. We can solve
  8247. this problem by modifying the \code{create\_block} function to
  8248. recognize this situation.
  8249. Second, \code{explicate\_control} creates a basic block whenever a
  8250. continuation \emph{might} get used more than once (wheneven a
  8251. continuation is passed into two or more recursive calls). However,
  8252. just because a continuation might get used more than once, doesn't
  8253. mean it will. In fact, some continuation parameters may not be used
  8254. at all because we sometimes ignore them. For example, consider the
  8255. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8256. discard the \code{els} branch. So the question is how can we decide
  8257. whether to create a basic block?
  8258. The solution to this conundrum is to use \emph{lazy
  8259. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8260. to delay creating a basic block until the point in time where we know
  8261. it will be used.
  8262. %
  8263. {\if\edition\racketEd
  8264. %
  8265. Racket provides support for
  8266. lazy evaluation with the
  8267. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8268. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8269. \index{subject}{delay} creates a
  8270. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8271. expressions is postponed. When \key{(force}
  8272. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8273. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8274. result of $e_n$ is cached in the promise and returned. If \code{force}
  8275. is applied again to the same promise, then the cached result is
  8276. returned. If \code{force} is applied to an argument that is not a
  8277. promise, \code{force} simply returns the argument.
  8278. %
  8279. \fi}
  8280. %
  8281. {\if\edition\pythonEd
  8282. %
  8283. While Python does not provide direct support for lazy evaluation, it
  8284. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8285. by wrapping it inside a function with no parameters. We can
  8286. \emph{force} its evaluation by calling the function. However, in some
  8287. cases of \code{explicate\_pred}, etc., we will return a list of
  8288. statements and in other cases we will return a function that computes
  8289. a list of statements. We use the term \emph{promise} to refer to a
  8290. value that may or may not be delayed. To uniformly deal with
  8291. promises, we define the following \code{force} function that checks
  8292. whether its input is delayed (i.e. whether it is a function) and then
  8293. either 1) calls the function, or 2) returns the input.
  8294. \begin{lstlisting}
  8295. def force(promise):
  8296. if isinstance(promise, types.FunctionType):
  8297. return promise()
  8298. else:
  8299. return promise
  8300. \end{lstlisting}
  8301. %
  8302. \fi}
  8303. We use promises for the input and output of the functions
  8304. \code{explicate\_pred}, \code{explicate\_assign},
  8305. %
  8306. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8307. %
  8308. So instead of taking and returning lists of statments, they take and
  8309. return promises. Furthermore, when we come to a situation in which a
  8310. continuation might be used more than once, as in the case for
  8311. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8312. that creates a basic block for each continuation (if there is not
  8313. already one) and then returns a \code{goto} statement to that basic
  8314. block.
  8315. %
  8316. {\if\edition\racketEd
  8317. %
  8318. The following auxiliary function named \code{create\_block} accomplishes
  8319. this task. It begins with \code{delay} to create a promise. When
  8320. forced, this promise will force the original promise. If that returns
  8321. a \code{goto} (because the block was already added to the control-flow
  8322. graph), then we return the \code{goto}. Otherwise we add the block to
  8323. the control-flow graph with another auxiliary function named
  8324. \code{add-node}. That function returns the label for the new block,
  8325. which we use to create a \code{goto}.
  8326. \begin{lstlisting}
  8327. (define (create_block tail)
  8328. (delay
  8329. (define t (force tail))
  8330. (match t
  8331. [(Goto label) (Goto label)]
  8332. [else (Goto (add-node t))])))
  8333. \end{lstlisting}
  8334. \fi}
  8335. {\if\edition\pythonEd
  8336. %
  8337. Here's the new version of the \code{create\_block} auxiliary function
  8338. that works on promises and that checks whether the block consists of a
  8339. solitary \code{goto} statement.\\
  8340. \begin{minipage}{\textwidth}
  8341. \begin{lstlisting}
  8342. def create_block(promise, basic_blocks):
  8343. stmts = force(promise)
  8344. match stmts:
  8345. case [Goto(l)]:
  8346. return Goto(l)
  8347. case _:
  8348. label = label_name(generate_name('block'))
  8349. basic_blocks[label] = stmts
  8350. return Goto(label)
  8351. \end{lstlisting}
  8352. \end{minipage}
  8353. \fi}
  8354. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8355. \code{explicate\_control} on the example of the nested \code{if}
  8356. expressions with the two improvements discussed above. As you can
  8357. see, the number of basic blocks has been reduced from 10 blocks (see
  8358. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8359. \begin{figure}[tbp]
  8360. {\if\edition\racketEd
  8361. \begin{tabular}{lll}
  8362. \begin{minipage}{0.4\textwidth}
  8363. % cond_test_41.rkt
  8364. \begin{lstlisting}
  8365. (let ([x (read)])
  8366. (let ([y (read)])
  8367. (if (if (< x 1)
  8368. (eq? x 0)
  8369. (eq? x 2))
  8370. (+ y 2)
  8371. (+ y 10))))
  8372. \end{lstlisting}
  8373. \end{minipage}
  8374. &
  8375. $\Rightarrow$
  8376. &
  8377. \begin{minipage}{0.55\textwidth}
  8378. \begin{lstlisting}
  8379. start:
  8380. x = (read);
  8381. y = (read);
  8382. if (< x 1) goto block40;
  8383. else goto block41;
  8384. block40:
  8385. if (eq? x 0) goto block38;
  8386. else goto block39;
  8387. block41:
  8388. if (eq? x 2) goto block38;
  8389. else goto block39;
  8390. block38:
  8391. return (+ y 2);
  8392. block39:
  8393. return (+ y 10);
  8394. \end{lstlisting}
  8395. \end{minipage}
  8396. \end{tabular}
  8397. \fi}
  8398. {\if\edition\pythonEd
  8399. \begin{tabular}{lll}
  8400. \begin{minipage}{0.4\textwidth}
  8401. % cond_test_41.rkt
  8402. \begin{lstlisting}
  8403. x = input_int()
  8404. y = input_int()
  8405. print(y + 2 \
  8406. if (x == 0 \
  8407. if x < 1 \
  8408. else x == 2) \
  8409. else y + 10)
  8410. \end{lstlisting}
  8411. \end{minipage}
  8412. &
  8413. $\Rightarrow$
  8414. &
  8415. \begin{minipage}{0.55\textwidth}
  8416. \begin{lstlisting}
  8417. start:
  8418. x = input_int()
  8419. y = input_int()
  8420. if x < 1:
  8421. goto block_4
  8422. else:
  8423. goto block_5
  8424. block_4:
  8425. if x == 0:
  8426. goto block_2
  8427. else:
  8428. goto block_3
  8429. block_5:
  8430. if x == 2:
  8431. goto block_2
  8432. else:
  8433. goto block_3
  8434. block_2:
  8435. tmp_0 = y + 2
  8436. goto block_1
  8437. block_3:
  8438. tmp_0 = y + 10
  8439. goto block_1
  8440. block_1:
  8441. print(tmp_0)
  8442. return 0
  8443. \end{lstlisting}
  8444. \end{minipage}
  8445. \end{tabular}
  8446. \fi}
  8447. \caption{Translation from \LangIf{} to \LangCIf{}
  8448. via the improved \code{explicate\_control}.}
  8449. \label{fig:explicate-control-challenge}
  8450. \end{figure}
  8451. %% Recall that in the example output of \code{explicate\_control} in
  8452. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8453. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8454. %% block. The first goal of this challenge assignment is to remove those
  8455. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8456. %% \code{explicate\_control} on the left and shows the result of bypassing
  8457. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8458. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8459. %% \code{block55}. The optimized code on the right of
  8460. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8461. %% \code{then} branch jumping directly to \code{block55}. The story is
  8462. %% similar for the \code{else} branch, as well as for the two branches in
  8463. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8464. %% have been optimized in this way, there are no longer any jumps to
  8465. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8466. %% \begin{figure}[tbp]
  8467. %% \begin{tabular}{lll}
  8468. %% \begin{minipage}{0.4\textwidth}
  8469. %% \begin{lstlisting}
  8470. %% block62:
  8471. %% tmp54 = (read);
  8472. %% if (eq? tmp54 2) then
  8473. %% goto block59;
  8474. %% else
  8475. %% goto block60;
  8476. %% block61:
  8477. %% tmp53 = (read);
  8478. %% if (eq? tmp53 0) then
  8479. %% goto block57;
  8480. %% else
  8481. %% goto block58;
  8482. %% block60:
  8483. %% goto block56;
  8484. %% block59:
  8485. %% goto block55;
  8486. %% block58:
  8487. %% goto block56;
  8488. %% block57:
  8489. %% goto block55;
  8490. %% block56:
  8491. %% return (+ 700 77);
  8492. %% block55:
  8493. %% return (+ 10 32);
  8494. %% start:
  8495. %% tmp52 = (read);
  8496. %% if (eq? tmp52 1) then
  8497. %% goto block61;
  8498. %% else
  8499. %% goto block62;
  8500. %% \end{lstlisting}
  8501. %% \end{minipage}
  8502. %% &
  8503. %% $\Rightarrow$
  8504. %% &
  8505. %% \begin{minipage}{0.55\textwidth}
  8506. %% \begin{lstlisting}
  8507. %% block62:
  8508. %% tmp54 = (read);
  8509. %% if (eq? tmp54 2) then
  8510. %% goto block55;
  8511. %% else
  8512. %% goto block56;
  8513. %% block61:
  8514. %% tmp53 = (read);
  8515. %% if (eq? tmp53 0) then
  8516. %% goto block55;
  8517. %% else
  8518. %% goto block56;
  8519. %% block56:
  8520. %% return (+ 700 77);
  8521. %% block55:
  8522. %% return (+ 10 32);
  8523. %% start:
  8524. %% tmp52 = (read);
  8525. %% if (eq? tmp52 1) then
  8526. %% goto block61;
  8527. %% else
  8528. %% goto block62;
  8529. %% \end{lstlisting}
  8530. %% \end{minipage}
  8531. %% \end{tabular}
  8532. %% \caption{Optimize jumps by removing trivial blocks.}
  8533. %% \label{fig:optimize-jumps}
  8534. %% \end{figure}
  8535. %% The name of this pass is \code{optimize-jumps}. We recommend
  8536. %% implementing this pass in two phases. The first phrase builds a hash
  8537. %% table that maps labels to possibly improved labels. The second phase
  8538. %% changes the target of each \code{goto} to use the improved label. If
  8539. %% the label is for a trivial block, then the hash table should map the
  8540. %% label to the first non-trivial block that can be reached from this
  8541. %% label by jumping through trivial blocks. If the label is for a
  8542. %% non-trivial block, then the hash table should map the label to itself;
  8543. %% we do not want to change jumps to non-trivial blocks.
  8544. %% The first phase can be accomplished by constructing an empty hash
  8545. %% table, call it \code{short-cut}, and then iterating over the control
  8546. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8547. %% then update the hash table, mapping the block's source to the target
  8548. %% of the \code{goto}. Also, the hash table may already have mapped some
  8549. %% labels to the block's source, to you must iterate through the hash
  8550. %% table and update all of those so that they instead map to the target
  8551. %% of the \code{goto}.
  8552. %% For the second phase, we recommend iterating through the $\Tail$ of
  8553. %% each block in the program, updating the target of every \code{goto}
  8554. %% according to the mapping in \code{short-cut}.
  8555. \begin{exercise}\normalfont
  8556. Implement the improvements to the \code{explicate\_control} pass.
  8557. Check that it removes trivial blocks in a few example programs. Then
  8558. check that your compiler still passes all of your tests.
  8559. \end{exercise}
  8560. \subsection{Remove Jumps}
  8561. There is an opportunity for removing jumps that is apparent in the
  8562. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8563. ends with a jump to \code{block\_4} and there are no other jumps to
  8564. \code{block\_4} in the rest of the program. In this situation we can
  8565. avoid the runtime overhead of this jump by merging \code{block\_4}
  8566. into the preceding block, in this case the \code{start} block.
  8567. Figure~\ref{fig:remove-jumps} shows the output of
  8568. \code{select\_instructions} on the left and the result of this
  8569. optimization on the right.
  8570. \begin{figure}[tbp]
  8571. {\if\edition\racketEd
  8572. \begin{tabular}{lll}
  8573. \begin{minipage}{0.5\textwidth}
  8574. % cond_test_20.rkt
  8575. \begin{lstlisting}
  8576. start:
  8577. callq read_int
  8578. movq %rax, tmp7951
  8579. cmpq $1, tmp7951
  8580. je block7952
  8581. jmp block7953
  8582. block7953:
  8583. movq $0, %rax
  8584. jmp conclusion
  8585. block7952:
  8586. movq $42, %rax
  8587. jmp conclusion
  8588. \end{lstlisting}
  8589. \end{minipage}
  8590. &
  8591. $\Rightarrow\qquad$
  8592. \begin{minipage}{0.4\textwidth}
  8593. \begin{lstlisting}
  8594. start:
  8595. callq read_int
  8596. movq %rax, tmp7951
  8597. cmpq $1, tmp7951
  8598. je block7952
  8599. movq $0, %rax
  8600. jmp conclusion
  8601. block7952:
  8602. movq $42, %rax
  8603. jmp conclusion
  8604. \end{lstlisting}
  8605. \end{minipage}
  8606. \end{tabular}
  8607. \fi}
  8608. {\if\edition\pythonEd
  8609. \begin{tabular}{lll}
  8610. \begin{minipage}{0.5\textwidth}
  8611. % cond_test_20.rkt
  8612. \begin{lstlisting}
  8613. start:
  8614. callq read_int
  8615. movq %rax, tmp_0
  8616. cmpq 1, tmp_0
  8617. je block_3
  8618. jmp block_4
  8619. block_3:
  8620. movq 42, tmp_1
  8621. jmp block_2
  8622. block_4:
  8623. movq 0, tmp_1
  8624. jmp block_2
  8625. block_2:
  8626. movq tmp_1, %rdi
  8627. callq print_int
  8628. movq 0, %rax
  8629. jmp conclusion
  8630. \end{lstlisting}
  8631. \end{minipage}
  8632. &
  8633. $\Rightarrow\qquad$
  8634. \begin{minipage}{0.4\textwidth}
  8635. \begin{lstlisting}
  8636. start:
  8637. callq read_int
  8638. movq %rax, tmp_0
  8639. cmpq 1, tmp_0
  8640. je block_3
  8641. movq 0, tmp_1
  8642. jmp block_2
  8643. block_3:
  8644. movq 42, tmp_1
  8645. jmp block_2
  8646. block_2:
  8647. movq tmp_1, %rdi
  8648. callq print_int
  8649. movq 0, %rax
  8650. jmp conclusion
  8651. \end{lstlisting}
  8652. \end{minipage}
  8653. \end{tabular}
  8654. \fi}
  8655. \caption{Merging basic blocks by removing unnecessary jumps.}
  8656. \label{fig:remove-jumps}
  8657. \end{figure}
  8658. \begin{exercise}\normalfont
  8659. %
  8660. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8661. into their preceding basic block, when there is only one preceding
  8662. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8663. %
  8664. {\if\edition\racketEd
  8665. In the \code{run-tests.rkt} script, add the following entry to the
  8666. list of \code{passes} between \code{allocate\_registers}
  8667. and \code{patch\_instructions}.
  8668. \begin{lstlisting}
  8669. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8670. \end{lstlisting}
  8671. \fi}
  8672. %
  8673. Run the script to test your compiler.
  8674. %
  8675. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8676. blocks on several test programs.
  8677. \end{exercise}
  8678. \section{Further Reading}
  8679. \label{sec:cond-further-reading}
  8680. The algorithm for the \code{explicate\_control} pass is based on the
  8681. the \code{explose-basic-blocks} pass in the course notes of
  8682. \citet{Dybvig:2010aa}.
  8683. %
  8684. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8685. \citet{Appel:2003fk}, and is related to translations into continuation
  8686. passing
  8687. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8688. %
  8689. The treatment of conditionals in the \code{explicate\_control} pass is
  8690. similar to short-cut boolean
  8691. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8692. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8693. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8694. \chapter{Loops and Dataflow Analysis}
  8695. \label{ch:Lwhile}
  8696. % TODO: define R'_8
  8697. % TODO: multi-graph
  8698. {\if\edition\racketEd
  8699. %
  8700. In this chapter we study two features that are the hallmarks of
  8701. imperative programming languages: loops and assignments to local
  8702. variables. The following example demonstrates these new features by
  8703. computing the sum of the first five positive integers.
  8704. % similar to loop_test_1.rkt
  8705. \begin{lstlisting}
  8706. (let ([sum 0])
  8707. (let ([i 5])
  8708. (begin
  8709. (while (> i 0)
  8710. (begin
  8711. (set! sum (+ sum i))
  8712. (set! i (- i 1))))
  8713. sum)))
  8714. \end{lstlisting}
  8715. The \code{while} loop consists of a condition and a
  8716. body\footnote{The \code{while} loop in particular is not a built-in
  8717. feature of the Racket language, but Racket includes many looping
  8718. constructs and it is straightforward to define \code{while} as a
  8719. macro.}. The body is evaluated repeatedly so long as the condition
  8720. remains true.
  8721. %
  8722. The \code{set!} consists of a variable and a right-hand-side
  8723. expression. The \code{set!} updates value of the variable to the
  8724. value of the right-hand-side.
  8725. %
  8726. The primary purpose of both the \code{while} loop and \code{set!} is
  8727. to cause side effects, so they do not have a meaningful result
  8728. value. Instead their result is the \code{\#<void>} value. The
  8729. expression \code{(void)} is an explicit way to create the
  8730. \code{\#<void>} value and it has type \code{Void}. The
  8731. \code{\#<void>} value can be passed around just like other values
  8732. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8733. compared for equality with another \code{\#<void>} value. However,
  8734. there are no other operations specific to the the \code{\#<void>}
  8735. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8736. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8737. \code{\#f} otherwise.
  8738. %
  8739. \footnote{Racket's \code{Void} type corresponds to what is called the
  8740. \code{Unit} type in the programming languages literature. Racket's
  8741. \code{Void} type is inhabited by a single value \code{\#<void>}
  8742. which corresponds to \code{unit} or \code{()} in the
  8743. literature~\citep{Pierce:2002hj}.}.
  8744. %
  8745. With the addition of side-effecting features such as \code{while} loop
  8746. and \code{set!}, it is helpful to also include in a language feature
  8747. for sequencing side effects: the \code{begin} expression. It consists
  8748. of one or more subexpressions that are evaluated left-to-right.
  8749. %
  8750. \fi}
  8751. {\if\edition\pythonEd
  8752. %
  8753. In this chapter we study loops, one of the hallmarks of imperative
  8754. programming languages. The following example demonstrates the
  8755. \code{while} loop by computing the sum of the first five positive
  8756. integers.
  8757. \begin{lstlisting}
  8758. sum = 0
  8759. i = 5
  8760. while i > 0:
  8761. sum = sum + i
  8762. i = i - 1
  8763. print(sum)
  8764. \end{lstlisting}
  8765. The \code{while} loop consists of a condition expression and a body (a
  8766. sequence of statements). The body is evaluated repeatedly so long as
  8767. the condition remains true.
  8768. %
  8769. \fi}
  8770. \section{The \LangLoop{} Language}
  8771. \newcommand{\LwhileGrammarRacket}{
  8772. \begin{array}{lcl}
  8773. \Type &::=& \key{Void}\\
  8774. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8775. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8776. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8777. \end{array}
  8778. }
  8779. \newcommand{\LwhileAST}{
  8780. \begin{array}{lcl}
  8781. \Type &::=& \key{Void}\\
  8782. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  8783. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  8784. \end{array}
  8785. }
  8786. \begin{figure}[tp]
  8787. \centering
  8788. \fbox{
  8789. \begin{minipage}{0.96\textwidth}
  8790. \small
  8791. {\if\edition\racketEd
  8792. \[
  8793. \begin{array}{l}
  8794. \gray{\LintGrammarRacket{}} \\ \hline
  8795. \gray{\LvarGrammarRacket{}} \\ \hline
  8796. \gray{\LifGrammarRacket{}} \\ \hline
  8797. \LwhileGrammarRacket \\
  8798. \begin{array}{lcl}
  8799. \LangLoopM{} &::=& \Exp
  8800. \end{array}
  8801. \end{array}
  8802. \]
  8803. \fi}
  8804. {\if\edition\pythonEd
  8805. \[
  8806. \begin{array}{rcl}
  8807. \itm{binaryop} &::= & \key{+} \MID \key{-} \MID \key{and} \MID \key{or} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  8808. \itm{unaryop} &::= & \key{-} \MID \key{not} \\
  8809. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \CUNIOP{\itm{unaryop}}{\Exp} \MID \CBINOP{\itm{binaryop}}{\Exp}{\Exp} \MID \Var{} \\
  8810. &\MID& \TRUE \MID \FALSE \MID \CIF{\Exp}{\Exp}{\Exp} \\
  8811. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \CASSIGN{\Var}{\Exp}
  8812. \MID \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}\\
  8813. &\MID& \key{while}~ \Exp \key{:}~ \Stmt^{+}\\
  8814. \LangLoopM{} &::=& \Stmt^{*}
  8815. \end{array}
  8816. \]
  8817. \fi}
  8818. \end{minipage}
  8819. }
  8820. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8821. \label{fig:Lwhile-concrete-syntax}
  8822. \end{figure}
  8823. \begin{figure}[tp]
  8824. \centering
  8825. \fbox{
  8826. \begin{minipage}{0.96\textwidth}
  8827. \small
  8828. {\if\edition\racketEd
  8829. \[
  8830. \begin{array}{l}
  8831. \gray{\LintOpAST} \\ \hline
  8832. \gray{\LvarAST{}} \\ \hline
  8833. \gray{\LifAST{}} \\ \hline
  8834. \LwhileAST{} \\
  8835. \begin{array}{lcl}
  8836. %% \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  8837. %% &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8838. %% &\MID& \gray{ \BOOL{\itm{bool}}
  8839. %% \MID \IF{\Exp}{\Exp}{\Exp} } \\
  8840. %% &\MID& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  8841. %% \MID \WHILE{\Exp}{\Exp} \\
  8842. %% &\MID& \VOID{} \\
  8843. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  8844. \end{array}
  8845. \end{array}
  8846. \]
  8847. \fi}
  8848. {\if\edition\pythonEd
  8849. \[
  8850. \begin{array}{lcl}
  8851. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  8852. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  8853. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  8854. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  8855. \itm{bool} &::=& \code{True} \MID \code{False} \\
  8856. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  8857. &\MID& \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  8858. \MID \UNIOP{\itm{unaryop}}{\Exp}\\
  8859. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  8860. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  8861. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8862. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  8863. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  8864. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}\\
  8865. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  8866. \end{array}
  8867. \]
  8868. \fi}
  8869. \end{minipage}
  8870. }
  8871. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  8872. \label{fig:Lwhile-syntax}
  8873. \end{figure}
  8874. The concrete syntax of \LangLoop{} is defined in
  8875. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  8876. in Figure~\ref{fig:Lwhile-syntax}.
  8877. %
  8878. The definitional interpreter for \LangLoop{} is shown in
  8879. Figure~\ref{fig:interp-Rwhile}.
  8880. %
  8881. {\if\edition\racketEd
  8882. %
  8883. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  8884. and \code{Void} and we make changes to the cases for \code{Var},
  8885. \code{Let}, and \code{Apply} regarding variables. To support
  8886. assignment to variables and to make their lifetimes indefinite (see
  8887. the second example in Section~\ref{sec:assignment-scoping}), we box
  8888. the value that is bound to each variable (in \code{Let}) and function
  8889. parameter (in \code{Apply}). The case for \code{Var} unboxes the
  8890. value.
  8891. %
  8892. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8893. variable in the environment to obtain a boxed value and then we change
  8894. it using \code{set-box!} to the result of evaluating the right-hand
  8895. side. The result value of a \code{SetBang} is \code{void}.
  8896. %
  8897. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8898. if the result is true, 2) evaluate the body.
  8899. The result value of a \code{while} loop is also \code{void}.
  8900. %
  8901. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8902. subexpressions \itm{es} for their effects and then evaluates
  8903. and returns the result from \itm{body}.
  8904. %
  8905. The $\VOID{}$ expression produces the \code{void} value.
  8906. %
  8907. \fi}
  8908. {\if\edition\pythonEd
  8909. %
  8910. We add a new case for \code{While} in the \code{interp\_stmts}
  8911. function, where we repeatedly interpret the \code{body} so long as the
  8912. \code{test} expression remains true.
  8913. %
  8914. \fi}
  8915. \begin{figure}[tbp]
  8916. {\if\edition\racketEd
  8917. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8918. (define interp-Rwhile_class
  8919. (class interp-Rany_class
  8920. (super-new)
  8921. (define/override ((interp-exp env) e)
  8922. (define recur (interp-exp env))
  8923. (match e
  8924. [(SetBang x rhs)
  8925. (set-box! (lookup x env) (recur rhs))]
  8926. [(WhileLoop cnd body)
  8927. (define (loop)
  8928. (cond [(recur cnd) (recur body) (loop)]
  8929. [else (void)]))
  8930. (loop)]
  8931. [(Begin es body)
  8932. (for ([e es]) (recur e))
  8933. (recur body)]
  8934. [(Void) (void)]
  8935. [else ((super interp-exp env) e)]))
  8936. ))
  8937. (define (interp-Rwhile p)
  8938. (send (new interp-Rwhile_class) interp-program p))
  8939. \end{lstlisting}
  8940. \fi}
  8941. {\if\edition\pythonEd
  8942. \begin{lstlisting}
  8943. class InterpLwhile(InterpLif):
  8944. def interp_stmts(self, ss, env):
  8945. if len(ss) == 0:
  8946. return
  8947. match ss[0]:
  8948. case While(test, body, []):
  8949. while self.interp_exp(test, env):
  8950. self.interp_stmts(body, env)
  8951. return self.interp_stmts(ss[1:], env)
  8952. case _:
  8953. return super().interp_stmts(ss, env)
  8954. \end{lstlisting}
  8955. \fi}
  8956. \caption{Interpreter for \LangLoop{}.}
  8957. \label{fig:interp-Rwhile}
  8958. \end{figure}
  8959. The type checker for \LangLoop{} is defined in
  8960. Figure~\ref{fig:type-check-Rwhile}.
  8961. %
  8962. {\if\edition\racketEd
  8963. %
  8964. For \LangLoop{} we add a type named \code{Void} and the only value of
  8965. this type is the \code{void} value.
  8966. %
  8967. The type checking of the \code{SetBang} expression requires the type of
  8968. the variable and the right-hand-side to agree. The result type is
  8969. \code{Void}. For \code{while}, the condition must be a
  8970. \code{Boolean}. The result type is also \code{Void}. For
  8971. \code{Begin}, the result type is the type of its last subexpression.
  8972. %
  8973. \fi}
  8974. %
  8975. {\if\edition\pythonEd
  8976. %
  8977. A \code{while} loop is well typed if the type of the \code{test}
  8978. expression is \code{bool} and the statements in the \code{body} are
  8979. well typed.
  8980. %
  8981. \fi}
  8982. \begin{figure}[tbp]
  8983. {\if\edition\racketEd
  8984. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8985. (define type-check-Rwhile_class
  8986. (class type-check-Rany_class
  8987. (super-new)
  8988. (inherit check-type-equal?)
  8989. (define/override (type-check-exp env)
  8990. (lambda (e)
  8991. (define recur (type-check-exp env))
  8992. (match e
  8993. [(SetBang x rhs)
  8994. (define-values (rhs^ rhsT) (recur rhs))
  8995. (define varT (dict-ref env x))
  8996. (check-type-equal? rhsT varT e)
  8997. (values (SetBang x rhs^) 'Void)]
  8998. [(WhileLoop cnd body)
  8999. (define-values (cnd^ Tc) (recur cnd))
  9000. (check-type-equal? Tc 'Boolean e)
  9001. (define-values (body^ Tbody) ((type-check-exp env) body))
  9002. (values (WhileLoop cnd^ body^) 'Void)]
  9003. [(Begin es body)
  9004. (define-values (es^ ts)
  9005. (for/lists (l1 l2) ([e es]) (recur e)))
  9006. (define-values (body^ Tbody) (recur body))
  9007. (values (Begin es^ body^) Tbody)]
  9008. [else ((super type-check-exp env) e)])))
  9009. ))
  9010. (define (type-check-Rwhile p)
  9011. (send (new type-check-Rwhile_class) type-check-program p))
  9012. \end{lstlisting}
  9013. \fi}
  9014. {\if\edition\pythonEd
  9015. \begin{lstlisting}
  9016. class TypeCheckLwhile(TypeCheckLif):
  9017. def type_check_stmts(self, ss, env):
  9018. if len(ss) == 0:
  9019. return
  9020. match ss[0]:
  9021. case While(test, body, []):
  9022. test_t = self.type_check_exp(test, env)
  9023. check_type_equal(bool, test_t, test)
  9024. body_t = self.type_check_stmts(body, env)
  9025. return self.type_check_stmts(ss[1:], env)
  9026. case _:
  9027. return super().type_check_stmts(ss, env)
  9028. \end{lstlisting}
  9029. \fi}
  9030. \caption{Type checker for the \LangLoop{} language.}
  9031. \label{fig:type-check-Rwhile}
  9032. \end{figure}
  9033. {\if\edition\racketEd
  9034. %
  9035. At first glance, the translation of these language features to x86
  9036. seems straightforward because the \LangCIf{} intermediate language
  9037. already supports all of the ingredients that we need: assignment,
  9038. \code{goto}, conditional branching, and sequencing. However, there are
  9039. complications that arise which we discuss in the next section. After
  9040. that we introduce the changes necessary to the existing passes.
  9041. %
  9042. \fi}
  9043. {\if\edition\pythonEd
  9044. %
  9045. At first glance, the translation of \code{while} loops to x86 seems
  9046. straightforward because the \LangCIf{} intermediate language already
  9047. supports \code{goto} and conditional branching. However, there are
  9048. complications that arise which we discuss in the next section. After
  9049. that we introduce the changes necessary to the existing passes.
  9050. %
  9051. \fi}
  9052. \section{Cyclic Control Flow and Dataflow Analysis}
  9053. \label{sec:dataflow-analysis}
  9054. Up until this point the control-flow graphs of the programs generated
  9055. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9056. each \code{while} loop introduces a cycle in the control-flow graph.
  9057. But does that matter?
  9058. %
  9059. Indeed it does. Recall that for register allocation, the compiler
  9060. performs liveness analysis to determine which variables can share the
  9061. same register. To accomplish this we analyzed the control-flow graph
  9062. in reverse topological order
  9063. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9064. only well-defined for acyclic graphs.
  9065. Let us return to the example of computing the sum of the first five
  9066. positive integers. Here is the program after instruction selection but
  9067. before register allocation.
  9068. \begin{center}
  9069. {\if\edition\racketEd
  9070. \begin{minipage}{0.45\textwidth}
  9071. \begin{lstlisting}
  9072. (define (main) : Integer
  9073. mainstart:
  9074. movq $0, sum
  9075. movq $5, i
  9076. jmp block5
  9077. block5:
  9078. movq i, tmp3
  9079. cmpq tmp3, $0
  9080. jl block7
  9081. jmp block8
  9082. \end{lstlisting}
  9083. \end{minipage}
  9084. \begin{minipage}{0.45\textwidth}
  9085. \begin{lstlisting}
  9086. block7:
  9087. addq i, sum
  9088. movq $1, tmp4
  9089. negq tmp4
  9090. addq tmp4, i
  9091. jmp block5
  9092. block8:
  9093. movq $27, %rax
  9094. addq sum, %rax
  9095. jmp mainconclusion
  9096. )
  9097. \end{lstlisting}
  9098. \end{minipage}
  9099. \fi}
  9100. {\if\edition\pythonEd
  9101. \begin{minipage}{0.45\textwidth}
  9102. \begin{lstlisting}
  9103. mainstart:
  9104. movq $0, sum
  9105. movq $5, i
  9106. jmp block5
  9107. block5:
  9108. cmpq $0, i
  9109. jg block7
  9110. jmp block8
  9111. \end{lstlisting}
  9112. \end{minipage}
  9113. \begin{minipage}{0.45\textwidth}
  9114. \begin{lstlisting}
  9115. block7:
  9116. addq i, sum
  9117. subq $1, i
  9118. jmp block5
  9119. block8:
  9120. movq sum, %rdi
  9121. callq print_int
  9122. movq $0, %rax
  9123. jmp mainconclusion
  9124. \end{lstlisting}
  9125. \end{minipage}
  9126. \fi}
  9127. \end{center}
  9128. Recall that liveness analysis works backwards, starting at the end
  9129. of each function. For this example we could start with \code{block8}
  9130. because we know what is live at the beginning of the conclusion,
  9131. just \code{rax} and \code{rsp}. So the live-before set
  9132. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9133. %
  9134. Next we might try to analyze \code{block5} or \code{block7}, but
  9135. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9136. we are stuck.
  9137. The way out of this impasse is to realize that we can compute an
  9138. under-approximation of the live-before set by starting with empty
  9139. live-after sets. By \emph{under-approximation}, we mean that the set
  9140. only contains variables that are live for some execution of the
  9141. program, but the set may be missing some variables. Next, the
  9142. under-approximations for each block can be improved by 1) updating the
  9143. live-after set for each block using the approximate live-before sets
  9144. from the other blocks and 2) perform liveness analysis again on each
  9145. block. In fact, by iterating this process, the under-approximations
  9146. eventually become the correct solutions!
  9147. %
  9148. This approach of iteratively analyzing a control-flow graph is
  9149. applicable to many static analysis problems and goes by the name
  9150. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9151. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9152. Washington.
  9153. Let us apply this approach to the above example. We use the empty set
  9154. for the initial live-before set for each block. Let $m_0$ be the
  9155. following mapping from label names to sets of locations (variables and
  9156. registers).
  9157. \begin{center}
  9158. \begin{lstlisting}
  9159. mainstart: {}, block5: {}, block7: {}, block8: {}
  9160. \end{lstlisting}
  9161. \end{center}
  9162. Using the above live-before approximations, we determine the
  9163. live-after for each block and then apply liveness analysis to each
  9164. block. This produces our next approximation $m_1$ of the live-before
  9165. sets.
  9166. \begin{center}
  9167. \begin{lstlisting}
  9168. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9169. \end{lstlisting}
  9170. \end{center}
  9171. For the second round, the live-after for \code{mainstart} is the
  9172. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9173. liveness analysis for \code{mainstart} computes the empty set. The
  9174. live-after for \code{block5} is the union of the live-before sets for
  9175. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9176. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9177. sum\}}. The live-after for \code{block7} is the live-before for
  9178. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9179. So the liveness analysis for \code{block7} remains \code{\{i,
  9180. sum\}}. Together these yield the following approximation $m_2$ of
  9181. the live-before sets.
  9182. \begin{center}
  9183. \begin{lstlisting}
  9184. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9185. \end{lstlisting}
  9186. \end{center}
  9187. In the preceding iteration, only \code{block5} changed, so we can
  9188. limit our attention to \code{mainstart} and \code{block7}, the two
  9189. blocks that jump to \code{block5}. As a result, the live-before sets
  9190. for \code{mainstart} and \code{block7} are updated to include
  9191. \code{rsp}, yielding the following approximation $m_3$.
  9192. \begin{center}
  9193. \begin{lstlisting}
  9194. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9195. \end{lstlisting}
  9196. \end{center}
  9197. Because \code{block7} changed, we analyze \code{block5} once more, but
  9198. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9199. our approximations have converged, so $m_3$ is the solution.
  9200. This iteration process is guaranteed to converge to a solution by the
  9201. Kleene Fixed-Point Theorem, a general theorem about functions on
  9202. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9203. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9204. elements, a least element $\bot$ (pronounced bottom), and a join
  9205. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9206. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9207. working with join semi-lattices.} When two elements are ordered $m_i
  9208. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9209. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9210. approximation than $m_i$. The bottom element $\bot$ represents the
  9211. complete lack of information, i.e., the worst approximation. The join
  9212. operator takes two lattice elements and combines their information,
  9213. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9214. bound}
  9215. A dataflow analysis typically involves two lattices: one lattice to
  9216. represent abstract states and another lattice that aggregates the
  9217. abstract states of all the blocks in the control-flow graph. For
  9218. liveness analysis, an abstract state is a set of locations. We form
  9219. the lattice $L$ by taking its elements to be sets of locations, the
  9220. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9221. set, and the join operator to be set union.
  9222. %
  9223. We form a second lattice $M$ by taking its elements to be mappings
  9224. from the block labels to sets of locations (elements of $L$). We
  9225. order the mappings point-wise, using the ordering of $L$. So given any
  9226. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9227. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9228. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9229. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9230. We can think of one iteration of liveness analysis applied to the
  9231. whole program as being a function $f$ on the lattice $M$. It takes a
  9232. mapping as input and computes a new mapping.
  9233. \[
  9234. f(m_i) = m_{i+1}
  9235. \]
  9236. Next let us think for a moment about what a final solution $m_s$
  9237. should look like. If we perform liveness analysis using the solution
  9238. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9239. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9240. \[
  9241. f(m_s) = m_s
  9242. \]
  9243. Furthermore, the solution should only include locations that are
  9244. forced to be there by performing liveness analysis on the program, so
  9245. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9246. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9247. monotone (better inputs produce better outputs), then the least fixed
  9248. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9249. chain} obtained by starting at $\bot$ and iterating $f$ as
  9250. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9251. \[
  9252. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9253. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9254. \]
  9255. When a lattice contains only finitely-long ascending chains, then
  9256. every Kleene chain tops out at some fixed point after some number of
  9257. iterations of $f$.
  9258. \[
  9259. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9260. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9261. \]
  9262. The liveness analysis is indeed a monotone function and the lattice
  9263. $M$ only has finitely-long ascending chains because there are only a
  9264. finite number of variables and blocks in the program. Thus we are
  9265. guaranteed that iteratively applying liveness analysis to all blocks
  9266. in the program will eventually produce the least fixed point solution.
  9267. Next let us consider dataflow analysis in general and discuss the
  9268. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9269. %
  9270. The algorithm has four parameters: the control-flow graph \code{G}, a
  9271. function \code{transfer} that applies the analysis to one block, the
  9272. \code{bottom} and \code{join} operator for the lattice of abstract
  9273. states. The algorithm begins by creating the bottom mapping,
  9274. represented by a hash table. It then pushes all of the nodes in the
  9275. control-flow graph onto the work list (a queue). The algorithm repeats
  9276. the \code{while} loop as long as there are items in the work list. In
  9277. each iteration, a node is popped from the work list and processed. The
  9278. \code{input} for the node is computed by taking the join of the
  9279. abstract states of all the predecessor nodes. The \code{transfer}
  9280. function is then applied to obtain the \code{output} abstract
  9281. state. If the output differs from the previous state for this block,
  9282. the mapping for this block is updated and its successor nodes are
  9283. pushed onto the work list.
  9284. Note that the \code{analyze\_dataflow} function is formulated as a
  9285. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9286. function come from the predecessor nodes in the control-flow
  9287. graph. However, liveness analysis is a \emph{backward} dataflow
  9288. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9289. function with the transpose of the control-flow graph.
  9290. \begin{figure}[tb]
  9291. {\if\edition\racketEd
  9292. \begin{lstlisting}
  9293. (define (analyze_dataflow G transfer bottom join)
  9294. (define mapping (make-hash))
  9295. (for ([v (in-vertices G)])
  9296. (dict-set! mapping v bottom))
  9297. (define worklist (make-queue))
  9298. (for ([v (in-vertices G)])
  9299. (enqueue! worklist v))
  9300. (define trans-G (transpose G))
  9301. (while (not (queue-empty? worklist))
  9302. (define node (dequeue! worklist))
  9303. (define input (for/fold ([state bottom])
  9304. ([pred (in-neighbors trans-G node)])
  9305. (join state (dict-ref mapping pred))))
  9306. (define output (transfer node input))
  9307. (cond [(not (equal? output (dict-ref mapping node)))
  9308. (dict-set! mapping node output)
  9309. (for ([v (in-neighbors G node)])
  9310. (enqueue! worklist v))]))
  9311. mapping)
  9312. \end{lstlisting}
  9313. \fi}
  9314. {\if\edition\pythonEd
  9315. \begin{lstlisting}
  9316. def analyze_dataflow(G, transfer, bottom, join):
  9317. trans_G = transpose(G)
  9318. mapping = {}
  9319. for v in G.vertices():
  9320. mapping[v] = bottom
  9321. worklist = deque()
  9322. for v in G.vertices():
  9323. worklist.append(v)
  9324. while worklist:
  9325. node = worklist.pop()
  9326. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9327. output = transfer(node, input)
  9328. if output != mapping[node]:
  9329. mapping[node] = output
  9330. for v in G.adjacent(node):
  9331. worklist.append(v)
  9332. \end{lstlisting}
  9333. \fi}
  9334. \caption{Generic work list algorithm for dataflow analysis}
  9335. \label{fig:generic-dataflow}
  9336. \end{figure}
  9337. {\if\edition\racketEd
  9338. \section{Mutable Variables \& Remove Complex Operands}
  9339. There is a subtle interaction between the addition of \code{set!}, the
  9340. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9341. evaluation of Racket. Consider the following example.
  9342. \begin{lstlisting}
  9343. (let ([x 2])
  9344. (+ x (begin (set! x 40) x)))
  9345. \end{lstlisting}
  9346. The result of this program is \code{42} because the first read from
  9347. \code{x} produces \code{2} and the second produces \code{40}. However,
  9348. if we naively apply the \code{remove\_complex\_operands} pass to this
  9349. example we obtain the following program whose result is \code{80}!
  9350. \begin{lstlisting}
  9351. (let ([x 2])
  9352. (let ([tmp (begin (set! x 40) x)])
  9353. (+ x tmp)))
  9354. \end{lstlisting}
  9355. The problem is that, with mutable variables, the ordering between
  9356. reads and writes is important, and the
  9357. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9358. before the first read of \code{x}.
  9359. We recommend solving this problem by giving special treatment to reads
  9360. from mutable variables, that is, variables that occur on the left-hand
  9361. side of a \code{set!}. We mark each read from a mutable variable with
  9362. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9363. that the read operation is effectful in that it can produce different
  9364. results at different points in time. Let's apply this idea to the
  9365. following variation that also involves a variable that is not mutated.
  9366. % loop_test_24.rkt
  9367. \begin{lstlisting}
  9368. (let ([x 2])
  9369. (let ([y 0])
  9370. (+ y (+ x (begin (set! x 40) x)))))
  9371. \end{lstlisting}
  9372. We analyze the above program to discover that variable \code{x} is
  9373. mutable but \code{y} is not. We then transform the program as follows,
  9374. replacing each occurence of \code{x} with \code{(get! x)}.
  9375. \begin{lstlisting}
  9376. (let ([x 2])
  9377. (let ([y 0])
  9378. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9379. \end{lstlisting}
  9380. Now that we have a clear distinction between reads from mutable and
  9381. immutable variables, we can apply the \code{remove\_complex\_operands}
  9382. pass, where reads from immutable variables are still classified as
  9383. atomic expressions but reads from mutable variables are classified as
  9384. complex. Thus, \code{remove\_complex\_operands} yields the following
  9385. program.
  9386. \begin{lstlisting}
  9387. (let ([x 2])
  9388. (let ([y 0])
  9389. (+ y (let ([t1 (get! x)])
  9390. (let ([t2 (begin (set! x 40) (get! x))])
  9391. (+ t1 t2))))))
  9392. \end{lstlisting}
  9393. The temporary variable \code{t1} gets the value of \code{x} before the
  9394. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9395. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9396. do not generate a temporary variable for the occurence of \code{y}
  9397. because it's an immutable variable. We want to avoid such unnecessary
  9398. extra temporaries because they would needless increase the number of
  9399. variables, making it more likely for some of them to be spilled. The
  9400. result of this program is \code{42}, the same as the result prior to
  9401. \code{remove\_complex\_operands}.
  9402. The approach that we've sketched above requires only a small
  9403. modification to \code{remove\_complex\_operands} to handle
  9404. \code{get!}. However, it requires a new pass, called
  9405. \code{uncover-get!}, that we discuss in
  9406. Section~\ref{sec:uncover-get-bang}.
  9407. As an aside, this problematic interaction between \code{set!} and the
  9408. pass \code{remove\_complex\_operands} is particular to Racket and not
  9409. its predecessor, the Scheme language. The key difference is that
  9410. Scheme does not specify an order of evaluation for the arguments of an
  9411. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9412. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9413. would be correct results for the example program. Interestingly,
  9414. Racket is implemented on top of the Chez Scheme
  9415. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9416. presented in this section (using extra \code{let} bindings to control
  9417. the order of evaluation) is used in the translation from Racket to
  9418. Scheme~\citep{Flatt:2019tb}.
  9419. \fi} % racket
  9420. Having discussed the complications that arise from adding support for
  9421. assignment and loops, we turn to discussing the individual compilation
  9422. passes.
  9423. {\if\edition\racketEd
  9424. \section{Uncover \texttt{get!}}
  9425. \label{sec:uncover-get-bang}
  9426. The goal of this pass it to mark uses of mutable variables so that
  9427. \code{remove\_complex\_operands} can treat them as complex expressions
  9428. and thereby preserve their ordering relative to the side-effects in
  9429. other operands. So the first step is to collect all the mutable
  9430. variables. We recommend creating an auxilliary function for this,
  9431. named \code{collect-set!}, that recursively traverses expressions,
  9432. returning a set of all variables that occur on the left-hand side of a
  9433. \code{set!}. Here's an exerpt of its implementation.
  9434. \begin{center}
  9435. \begin{minipage}{\textwidth}
  9436. \begin{lstlisting}
  9437. (define (collect-set! e)
  9438. (match e
  9439. [(Var x) (set)]
  9440. [(Int n) (set)]
  9441. [(Let x rhs body)
  9442. (set-union (collect-set! rhs) (collect-set! body))]
  9443. [(SetBang var rhs)
  9444. (set-union (set var) (collect-set! rhs))]
  9445. ...))
  9446. \end{lstlisting}
  9447. \end{minipage}
  9448. \end{center}
  9449. By placing this pass after \code{uniquify}, we need not worry about
  9450. variable shadowing and our logic for \code{let} can remain simple, as
  9451. in the exerpt above.
  9452. The second step is to mark the occurences of the mutable variables
  9453. with the new \code{GetBang} AST node (\code{get!} in concrete
  9454. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9455. function, which takes two parameters: the set of mutable varaibles
  9456. \code{set!-vars}, and the expression \code{e} to be processed. The
  9457. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9458. mutable variable or leaves it alone if not.
  9459. \begin{center}
  9460. \begin{minipage}{\textwidth}
  9461. \begin{lstlisting}
  9462. (define ((uncover-get!-exp set!-vars) e)
  9463. (match e
  9464. [(Var x)
  9465. (if (set-member? set!-vars x)
  9466. (GetBang x)
  9467. (Var x))]
  9468. ...))
  9469. \end{lstlisting}
  9470. \end{minipage}
  9471. \end{center}
  9472. To wrap things up, define the \code{uncover-get!} function for
  9473. processing a whole program, using \code{collect-set!} to obtain the
  9474. set of mutable variables and then \code{uncover-get!-exp} to replace
  9475. their occurences with \code{GetBang}.
  9476. \fi}
  9477. \section{Remove Complex Operands}
  9478. \label{sec:rco-loop}
  9479. {\if\edition\racketEd
  9480. %
  9481. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9482. \code{while} are all complex expressions. The subexpressions of
  9483. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9484. %
  9485. \fi}
  9486. {\if\edition\pythonEd
  9487. %
  9488. The change needed for this pass is to add a case for the \code{while}
  9489. statement. The condition of a \code{while} loop is allowed to be a
  9490. complex expression, just like the condition of the \code{if}
  9491. statement.
  9492. %
  9493. \fi}
  9494. %
  9495. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9496. \LangLoopANF{} of this pass.
  9497. \begin{figure}[tp]
  9498. \centering
  9499. \fbox{
  9500. \begin{minipage}{0.96\textwidth}
  9501. \small
  9502. {\if\edition\racketEd
  9503. \[
  9504. \begin{array}{rcl}
  9505. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  9506. \MID \VOID{} } \\
  9507. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9508. &\MID& \GETBANG{\Var}
  9509. \MID \SETBANG{\Var}{\Exp} \\
  9510. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9511. \MID \WHILE{\Exp}{\Exp} \\
  9512. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9513. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9514. \end{array}
  9515. \]
  9516. \fi}
  9517. {\if\edition\pythonEd
  9518. \[
  9519. \begin{array}{rcl}
  9520. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9521. \Exp &::=& \Atm \MID \READ{} \\
  9522. &\MID& \BINOP{\itm{binaryop}}{\Atm}{\Atm} \MID \UNIOP{\key{unaryop}}{\Atm} \\
  9523. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9524. % &\MID& \LET{\Var}{\Exp}{\Exp}\\
  9525. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9526. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9527. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9528. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9529. \end{array}
  9530. \]
  9531. \fi}
  9532. \end{minipage}
  9533. }
  9534. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9535. \label{fig:Rwhile-anf-syntax}
  9536. \end{figure}
  9537. {\if\edition\racketEd
  9538. As usual, when a complex expression appears in a grammar position that
  9539. needs to be atomic, such as the argument of a primitive operator, we
  9540. must introduce a temporary variable and bind it to the complex
  9541. expression. This approach applies, unchanged, to handle the new
  9542. language forms. For example, in the following code there are two
  9543. \code{begin} expressions appearing as arguments to \code{+}. The
  9544. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9545. expressions have been bound to temporary variables. Recall that
  9546. \code{let} expressions in \LangLoopANF{} are allowed to have
  9547. arbitrary expressions in their right-hand-side expression, so it is
  9548. fine to place \code{begin} there.
  9549. \begin{center}
  9550. \begin{minipage}{\textwidth}
  9551. \begin{lstlisting}
  9552. (let ([x0 10])
  9553. (let ([y1 0])
  9554. (+ (+ (begin (set! y1 (read)) x0)
  9555. (begin (set! x0 (read)) y1))
  9556. x0)))
  9557. |$\Rightarrow$|
  9558. (let ([x0 10])
  9559. (let ([y1 0])
  9560. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9561. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9562. (let ([tmp4 (+ tmp2 tmp3)])
  9563. (+ tmp4 x0))))))
  9564. \end{lstlisting}
  9565. \end{minipage}
  9566. \end{center}
  9567. \fi}
  9568. \section{Explicate Control \racket{and \LangCLoop{}}}
  9569. \label{sec:explicate-loop}
  9570. {\if\edition\racketEd
  9571. Recall that in the \code{explicate\_control} pass we define one helper
  9572. function for each kind of position in the program. For the \LangVar{}
  9573. language of integers and variables we needed kinds of positions:
  9574. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9575. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9576. yet another kind of position: effect position. Except for the last
  9577. subexpression, the subexpressions inside a \code{begin} are evaluated
  9578. only for their effect. Their result values are discarded. We can
  9579. generate better code by taking this fact into account.
  9580. The output language of \code{explicate\_control} is \LangCLoop{}
  9581. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9582. \LangCLam{}. The only syntactic difference is that \code{Call} and
  9583. \code{read} may also appear as statements. The most significant
  9584. difference between \LangCLam{} and \LangCLoop{} is that the
  9585. control-flow graphs of the later may contain cycles.
  9586. \begin{figure}[tp]
  9587. \fbox{
  9588. \begin{minipage}{0.96\textwidth}
  9589. \small
  9590. \[
  9591. \begin{array}{lcl}
  9592. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9593. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  9594. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  9595. % &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  9596. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9597. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9598. \end{array}
  9599. \]
  9600. \end{minipage}
  9601. }
  9602. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9603. \label{fig:c7-syntax}
  9604. \end{figure}
  9605. The new auxiliary function \code{explicate\_effect} takes an
  9606. expression (in an effect position) and a continuation. The function
  9607. returns a $\Tail$ that includes the generated code for the input
  9608. expression followed by the continuation. If the expression is
  9609. obviously pure, that is, never causes side effects, then the
  9610. expression can be removed, so the result is just the continuation.
  9611. %
  9612. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9613. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9614. the loop. Recursively process the \itm{body} (in effect position)
  9615. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9616. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9617. \itm{body'} as the then-branch and the continuation block as the
  9618. else-branch. The result should be added to the control-flow graph with
  9619. the label \itm{loop}. The result for the whole \code{while} loop is a
  9620. \code{goto} to the \itm{loop} label.
  9621. The auxiliary functions for tail, assignment, and predicate positions
  9622. need to be updated. The three new language forms, \code{while},
  9623. \code{set!}, and \code{begin}, can appear in assignment and tail
  9624. positions. Only \code{begin} may appear in predicate positions; the
  9625. other two have result type \code{Void}.
  9626. \fi}
  9627. %
  9628. {\if\edition\pythonEd
  9629. %
  9630. The output of this pass is the language \LangCIf{}. No new language
  9631. features are needed in the output because a \code{while} loop can be
  9632. expressed in terms of \code{goto} and \code{if} statements, which are
  9633. already in \LangCIf{}.
  9634. %
  9635. Add a case for the \code{while} statement to the
  9636. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9637. the condition expression.
  9638. %
  9639. \fi}
  9640. {\if\edition\racketEd
  9641. \section{Select Instructions}
  9642. \label{sec:select-instructions-loop}
  9643. Only three small additions are needed in the
  9644. \code{select\_instructions} pass to handle the changes to
  9645. \LangCLoop{}. That is, a \code{Call} to \code{read} may now appear as a
  9646. stand-alone statement instead of only appearing on the right-hand
  9647. side of an assignment statement. The code generation is nearly
  9648. identical; just leave off the instruction for moving the result into
  9649. the left-hand side.
  9650. \fi}
  9651. \section{Register Allocation}
  9652. \label{sec:register-allocation-loop}
  9653. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9654. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9655. which complicates the liveness analysis needed for register
  9656. allocation.
  9657. \subsection{Liveness Analysis}
  9658. \label{sec:liveness-analysis-r8}
  9659. We recommend using the generic \code{analyze\_dataflow} function that
  9660. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9661. perform liveness analysis, replacing the code in
  9662. \code{uncover\_live} that processed the basic blocks in topological
  9663. order (Section~\ref{sec:liveness-analysis-Lif}).
  9664. The \code{analyze\_dataflow} function has four parameters.
  9665. \begin{enumerate}
  9666. \item The first parameter \code{G} should be a directed graph from the
  9667. \racket{
  9668. \code{racket/graph} package (see the sidebar in
  9669. Section~\ref{sec:build-interference})}
  9670. \python{\code{graph.py} file in the support code}
  9671. that represents the
  9672. control-flow graph.
  9673. \item The second parameter \code{transfer} is a function that applies
  9674. liveness analysis to a basic block. It takes two parameters: the
  9675. label for the block to analyze and the live-after set for that
  9676. block. The transfer function should return the live-before set for
  9677. the block.
  9678. %
  9679. \racket{Also, as a side-effect, it should update the block's
  9680. $\itm{info}$ with the liveness information for each instruction.}
  9681. %
  9682. \python{Also, as a side-effect, it should update the live-before and
  9683. live-after sets for each instruction.}
  9684. %
  9685. To implement the \code{transfer} function, you should be able to
  9686. reuse the code you already have for analyzing basic blocks.
  9687. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9688. \code{bottom} and \code{join} for the lattice of abstract states,
  9689. i.e. sets of locations. The bottom of the lattice is the empty set
  9690. and the join operator is set union.
  9691. \end{enumerate}
  9692. \begin{figure}[p]
  9693. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9694. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9695. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9696. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9697. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9698. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9699. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9700. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9701. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9702. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9703. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9704. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9705. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9706. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9707. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9708. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9709. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9710. %% \path[->,bend left=15] (Rfun) edge [above] node
  9711. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9712. \path[->,bend left=15] (Rfun) edge [above] node
  9713. {\ttfamily\footnotesize shrink} (Rfun-2);
  9714. \path[->,bend left=15] (Rfun-2) edge [above] node
  9715. {\ttfamily\footnotesize uniquify} (F1-4);
  9716. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9717. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9718. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9719. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9720. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9721. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9722. %% \path[->,bend right=15] (F1-2) edge [above] node
  9723. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9724. %% \path[->,bend right=15] (F1-3) edge [above] node
  9725. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9726. \path[->,bend left=15] (F1-4) edge [above] node
  9727. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9728. \path[->,bend left=15] (F1-5) edge [right] node
  9729. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9730. \path[->,bend left=15] (C3-2) edge [left] node
  9731. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9732. \path[->,bend right=15] (x86-2) edge [left] node
  9733. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9734. \path[->,bend right=15] (x86-2-1) edge [below] node
  9735. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9736. \path[->,bend right=15] (x86-2-2) edge [left] node
  9737. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9738. \path[->,bend left=15] (x86-3) edge [above] node
  9739. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9740. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9741. \end{tikzpicture}
  9742. \caption{Diagram of the passes for \LangLoop{}.}
  9743. \label{fig:Rwhile-passes}
  9744. \end{figure}
  9745. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9746. for the compilation of \LangLoop{}.
  9747. % Further Reading: dataflow analysis
  9748. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9749. \chapter{Tuples and Garbage Collection}
  9750. \label{ch:Lvec}
  9751. \index{subject}{tuple}
  9752. \index{subject}{vector}
  9753. \index{subject}{allocate}
  9754. \index{subject}{heap allocate}
  9755. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9756. %% all the IR grammars are spelled out! \\ --Jeremy}
  9757. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9758. %% the root stack. \\ --Jeremy}
  9759. In this chapter we study the implementation of
  9760. tuples\racket{, called vectors in Racket}.
  9761. %
  9762. This language feature is the first of ours to use the computer's
  9763. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9764. indefinite, that is, a tuple lives forever from the programmer's
  9765. viewpoint. Of course, from an implementer's viewpoint, it is important
  9766. to reclaim the space associated with a tuple when it is no longer
  9767. needed, which is why we also study \emph{garbage collection}
  9768. \index{garbage collection} techniques in this chapter.
  9769. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9770. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9771. language of Chapter~\ref{ch:Lwhile} with tuples.
  9772. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9773. copying live objects back and forth between two halves of the
  9774. heap. The garbage collector requires coordination with the compiler so
  9775. that it can see all of the \emph{root} pointers, that is, pointers in
  9776. registers or on the procedure call stack.
  9777. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9778. discuss all the necessary changes and additions to the compiler
  9779. passes, including a new compiler pass named \code{expose\_allocation}.
  9780. \section{The \LangVec{} Language}
  9781. \label{sec:r3}
  9782. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9783. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9784. %
  9785. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9786. creating a tuple, \code{vector-ref} for reading an element of a
  9787. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9788. \code{vector-length} for obtaining the number of elements of a
  9789. tuple.}
  9790. %
  9791. \python{The \LangVec{} language adds 1) tuple creation via a
  9792. comma-separated list of expressions, 2) accessing an element of a
  9793. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9794. the nth element of the tuple \code{t}, 3) the \code{is} comparison
  9795. operator, and 4) obtaining the number of elements (the length) of a
  9796. tuple.}
  9797. %
  9798. The program below shows an example use of tuples. It creates a 3-tuple
  9799. \code{t} and a 1-tuple that is stored at index $2$ of the 3-tuple,
  9800. demonstrating that tuples are first-class values. The element at
  9801. index $1$ of \code{t} is \racket{\code{\#t}}\python{\code{True}}, so the
  9802. ``then'' branch of the \key{if} is taken. The element at index $0$ of
  9803. \code{t} is \code{40}, to which we add \code{2}, the element at index
  9804. $0$ of the 1-tuple. So the result of the program is \code{42}.
  9805. %
  9806. {\if\edition\racketEd
  9807. \begin{lstlisting}
  9808. (let ([t (vector 40 #t (vector 2))])
  9809. (if (vector-ref t 1)
  9810. (+ (vector-ref t 0)
  9811. (vector-ref (vector-ref t 2) 0))
  9812. 44))
  9813. \end{lstlisting}
  9814. \fi}
  9815. {\if\edition\pythonEd
  9816. \begin{lstlisting}
  9817. t = 40, True, (2,)
  9818. print( t[0] + t[2][0] if t[1] else 44 )
  9819. \end{lstlisting}
  9820. \fi}
  9821. \newcommand{\LtupGrammarRacket}{
  9822. \begin{array}{lcl}
  9823. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9824. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  9825. \MID \LP\key{vector-length}\;\Exp\RP \\
  9826. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9827. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  9828. \end{array}
  9829. }
  9830. \newcommand{\LtupAST}{
  9831. \begin{array}{lcl}
  9832. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9833. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  9834. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  9835. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9836. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  9837. \end{array}
  9838. }
  9839. \begin{figure}[tbp]
  9840. \centering
  9841. \fbox{
  9842. \begin{minipage}{0.96\textwidth}
  9843. {\if\edition\racketEd
  9844. \[
  9845. \begin{array}{l}
  9846. \gray{\LintGrammarRacket{}} \\ \hline
  9847. \gray{\LvarGrammarRacket{}} \\ \hline
  9848. \gray{\LifGrammarRacket{}} \\ \hline
  9849. \gray{\LwhileGrammarRacket} \\ \hline
  9850. \LtupGrammarRacket \\
  9851. \begin{array}{lcl}
  9852. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}}
  9853. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}\\
  9854. %% \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  9855. %% &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  9856. %% &\MID& \gray{ \key{\#t} \MID \key{\#f}
  9857. %% \MID \LP\key{and}\;\Exp\;\Exp\RP
  9858. %% \MID \LP\key{or}\;\Exp\;\Exp\RP
  9859. %% \MID \LP\key{not}\;\Exp\RP } \\
  9860. %% &\MID& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  9861. %% \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  9862. %% &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  9863. %% \MID \CBEGIN{\Exp\ldots}{\Exp}
  9864. %% \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP } \\
  9865. %% &\MID& \LP\key{vector}\;\Exp\ldots\RP
  9866. %% \MID \LP\key{vector-length}\;\Exp\RP \\
  9867. %% &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9868. %% \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  9869. %% &\MID& \LP\key{has-type}~\Exp~\Type\RP\\
  9870. \LangVecM{} &::=& \Exp
  9871. \end{array}
  9872. \end{array}
  9873. \]
  9874. \fi}
  9875. {\if\edition\pythonEd
  9876. \[
  9877. \begin{array}{rcl}
  9878. \itm{binaryop} &::= & \key{+} \MID \key{-} \MID \key{and} \MID \key{or} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  9879. \itm{unaryop} &::= & \key{-} \MID \key{not} \\
  9880. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \CUNIOP{\itm{unaryop}}{\Exp} \MID \CBINOP{\itm{binaryop}}{\Exp}{\Exp} \MID \Var{} \\
  9881. &\MID& \TRUE \MID \FALSE \MID \CIF{\Exp}{\Exp}{\Exp} \\
  9882. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp} \MID \CLEN{\Exp} \\
  9883. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \CASSIGN{\Var}{\Exp}
  9884. \MID \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}\\
  9885. &\MID& \key{while}~ \Exp \key{:}~ \Stmt^{+}\\
  9886. \LangVecM{} &::=& \Stmt^{*}
  9887. \end{array}
  9888. \]
  9889. \fi}
  9890. \end{minipage}
  9891. }
  9892. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  9893. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  9894. \label{fig:Lvec-concrete-syntax}
  9895. \end{figure}
  9896. \begin{figure}[tp]
  9897. \centering
  9898. \fbox{
  9899. \begin{minipage}{0.96\textwidth}
  9900. {\if\edition\racketEd
  9901. \[
  9902. \begin{array}{l}
  9903. \gray{\LintOpAST} \\ \hline
  9904. \gray{\LvarAST{}} \\ \hline
  9905. \gray{\LifAST{}} \\ \hline
  9906. \gray{\LwhileAST{}} \\ \hline
  9907. \LtupAST{} \\
  9908. \begin{array}{lcl}
  9909. %% \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  9910. %% &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  9911. %% \MID \BOOL{\itm{bool}}
  9912. %% \MID \IF{\Exp}{\Exp}{\Exp} } \\
  9913. %% &\MID& \VECREF{\Exp}{\INT{\Int}}\\
  9914. %% &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9915. %% &\MID& \LP\key{HasType}~\Exp~\Type \RP \\
  9916. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  9917. \end{array}
  9918. \end{array}
  9919. \]
  9920. \fi}
  9921. {\if\edition\pythonEd
  9922. \[
  9923. \begin{array}{lcl}
  9924. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  9925. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  9926. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  9927. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  9928. \itm{bool} &::=& \code{True} \MID \code{False} \\
  9929. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  9930. &\MID& \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  9931. \MID \UNIOP{\itm{unaryop}}{\Exp}\\
  9932. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  9933. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  9934. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9935. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  9936. &\MID& \LEN{\Exp}\\
  9937. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  9938. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9939. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}\\
  9940. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9941. \end{array}
  9942. \]
  9943. \fi}
  9944. \end{minipage}
  9945. }
  9946. \caption{The abstract syntax of \LangVec{}.}
  9947. \label{fig:Lvec-syntax}
  9948. \end{figure}
  9949. Tuples raises several interesting new issues. First, variable binding
  9950. performs a shallow-copy when dealing with tuples, which means that
  9951. different variables can refer to the same tuple, that is, two
  9952. variables can be \emph{aliases}\index{subject}{alias} for the same
  9953. entity. Consider the following example in which both \code{t1} and
  9954. \code{t2} refer to the same tuple value but \code{t3} refers to a
  9955. different tuple value but with equal elements. The result of the
  9956. program is \code{42}.
  9957. \begin{center}
  9958. \begin{minipage}{0.96\textwidth}
  9959. {\if\edition\racketEd
  9960. \begin{lstlisting}
  9961. (let ([t1 (vector 3 7)])
  9962. (let ([t2 t1])
  9963. (let ([t3 (vector 3 7)])
  9964. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  9965. 42
  9966. 0))))
  9967. \end{lstlisting}
  9968. \fi}
  9969. {\if\edition\pythonEd
  9970. \begin{lstlisting}
  9971. t1 = 3, 7
  9972. t2 = t1
  9973. t3 = 3, 7
  9974. print( 42 if (t1 is t2) and not (t1 is t3) else 0)
  9975. \end{lstlisting}
  9976. \fi}
  9977. \end{minipage}
  9978. \end{center}
  9979. {\if\edition\racketEd
  9980. Whether two variables are aliased or not affects what happens
  9981. when the underlying tuple is mutated\index{subject}{mutation}.
  9982. Consider the following example in which \code{t1} and \code{t2}
  9983. again refer to the same tuple value.
  9984. \begin{center}
  9985. \begin{minipage}{0.96\textwidth}
  9986. \begin{lstlisting}
  9987. (let ([t1 (vector 3 7)])
  9988. (let ([t2 t1])
  9989. (let ([_ (vector-set! t2 0 42)])
  9990. (vector-ref t1 0))))
  9991. \end{lstlisting}
  9992. \end{minipage}
  9993. \end{center}
  9994. The mutation through \code{t2} is visible when referencing the tuple
  9995. from \code{t1}, so the result of this program is \code{42}.
  9996. \fi}
  9997. The next issue concerns the lifetime of tuples. When does their
  9998. lifetime end? Notice that \LangVec{} does not include an operation
  9999. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10000. to any notion of static scoping.
  10001. %
  10002. {\if\edition\racketEd
  10003. %
  10004. For example, the following program returns \code{42} even though the
  10005. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10006. that reads from the vector it was bound to.
  10007. \begin{center}
  10008. \begin{minipage}{0.96\textwidth}
  10009. \begin{lstlisting}
  10010. (let ([v (vector (vector 44))])
  10011. (let ([x (let ([w (vector 42)])
  10012. (let ([_ (vector-set! v 0 w)])
  10013. 0))])
  10014. (+ x (vector-ref (vector-ref v 0) 0))))
  10015. \end{lstlisting}
  10016. \end{minipage}
  10017. \end{center}
  10018. \fi}
  10019. %
  10020. {\if\edition\pythonEd
  10021. %
  10022. For example, the following program returns \code{42} even though the
  10023. variable \code{x} goes out of scope when the function returns, prior
  10024. to reading the tuple element at index zero. (We study the compilation
  10025. of functions in Chapter~\ref{ch:Rfun}.)
  10026. %
  10027. \begin{center}
  10028. \begin{minipage}{0.96\textwidth}
  10029. \begin{lstlisting}
  10030. def f():
  10031. x = 42, 43
  10032. return x
  10033. t = f()
  10034. print( t[0] )
  10035. \end{lstlisting}
  10036. \end{minipage}
  10037. \end{center}
  10038. \fi}
  10039. %
  10040. From the perspective of programmer-observable behavior, tuples live
  10041. forever. Of course, if they really lived forever then many programs
  10042. would run out of memory. The language's runtime system must therefore
  10043. perform automatic garbage collection.
  10044. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10045. \LangVec{} language.
  10046. %
  10047. \racket{We define the \code{vector}, \code{vector-ref},
  10048. \code{vector-set!}, and \code{vector-length} operations for
  10049. \LangVec{} in terms of the corresponding operations in Racket. One
  10050. subtle point is that the \code{vector-set!} operation returns the
  10051. \code{\#<void>} value.}
  10052. %
  10053. \python{We define tuple creation, element access, and the \code{len}
  10054. operator for \LangVec{} in terms of the corresponding operations in
  10055. Python.}
  10056. \begin{figure}[tbp]
  10057. {\if\edition\racketEd
  10058. \begin{lstlisting}
  10059. (define interp-Lvec_class
  10060. (class interp-Lif_class
  10061. (super-new)
  10062. (define/override (interp-op op)
  10063. (match op
  10064. ['eq? (lambda (v1 v2)
  10065. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10066. (and (boolean? v1) (boolean? v2))
  10067. (and (vector? v1) (vector? v2))
  10068. (and (void? v1) (void? v2)))
  10069. (eq? v1 v2)]))]
  10070. ['vector vector]
  10071. ['vector-length vector-length]
  10072. ['vector-ref vector-ref]
  10073. ['vector-set! vector-set!]
  10074. [else (super interp-op op)]
  10075. ))
  10076. (define/override ((interp-exp env) e)
  10077. (define recur (interp-exp env))
  10078. (match e
  10079. [(HasType e t) (recur e)]
  10080. [(Void) (void)]
  10081. [else ((super interp-exp env) e)]
  10082. ))
  10083. ))
  10084. (define (interp-Lvec p)
  10085. (send (new interp-Lvec_class) interp-program p))
  10086. \end{lstlisting}
  10087. \fi}
  10088. %
  10089. {\if\edition\pythonEd
  10090. \begin{lstlisting}
  10091. class InterpLtup(InterpLwhile):
  10092. def interp_cmp(self, cmp):
  10093. match cmp:
  10094. case Is():
  10095. return lambda x, y: x is y
  10096. case _:
  10097. return super().interp_cmp(cmp)
  10098. def interp_exp(self, e, env):
  10099. match e:
  10100. case Tuple(es, Load()):
  10101. return tuple([self.interp_exp(e, env) for e in es])
  10102. case Subscript(tup, index, Load()):
  10103. t = self.interp_exp(tup, env)
  10104. n = self.interp_exp(index, env)
  10105. return t[n]
  10106. case _:
  10107. return super().interp_exp(e, env)
  10108. \end{lstlisting}
  10109. \fi}
  10110. \caption{Interpreter for the \LangVec{} language.}
  10111. \label{fig:interp-Lvec}
  10112. \end{figure}
  10113. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10114. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10115. we need to know which elements of the tuple are pointers (i.e. are
  10116. also tuple) for garbage collection purposes. We can obtain this
  10117. information during type checking. The type checker in
  10118. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10119. expression, it also
  10120. %
  10121. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10122. where $T$ is the vector's type.
  10123. To create the s-expression for the \code{Vector} type in
  10124. Figure~\ref{fig:type-check-Lvec}, we use the
  10125. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10126. operator} \code{,@} to insert the list \code{t*} without its usual
  10127. start and end parentheses. \index{subject}{unquote-slicing}}
  10128. %
  10129. \python{records the type of each tuple expression in a new field
  10130. named \code{has\_type}.}
  10131. \begin{figure}[tp]
  10132. {\if\edition\racketEd
  10133. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10134. (define type-check-Lvec_class
  10135. (class type-check-Lif_class
  10136. (super-new)
  10137. (inherit check-type-equal?)
  10138. (define/override (type-check-exp env)
  10139. (lambda (e)
  10140. (define recur (type-check-exp env))
  10141. (match e
  10142. [(Void) (values (Void) 'Void)]
  10143. [(Prim 'vector es)
  10144. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10145. (define t `(Vector ,@t*))
  10146. (values (HasType (Prim 'vector e*) t) t)]
  10147. [(Prim 'vector-ref (list e1 (Int i)))
  10148. (define-values (e1^ t) (recur e1))
  10149. (match t
  10150. [`(Vector ,ts ...)
  10151. (unless (and (0 . <= . i) (i . < . (length ts)))
  10152. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10153. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10154. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10155. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10156. (define-values (e-vec t-vec) (recur e1))
  10157. (define-values (e-arg^ t-arg) (recur arg))
  10158. (match t-vec
  10159. [`(Vector ,ts ...)
  10160. (unless (and (0 . <= . i) (i . < . (length ts)))
  10161. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10162. (check-type-equal? (list-ref ts i) t-arg e)
  10163. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10164. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10165. [(Prim 'vector-length (list e))
  10166. (define-values (e^ t) (recur e))
  10167. (match t
  10168. [`(Vector ,ts ...)
  10169. (values (Prim 'vector-length (list e^)) 'Integer)]
  10170. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10171. [(Prim 'eq? (list arg1 arg2))
  10172. (define-values (e1 t1) (recur arg1))
  10173. (define-values (e2 t2) (recur arg2))
  10174. (match* (t1 t2)
  10175. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10176. [(other wise) (check-type-equal? t1 t2 e)])
  10177. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10178. [(HasType (Prim 'vector es) t)
  10179. ((type-check-exp env) (Prim 'vector es))]
  10180. [(HasType e1 t)
  10181. (define-values (e1^ t^) (recur e1))
  10182. (check-type-equal? t t^ e)
  10183. (values (HasType e1^ t) t)]
  10184. [else ((super type-check-exp env) e)]
  10185. )))
  10186. ))
  10187. (define (type-check-Lvec p)
  10188. (send (new type-check-Lvec_class) type-check-program p))
  10189. \end{lstlisting}
  10190. \fi}
  10191. {\if\edition\pythonEd
  10192. \begin{lstlisting}
  10193. class TypeCheckLtup(TypeCheckLwhile):
  10194. def type_check_exp(self, e, env):
  10195. match e:
  10196. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10197. l = self.type_check_exp(left, env)
  10198. r = self.type_check_exp(right, env)
  10199. check_type_equal(l, r, e)
  10200. return bool
  10201. case Tuple(es, Load()):
  10202. ts = [self.type_check_exp(e, env) for e in es]
  10203. e.has_type = tuple(ts)
  10204. return e.has_type
  10205. case Subscript(tup, Constant(index), Load()):
  10206. tup_ty = self.type_check_exp(tup, env)
  10207. index_ty = self.type_check_exp(Constant(index), env)
  10208. check_type_equal(index_ty, int, index)
  10209. match tup_ty:
  10210. case tuple(ts):
  10211. return ts[index]
  10212. case _:
  10213. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10214. case _:
  10215. return super().type_check_exp(e, env)
  10216. \end{lstlisting}
  10217. \fi}
  10218. \caption{Type checker for the \LangVec{} language.}
  10219. \label{fig:type-check-Lvec}
  10220. \end{figure}
  10221. \section{Garbage Collection}
  10222. \label{sec:GC}
  10223. Here we study a relatively simple algorithm for garbage collection
  10224. that is the basis of state-of-the-art garbage
  10225. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10226. particular, we describe a two-space copying
  10227. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10228. perform the
  10229. copy~\citep{Cheney:1970aa}.
  10230. \index{subject}{copying collector}
  10231. \index{subject}{two-space copying collector}
  10232. Figure~\ref{fig:copying-collector} gives a
  10233. coarse-grained depiction of what happens in a two-space collector,
  10234. showing two time steps, prior to garbage collection (on the top) and
  10235. after garbage collection (on the bottom). In a two-space collector,
  10236. the heap is divided into two parts named the FromSpace and the
  10237. ToSpace. Initially, all allocations go to the FromSpace until there is
  10238. not enough room for the next allocation request. At that point, the
  10239. garbage collector goes to work to make more room.
  10240. \index{subject}{ToSpace}
  10241. \index{subject}{FromSpace}
  10242. The garbage collector must be careful not to reclaim tuples that will
  10243. be used by the program in the future. Of course, it is impossible in
  10244. general to predict what a program will do, but we can over approximate
  10245. the will-be-used tuples by preserving all tuples that could be
  10246. accessed by \emph{any} program given the current computer state. A
  10247. program could access any tuple whose address is in a register or on
  10248. the procedure call stack. These addresses are called the \emph{root
  10249. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  10250. transitively reachable from the root set. Thus, it is safe for the
  10251. garbage collector to reclaim the tuples that are not reachable in this
  10252. way.
  10253. So the goal of the garbage collector is twofold:
  10254. \begin{enumerate}
  10255. \item preserve all tuple that are reachable from the root set via a
  10256. path of pointers, that is, the \emph{live} tuples, and
  10257. \item reclaim the memory of everything else, that is, the
  10258. \emph{garbage}.
  10259. \end{enumerate}
  10260. A copying collector accomplishes this by copying all of the live
  10261. objects from the FromSpace into the ToSpace and then performs a sleight
  10262. of hand, treating the ToSpace as the new FromSpace and the old
  10263. FromSpace as the new ToSpace. In the example of
  10264. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10265. root set, one in a register and two on the stack. All of the live
  10266. objects have been copied to the ToSpace (the right-hand side of
  10267. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10268. pointer relationships. For example, the pointer in the register still
  10269. points to a 2-tuple whose first element is a 3-tuple and whose second
  10270. element is a 2-tuple. There are four tuples that are not reachable
  10271. from the root set and therefore do not get copied into the ToSpace.
  10272. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10273. created by a well-typed program in \LangVec{} because it contains a
  10274. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  10275. We design the garbage collector to deal with cycles to begin with so
  10276. we will not need to revisit this issue.
  10277. \begin{figure}[tbp]
  10278. \centering
  10279. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  10280. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  10281. \caption{A copying collector in action.}
  10282. \label{fig:copying-collector}
  10283. \end{figure}
  10284. There are many alternatives to copying collectors (and their bigger
  10285. siblings, the generational collectors) when its comes to garbage
  10286. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  10287. reference counting~\citep{Collins:1960aa}. The strengths of copying
  10288. collectors are that allocation is fast (just a comparison and pointer
  10289. increment), there is no fragmentation, cyclic garbage is collected,
  10290. and the time complexity of collection only depends on the amount of
  10291. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  10292. main disadvantages of a two-space copying collector is that it uses a
  10293. lot of space and takes a long time to perform the copy, though these
  10294. problems are ameliorated in generational collectors. Racket and
  10295. Scheme programs tend to allocate many small objects and generate a lot
  10296. of garbage, so copying and generational collectors are a good fit.
  10297. Garbage collection is an active research topic, especially concurrent
  10298. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  10299. developing new techniques and revisiting old
  10300. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  10301. meet every year at the International Symposium on Memory Management to
  10302. present these findings.
  10303. \subsection{Graph Copying via Cheney's Algorithm}
  10304. \label{sec:cheney}
  10305. \index{subject}{Cheney's algorithm}
  10306. Let us take a closer look at the copying of the live objects. The
  10307. allocated objects and pointers can be viewed as a graph and we need to
  10308. copy the part of the graph that is reachable from the root set. To
  10309. make sure we copy all of the reachable vertices in the graph, we need
  10310. an exhaustive graph traversal algorithm, such as depth-first search or
  10311. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10312. such algorithms take into account the possibility of cycles by marking
  10313. which vertices have already been visited, so as to ensure termination
  10314. of the algorithm. These search algorithms also use a data structure
  10315. such as a stack or queue as a to-do list to keep track of the vertices
  10316. that need to be visited. We use breadth-first search and a trick
  10317. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10318. and copying tuples into the ToSpace.
  10319. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10320. copy progresses. The queue is represented by a chunk of contiguous
  10321. memory at the beginning of the ToSpace, using two pointers to track
  10322. the front and the back of the queue. The algorithm starts by copying
  10323. all tuples that are immediately reachable from the root set into the
  10324. ToSpace to form the initial queue. When we copy a tuple, we mark the
  10325. old tuple to indicate that it has been visited. We discuss how this
  10326. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  10327. pointers inside the copied tuples in the queue still point back to the
  10328. FromSpace. Once the initial queue has been created, the algorithm
  10329. enters a loop in which it repeatedly processes the tuple at the front
  10330. of the queue and pops it off the queue. To process a tuple, the
  10331. algorithm copies all the tuple that are directly reachable from it to
  10332. the ToSpace, placing them at the back of the queue. The algorithm then
  10333. updates the pointers in the popped tuple so they point to the newly
  10334. copied tuples.
  10335. \begin{figure}[tbp]
  10336. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  10337. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10338. \label{fig:cheney}
  10339. \end{figure}
  10340. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10341. tuple whose second element is $42$ to the back of the queue. The other
  10342. pointer goes to a tuple that has already been copied, so we do not
  10343. need to copy it again, but we do need to update the pointer to the new
  10344. location. This can be accomplished by storing a \emph{forwarding
  10345. pointer} to the new location in the old tuple, back when we initially
  10346. copied the tuple into the ToSpace. This completes one step of the
  10347. algorithm. The algorithm continues in this way until the front of the
  10348. queue is empty, that is, until the front catches up with the back.
  10349. \subsection{Data Representation}
  10350. \label{sec:data-rep-gc}
  10351. The garbage collector places some requirements on the data
  10352. representations used by our compiler. First, the garbage collector
  10353. needs to distinguish between pointers and other kinds of data. There
  10354. are several ways to accomplish this.
  10355. \begin{enumerate}
  10356. \item Attached a tag to each object that identifies what type of
  10357. object it is~\citep{McCarthy:1960dz}.
  10358. \item Store different types of objects in different
  10359. regions~\citep{Steele:1977ab}.
  10360. \item Use type information from the program to either generate
  10361. type-specific code for collecting or to generate tables that can
  10362. guide the
  10363. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10364. \end{enumerate}
  10365. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10366. need to tag objects anyways, so option 1 is a natural choice for those
  10367. languages. However, \LangVec{} is a statically typed language, so it
  10368. would be unfortunate to require tags on every object, especially small
  10369. and pervasive objects like integers and Booleans. Option 3 is the
  10370. best-performing choice for statically typed languages, but comes with
  10371. a relatively high implementation complexity. To keep this chapter
  10372. within a 2-week time budget, we recommend a combination of options 1
  10373. and 2, using separate strategies for the stack and the heap.
  10374. Regarding the stack, we recommend using a separate stack for pointers,
  10375. which we call a \emph{root stack}\index{subject}{root stack}
  10376. (a.k.a. ``shadow
  10377. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10378. is, when a local variable needs to be spilled and is of type
  10379. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10380. root stack instead of the normal procedure call stack. Furthermore, we
  10381. always spill tuple-typed variables if they are live during a call to
  10382. the collector, thereby ensuring that no pointers are in registers
  10383. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  10384. example from Figure~\ref{fig:copying-collector} and contrasts it with
  10385. the data layout using a root stack. The root stack contains the two
  10386. pointers from the regular stack and also the pointer in the second
  10387. register.
  10388. \begin{figure}[tbp]
  10389. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  10390. \caption{Maintaining a root stack to facilitate garbage collection.}
  10391. \label{fig:shadow-stack}
  10392. \end{figure}
  10393. The problem of distinguishing between pointers and other kinds of data
  10394. also arises inside of each tuple on the heap. We solve this problem by
  10395. attaching a tag, an extra 64-bits, to each
  10396. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10397. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10398. that we have drawn the bits in a big-endian way, from right-to-left,
  10399. with bit location 0 (the least significant bit) on the far right,
  10400. which corresponds to the direction of the x86 shifting instructions
  10401. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10402. is dedicated to specifying which elements of the tuple are pointers,
  10403. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10404. indicates there is a pointer and a 0 bit indicates some other kind of
  10405. data. The pointer mask starts at bit location 7. We have limited
  10406. tuples to a maximum size of 50 elements, so we just need 50 bits for
  10407. the pointer mask. The tag also contains two other pieces of
  10408. information. The length of the tuple (number of elements) is stored in
  10409. bits location 1 through 6. Finally, the bit at location 0 indicates
  10410. whether the tuple has yet to be copied to the ToSpace. If the bit has
  10411. value 1, then this tuple has not yet been copied. If the bit has
  10412. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  10413. of a pointer are always zero anyways because our tuples are 8-byte
  10414. aligned.)
  10415. \begin{figure}[tbp]
  10416. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10417. \caption{Representation of tuples in the heap.}
  10418. \label{fig:tuple-rep}
  10419. \end{figure}
  10420. \subsection{Implementation of the Garbage Collector}
  10421. \label{sec:organize-gz}
  10422. \index{subject}{prelude}
  10423. An implementation of the copying collector is provided in the
  10424. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10425. interface to the garbage collector that is used by the compiler. The
  10426. \code{initialize} function creates the FromSpace, ToSpace, and root
  10427. stack and should be called in the prelude of the \code{main}
  10428. function. The arguments of \code{initialize} are the root stack size
  10429. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10430. good choice for both. The \code{initialize} function puts the address
  10431. of the beginning of the FromSpace into the global variable
  10432. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10433. the address that is 1-past the last element of the FromSpace. (We use
  10434. half-open intervals to represent chunks of
  10435. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10436. points to the first element of the root stack.
  10437. As long as there is room left in the FromSpace, your generated code
  10438. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10439. %
  10440. The amount of room left in FromSpace is the difference between the
  10441. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10442. function should be called when there is not enough room left in the
  10443. FromSpace for the next allocation. The \code{collect} function takes
  10444. a pointer to the current top of the root stack (one past the last item
  10445. that was pushed) and the number of bytes that need to be
  10446. allocated. The \code{collect} function performs the copying collection
  10447. and leaves the heap in a state such that the next allocation will
  10448. succeed.
  10449. \begin{figure}[tbp]
  10450. \begin{lstlisting}
  10451. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10452. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10453. int64_t* free_ptr;
  10454. int64_t* fromspace_begin;
  10455. int64_t* fromspace_end;
  10456. int64_t** rootstack_begin;
  10457. \end{lstlisting}
  10458. \caption{The compiler's interface to the garbage collector.}
  10459. \label{fig:gc-header}
  10460. \end{figure}
  10461. %% \begin{exercise}
  10462. %% In the file \code{runtime.c} you will find the implementation of
  10463. %% \code{initialize} and a partial implementation of \code{collect}.
  10464. %% The \code{collect} function calls another function, \code{cheney},
  10465. %% to perform the actual copy, and that function is left to the reader
  10466. %% to implement. The following is the prototype for \code{cheney}.
  10467. %% \begin{lstlisting}
  10468. %% static void cheney(int64_t** rootstack_ptr);
  10469. %% \end{lstlisting}
  10470. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10471. %% rootstack (which is an array of pointers). The \code{cheney} function
  10472. %% also communicates with \code{collect} through the global
  10473. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10474. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10475. %% the ToSpace:
  10476. %% \begin{lstlisting}
  10477. %% static int64_t* tospace_begin;
  10478. %% static int64_t* tospace_end;
  10479. %% \end{lstlisting}
  10480. %% The job of the \code{cheney} function is to copy all the live
  10481. %% objects (reachable from the root stack) into the ToSpace, update
  10482. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10483. %% update the root stack so that it points to the objects in the
  10484. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10485. %% and ToSpace.
  10486. %% \end{exercise}
  10487. %% \section{Compiler Passes}
  10488. %% \label{sec:code-generation-gc}
  10489. The introduction of garbage collection has a non-trivial impact on our
  10490. compiler passes. We introduce a new compiler pass named
  10491. \code{expose\_allocation}. We make significant changes to
  10492. \code{select\_instructions}, \code{build\_interference},
  10493. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10494. make minor changes in several more passes. The following program will
  10495. serve as our running example. It creates two tuples, one nested
  10496. inside the other. Both tuples have length one. The program accesses
  10497. the element in the inner tuple tuple.
  10498. % tests/vectors_test_17.rkt
  10499. {\if\edition\racketEd
  10500. \begin{lstlisting}
  10501. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10502. \end{lstlisting}
  10503. \fi}
  10504. {\if\edition\pythonEd
  10505. \begin{lstlisting}
  10506. print( ((42,),)[0][0] )
  10507. \end{lstlisting}
  10508. \fi}
  10509. {\if\edition\racketEd
  10510. \section{Shrink}
  10511. \label{sec:shrink-Lvec}
  10512. Recall that the \code{shrink} pass translates the primitives operators
  10513. into a smaller set of primitives.
  10514. %
  10515. This pass comes after type checking and the type checker adds a
  10516. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10517. need to add a case for \code{HasType} to the \code{shrink} pass.
  10518. \fi}
  10519. \section{Expose Allocation}
  10520. \label{sec:expose-allocation}
  10521. The pass \code{expose\_allocation} lowers tuple creation into a
  10522. conditional call to the collector followed by allocating the
  10523. appropriate amount of memory and initializing it. We choose to place
  10524. the \code{expose\_allocation} pass before
  10525. \code{remove\_complex\_operands} because the code generated by
  10526. \code{expose\_allocation} contains complex operands.
  10527. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10528. that extends \LangVec{} with new forms that we use in the translation
  10529. of tuple creation.
  10530. %
  10531. {\if\edition\racketEd
  10532. \[
  10533. \begin{array}{lcl}
  10534. \Exp &::=& \cdots
  10535. \MID (\key{collect} \,\itm{int})
  10536. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10537. \MID (\key{global-value} \,\itm{name})
  10538. \end{array}
  10539. \]
  10540. \fi}
  10541. {\if\edition\pythonEd
  10542. \[
  10543. \begin{array}{lcl}
  10544. \Exp &::=& \cdots\\
  10545. &\MID& \key{collect}(\itm{int})
  10546. \MID \key{allocate}(\itm{int},\itm{type})
  10547. \MID \key{global\_value}(\itm{name}) \\
  10548. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp
  10549. \end{array}
  10550. \]
  10551. \fi}
  10552. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10553. make sure that there are $n$ bytes ready to be allocated. During
  10554. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10555. the \code{collect} function in \code{runtime.c}.
  10556. %
  10557. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10558. space at the front for the 64 bit tag), but the elements are not
  10559. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10560. of the tuple:
  10561. %
  10562. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10563. %
  10564. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10565. \CGLOBAL{\itm{name}} form reads the value of a global variable, such
  10566. as \code{free\_ptr}.
  10567. %
  10568. \python{The \code{begin} form is an expression that executes a
  10569. sequence of statements and then produces the value of the expression
  10570. at the end.}
  10571. The following shows the transformation of tuple creation into 1) a
  10572. sequence of temporary variables bindings for the initializing
  10573. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10574. \code{allocate}, and 4) the initialization of the tuple. The
  10575. \itm{len} placeholder refers to the length of the tuple and
  10576. \itm{bytes} is how many total bytes need to be allocated for the
  10577. tuple, which is 8 for the tag plus \itm{len} times 8.
  10578. %
  10579. \python{The \itm{type} needed for the second argument of the
  10580. \code{allocate} form can be obtained from the \code{has\_type} field
  10581. of the tuple AST node, which is stored there by running the type
  10582. checker for \LangVec{} immediately before this pass.}
  10583. %
  10584. {\if\edition\racketEd
  10585. \begin{lstlisting}
  10586. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10587. |$\Longrightarrow$|
  10588. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10589. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10590. (global-value fromspace_end))
  10591. (void)
  10592. (collect |\itm{bytes}|))])
  10593. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10594. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10595. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10596. |$v$|) ... )))) ...)
  10597. \end{lstlisting}
  10598. \fi}
  10599. {\if\edition\pythonEd
  10600. \begin{lstlisting}
  10601. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10602. |$\Longrightarrow$|
  10603. begin:
  10604. |$x_0$| = |$e_0$|
  10605. |$\vdots$|
  10606. |$x_{n-1}$| = |$e_{n-1}$|
  10607. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10608. 0
  10609. else:
  10610. collect(|\itm{bytes}|)
  10611. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10612. |$v$|[0] = |$x_0$|
  10613. |$\vdots$|
  10614. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10615. |$v$|
  10616. \end{lstlisting}
  10617. \fi}
  10618. %
  10619. \noindent The sequencing of the initializing expressions
  10620. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10621. they may trigger garbage collection and we cannot have an allocated
  10622. but uninitialized tuple on the heap during a collection.
  10623. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10624. \code{expose\_allocation} pass on our running example.
  10625. \begin{figure}[tbp]
  10626. % tests/s2_17.rkt
  10627. {\if\edition\racketEd
  10628. \begin{lstlisting}
  10629. (vector-ref
  10630. (vector-ref
  10631. (let ([vecinit7976
  10632. (let ([vecinit7972 42])
  10633. (let ([collectret7974
  10634. (if (< (+ (global-value free_ptr) 16)
  10635. (global-value fromspace_end))
  10636. (void)
  10637. (collect 16)
  10638. )])
  10639. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10640. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10641. alloc7971))))])
  10642. (let ([collectret7978
  10643. (if (< (+ (global-value free_ptr) 16)
  10644. (global-value fromspace_end))
  10645. (void)
  10646. (collect 16)
  10647. )])
  10648. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10649. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10650. alloc7975))))
  10651. 0)
  10652. 0)
  10653. \end{lstlisting}
  10654. \fi}
  10655. {\if\edition\pythonEd
  10656. \begin{lstlisting}
  10657. print( |$T_1$|[0][0] )
  10658. \end{lstlisting}
  10659. where $T_1$ is
  10660. \begin{lstlisting}
  10661. begin:
  10662. tmp.1 = |$T_2$|
  10663. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10664. 0
  10665. else:
  10666. collect(16)
  10667. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10668. tmp.2[0] = tmp.1
  10669. tmp.2
  10670. \end{lstlisting}
  10671. and $T_2$ is
  10672. \begin{lstlisting}
  10673. begin:
  10674. tmp.3 = 42
  10675. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10676. 0
  10677. else:
  10678. collect(16)
  10679. tmp.4 = allocate(1, TupleType([int]))
  10680. tmp.4[0] = tmp.3
  10681. tmp.4
  10682. \end{lstlisting}
  10683. \fi}
  10684. \caption{Output of the \code{expose\_allocation} pass.}
  10685. \label{fig:expose-alloc-output}
  10686. \end{figure}
  10687. \section{Remove Complex Operands}
  10688. \label{sec:remove-complex-opera-Lvec}
  10689. {\if\edition\racketEd
  10690. %
  10691. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10692. should be treated as complex operands.
  10693. %
  10694. \fi}
  10695. %
  10696. {\if\edition\pythonEd
  10697. %
  10698. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10699. and tuple access should be treated as complex operands. The
  10700. sub-expressions of tuple access must be atomic.
  10701. %
  10702. \fi}
  10703. %% A new case for
  10704. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10705. %% handled carefully to prevent the \code{Prim} node from being separated
  10706. %% from its enclosing \code{HasType}.
  10707. Figure~\ref{fig:Lvec-anf-syntax}
  10708. shows the grammar for the output language \LangVecANF{} of this
  10709. pass, which is \LangVec{} in monadic normal form.
  10710. \begin{figure}[tp]
  10711. \centering
  10712. \fbox{
  10713. \begin{minipage}{0.96\textwidth}
  10714. \small
  10715. {\if\edition\racketEd
  10716. \[
  10717. \begin{array}{rcl}
  10718. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10719. \MID \VOID{} } \\
  10720. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10721. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10722. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10723. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10724. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10725. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10726. \MID \GLOBALVALUE{\Var}\\
  10727. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10728. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10729. \end{array}
  10730. \]
  10731. \fi}
  10732. {\if\edition\pythonEd
  10733. \[
  10734. \begin{array}{lcl}
  10735. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10736. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10737. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10738. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10739. \itm{bool} &::=& \code{True} \MID \code{False} \\
  10740. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10741. \Exp &::=& \Atm \MID \READ{} \MID \\
  10742. &\MID& \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  10743. \MID \UNIOP{\itm{unaryop}}{\Exp}\\
  10744. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  10745. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  10746. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10747. &\MID& \GET{\Atm}{\Atm} \\
  10748. &\MID& \LEN{\Exp}\\
  10749. &\MID& \ALLOCATE{\Int}{\Type}
  10750. \MID \GLOBALVALUE{\Var}\RP\\
  10751. &\MID& \BEGIN{\Stmt^{*}}{\Exp} \\
  10752. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  10753. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10754. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10755. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10756. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10757. \MID \COLLECT{\Int} \\
  10758. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10759. \end{array}
  10760. \]
  10761. \fi}
  10762. \end{minipage}
  10763. }
  10764. \caption{\LangVecANF{} is \LangVec{} in monadic normal form.}
  10765. \label{fig:Lvec-anf-syntax}
  10766. \end{figure}
  10767. \section{Explicate Control and the \LangCVec{} language}
  10768. \label{sec:explicate-control-r3}
  10769. \begin{figure}[tp]
  10770. \fbox{
  10771. \begin{minipage}{0.96\textwidth}
  10772. \small
  10773. {\if\edition\racketEd
  10774. \[
  10775. \begin{array}{lcl}
  10776. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  10777. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  10778. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  10779. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  10780. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  10781. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10782. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  10783. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  10784. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  10785. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  10786. \MID \LP\key{Collect} \,\itm{int}\RP \\
  10787. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10788. \MID \GOTO{\itm{label}} } \\
  10789. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10790. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  10791. \end{array}
  10792. \]
  10793. \fi}
  10794. {\if\edition\pythonEd
  10795. \[
  10796. \begin{array}{lcl}
  10797. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10798. \Exp &::= & \Atm \MID \READ{} \\
  10799. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  10800. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10801. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  10802. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  10803. &\MID& \GET{\Atm}{\Atm}
  10804. \MID \ALLOCATE{\Int}{\Type} \MID \GLOBALVALUE{\Var}\RP\\
  10805. &\MID& \LEN{\Atm} \\
  10806. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  10807. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  10808. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  10809. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  10810. &\MID& \COLLECT{\Int} \\
  10811. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  10812. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{*}, \ldots \RC}
  10813. \end{array}
  10814. \]
  10815. \fi}
  10816. \end{minipage}
  10817. }
  10818. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  10819. (Figure~\ref{fig:c1-syntax}).}
  10820. \label{fig:c2-syntax}
  10821. \end{figure}
  10822. The output of \code{explicate\_control} is a program in the
  10823. intermediate language \LangCVec{}, whose abstract syntax is defined in
  10824. Figure~\ref{fig:c2-syntax}. \racket{(The concrete syntax is defined
  10825. in Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)} The new
  10826. expressions of \LangCVec{} include \key{allocate},
  10827. %
  10828. \racket{\key{vector-ref}, and \key{vector-set!},}
  10829. %
  10830. \python{accessing tuple elements,}
  10831. %
  10832. and \key{global\_value}.
  10833. %
  10834. \python{\LangCVec{} also includes the \code{collect} statement and
  10835. assignment to a tuple element.}
  10836. %
  10837. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  10838. %
  10839. The \code{explicate\_control} pass can treat these new forms much like
  10840. the other forms that we've already encoutered.
  10841. \section{Select Instructions and the \LangXGlobal{} Language}
  10842. \label{sec:select-instructions-gc}
  10843. \index{subject}{instruction selection}
  10844. %% void (rep as zero)
  10845. %% allocate
  10846. %% collect (callq collect)
  10847. %% vector-ref
  10848. %% vector-set!
  10849. %% global (postpone)
  10850. In this pass we generate x86 code for most of the new operations that
  10851. were needed to compile tuples, including \code{Allocate},
  10852. \code{Collect}, and accessing tuple elements.
  10853. %
  10854. We compile \code{GlobalValue} to \code{Global} because the later has a
  10855. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  10856. \ref{fig:x86-2}). \index{subject}{x86}
  10857. The tuple read and write forms translate into \code{movq}
  10858. instructions. (The plus one in the offset is to get past the tag at
  10859. the beginning of the tuple representation.)
  10860. %
  10861. \begin{center}
  10862. \begin{minipage}{\textwidth}
  10863. {\if\edition\racketEd
  10864. \begin{lstlisting}
  10865. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  10866. |$\Longrightarrow$|
  10867. movq |$\itm{tup}'$|, %r11
  10868. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10869. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  10870. |$\Longrightarrow$|
  10871. movq |$\itm{tup}'$|, %r11
  10872. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10873. movq $0, |$\itm{lhs'}$|
  10874. \end{lstlisting}
  10875. \fi}
  10876. {\if\edition\pythonEd
  10877. \begin{lstlisting}
  10878. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  10879. |$\Longrightarrow$|
  10880. movq |$\itm{tup}'$|, %r11
  10881. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10882. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  10883. |$\Longrightarrow$|
  10884. movq |$\itm{tup}'$|, %r11
  10885. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10886. movq $0, |$\itm{lhs'}$|
  10887. \end{lstlisting}
  10888. \fi}
  10889. \end{minipage}
  10890. \end{center}
  10891. The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$ are obtained by
  10892. translating $\itm{tup}$ and $\itm{rhs}$ to x86. The move of $\itm{tup}'$ to
  10893. register \code{r11} ensures that offset expression
  10894. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  10895. removing \code{r11} from consideration by the register allocating.
  10896. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  10897. \code{rax}. Then the generated code for tuple assignment would be
  10898. \begin{lstlisting}
  10899. movq |$\itm{tup}'$|, %rax
  10900. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  10901. movq $0, |$\itm{lhs}'$|
  10902. \end{lstlisting}
  10903. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  10904. \code{patch\_instructions} would insert a move through \code{rax}
  10905. as follows.
  10906. \begin{lstlisting}
  10907. movq |$\itm{tup}'$|, %rax
  10908. movq |$\itm{rhs}'$|, %rax
  10909. movq %rax, |$8(n+1)$|(%rax)
  10910. movq $0, |$\itm{lhs}'$|
  10911. \end{lstlisting}
  10912. But the above sequence of instructions does not work because we're
  10913. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  10914. $\itm{rhs}'$) at the same time!
  10915. We compile the \code{allocate} form to operations on the
  10916. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  10917. is the next free address in the FromSpace, so we copy it into
  10918. \code{r11} and then move it forward by enough space for the tuple
  10919. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  10920. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  10921. initialize the \itm{tag} and finally copy the address in \code{r11} to
  10922. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  10923. tag is organized.
  10924. %
  10925. \racket{We recommend using the Racket operations
  10926. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  10927. during compilation.}
  10928. %
  10929. The type annotation in the \code{allocate} form is used to determine
  10930. the pointer mask region of the tag.
  10931. %
  10932. {\if\edition\racketEd
  10933. \begin{lstlisting}
  10934. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  10935. |$\Longrightarrow$|
  10936. movq free_ptr(%rip), %r11
  10937. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  10938. movq $|$\itm{tag}$|, 0(%r11)
  10939. movq %r11, |$\itm{lhs}'$|
  10940. \end{lstlisting}
  10941. \fi}
  10942. {\if\edition\pythonEd
  10943. \begin{lstlisting}
  10944. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  10945. |$\Longrightarrow$|
  10946. movq free_ptr(%rip), %r11
  10947. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  10948. movq $|$\itm{tag}$|, 0(%r11)
  10949. movq %r11, |$\itm{lhs}'$|
  10950. \end{lstlisting}
  10951. \fi}
  10952. The \code{collect} form is compiled to a call to the \code{collect}
  10953. function in the runtime. The arguments to \code{collect} are 1) the
  10954. top of the root stack and 2) the number of bytes that need to be
  10955. allocated. We use another dedicated register, \code{r15}, to
  10956. store the pointer to the top of the root stack. So \code{r15} is not
  10957. available for use by the register allocator.
  10958. {\if\edition\racketEd
  10959. \begin{lstlisting}
  10960. (collect |$\itm{bytes}$|)
  10961. |$\Longrightarrow$|
  10962. movq %r15, %rdi
  10963. movq $|\itm{bytes}|, %rsi
  10964. callq collect
  10965. \end{lstlisting}
  10966. \fi}
  10967. {\if\edition\pythonEd
  10968. \begin{lstlisting}
  10969. collect(|$\itm{bytes}$|)
  10970. |$\Longrightarrow$|
  10971. movq %r15, %rdi
  10972. movq $|\itm{bytes}|, %rsi
  10973. callq collect
  10974. \end{lstlisting}
  10975. \fi}
  10976. \begin{figure}[tp]
  10977. \fbox{
  10978. \begin{minipage}{0.96\textwidth}
  10979. \[
  10980. \begin{array}{lcl}
  10981. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  10982. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  10983. & & \gray{ \key{main:} \; \Instr\ldots }
  10984. \end{array}
  10985. \]
  10986. \end{minipage}
  10987. }
  10988. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  10989. \label{fig:x86-2-concrete}
  10990. \end{figure}
  10991. \begin{figure}[tp]
  10992. \fbox{
  10993. \begin{minipage}{0.96\textwidth}
  10994. \small
  10995. \[
  10996. \begin{array}{lcl}
  10997. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  10998. \MID \BYTEREG{\Reg}} \\
  10999. &\MID& \GLOBAL{\Var} \\
  11000. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11001. \end{array}
  11002. \]
  11003. \end{minipage}
  11004. }
  11005. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11006. \label{fig:x86-2}
  11007. \end{figure}
  11008. The concrete and abstract syntax of the \LangXGlobal{} language is
  11009. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11010. differs from \LangXIf{} just in the addition of global variables.
  11011. %
  11012. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11013. \code{select\_instructions} pass on the running example.
  11014. \begin{figure}[tbp]
  11015. \centering
  11016. % tests/s2_17.rkt
  11017. \begin{minipage}[t]{0.5\textwidth}
  11018. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11019. block35:
  11020. movq free_ptr(%rip), alloc9024
  11021. addq $16, free_ptr(%rip)
  11022. movq alloc9024, %r11
  11023. movq $131, 0(%r11)
  11024. movq alloc9024, %r11
  11025. movq vecinit9025, 8(%r11)
  11026. movq $0, initret9026
  11027. movq alloc9024, %r11
  11028. movq 8(%r11), tmp9034
  11029. movq tmp9034, %r11
  11030. movq 8(%r11), %rax
  11031. jmp conclusion
  11032. block36:
  11033. movq $0, collectret9027
  11034. jmp block35
  11035. block38:
  11036. movq free_ptr(%rip), alloc9020
  11037. addq $16, free_ptr(%rip)
  11038. movq alloc9020, %r11
  11039. movq $3, 0(%r11)
  11040. movq alloc9020, %r11
  11041. movq vecinit9021, 8(%r11)
  11042. movq $0, initret9022
  11043. movq alloc9020, vecinit9025
  11044. movq free_ptr(%rip), tmp9031
  11045. movq tmp9031, tmp9032
  11046. addq $16, tmp9032
  11047. movq fromspace_end(%rip), tmp9033
  11048. cmpq tmp9033, tmp9032
  11049. jl block36
  11050. jmp block37
  11051. block37:
  11052. movq %r15, %rdi
  11053. movq $16, %rsi
  11054. callq 'collect
  11055. jmp block35
  11056. block39:
  11057. movq $0, collectret9023
  11058. jmp block38
  11059. \end{lstlisting}
  11060. \end{minipage}
  11061. \begin{minipage}[t]{0.45\textwidth}
  11062. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11063. start:
  11064. movq $42, vecinit9021
  11065. movq free_ptr(%rip), tmp9028
  11066. movq tmp9028, tmp9029
  11067. addq $16, tmp9029
  11068. movq fromspace_end(%rip), tmp9030
  11069. cmpq tmp9030, tmp9029
  11070. jl block39
  11071. jmp block40
  11072. block40:
  11073. movq %r15, %rdi
  11074. movq $16, %rsi
  11075. callq 'collect
  11076. jmp block38
  11077. \end{lstlisting}
  11078. \end{minipage}
  11079. \caption{Output of the \code{select\_instructions} pass.}
  11080. \label{fig:select-instr-output-gc}
  11081. \end{figure}
  11082. \clearpage
  11083. \section{Register Allocation}
  11084. \label{sec:reg-alloc-gc}
  11085. \index{subject}{register allocation}
  11086. As discussed earlier in this chapter, the garbage collector needs to
  11087. access all the pointers in the root set, that is, all variables that
  11088. are tuples. It will be the responsibility of the register allocator
  11089. to make sure that:
  11090. \begin{enumerate}
  11091. \item the root stack is used for spilling tuple-typed variables, and
  11092. \item if a tuple-typed variable is live during a call to the
  11093. collector, it must be spilled to ensure it is visible to the
  11094. collector.
  11095. \end{enumerate}
  11096. The later responsibility can be handled during construction of the
  11097. interference graph, by adding interference edges between the call-live
  11098. tuple-typed variables and all the callee-saved registers. (They
  11099. already interfere with the caller-saved registers.)
  11100. %
  11101. \racket{The type information for variables is in the \code{Program}
  11102. form, so we recommend adding another parameter to the
  11103. \code{build\_interference} function to communicate this alist.}
  11104. %
  11105. \python{The type information for variables is generated by the type
  11106. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11107. the \code{CProgram} AST mode. You'll need to propagate that
  11108. information so that it is available in this pass.}
  11109. The spilling of tuple-typed variables to the root stack can be handled
  11110. after graph coloring, when choosing how to assign the colors
  11111. (integers) to registers and stack locations. The
  11112. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11113. changes to also record the number of spills to the root stack.
  11114. % build-interference
  11115. %
  11116. % callq
  11117. % extra parameter for var->type assoc. list
  11118. % update 'program' and 'if'
  11119. % allocate-registers
  11120. % allocate spilled vectors to the rootstack
  11121. % don't change color-graph
  11122. \section{Prelude and Conclusion}
  11123. \label{sec:print-x86-gc}
  11124. \label{sec:prelude-conclusion-x86-gc}
  11125. \index{subject}{prelude}\index{subject}{conclusion}
  11126. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11127. \code{prelude\_and\_conclusion} pass on the running example. In the
  11128. prelude and conclusion of the \code{main} function, we treat the root
  11129. stack very much like the regular stack in that we move the root stack
  11130. pointer (\code{r15}) to make room for the spills to the root stack,
  11131. except that the root stack grows up instead of down. For the running
  11132. example, there was just one spill so we increment \code{r15} by 8
  11133. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11134. One issue that deserves special care is that there may be a call to
  11135. \code{collect} prior to the initializing assignments for all the
  11136. variables in the root stack. We do not want the garbage collector to
  11137. accidentally think that some uninitialized variable is a pointer that
  11138. needs to be followed. Thus, we zero-out all locations on the root
  11139. stack in the prelude of \code{main}. In
  11140. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11141. %
  11142. \lstinline{movq $0, (%r15)}
  11143. %
  11144. accomplishes this task. The garbage collector tests each root to see
  11145. if it is null prior to dereferencing it.
  11146. \begin{figure}[htbp]
  11147. % TODO: Python Version -Jeremy
  11148. \begin{minipage}[t]{0.5\textwidth}
  11149. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11150. block35:
  11151. movq free_ptr(%rip), %rcx
  11152. addq $16, free_ptr(%rip)
  11153. movq %rcx, %r11
  11154. movq $131, 0(%r11)
  11155. movq %rcx, %r11
  11156. movq -8(%r15), %rax
  11157. movq %rax, 8(%r11)
  11158. movq $0, %rdx
  11159. movq %rcx, %r11
  11160. movq 8(%r11), %rcx
  11161. movq %rcx, %r11
  11162. movq 8(%r11), %rax
  11163. jmp conclusion
  11164. block36:
  11165. movq $0, %rcx
  11166. jmp block35
  11167. block38:
  11168. movq free_ptr(%rip), %rcx
  11169. addq $16, free_ptr(%rip)
  11170. movq %rcx, %r11
  11171. movq $3, 0(%r11)
  11172. movq %rcx, %r11
  11173. movq %rbx, 8(%r11)
  11174. movq $0, %rdx
  11175. movq %rcx, -8(%r15)
  11176. movq free_ptr(%rip), %rcx
  11177. addq $16, %rcx
  11178. movq fromspace_end(%rip), %rdx
  11179. cmpq %rdx, %rcx
  11180. jl block36
  11181. movq %r15, %rdi
  11182. movq $16, %rsi
  11183. callq collect
  11184. jmp block35
  11185. block39:
  11186. movq $0, %rcx
  11187. jmp block38
  11188. \end{lstlisting}
  11189. \end{minipage}
  11190. \begin{minipage}[t]{0.45\textwidth}
  11191. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11192. start:
  11193. movq $42, %rbx
  11194. movq free_ptr(%rip), %rdx
  11195. addq $16, %rdx
  11196. movq fromspace_end(%rip), %rcx
  11197. cmpq %rcx, %rdx
  11198. jl block39
  11199. movq %r15, %rdi
  11200. movq $16, %rsi
  11201. callq collect
  11202. jmp block38
  11203. .globl main
  11204. main:
  11205. pushq %rbp
  11206. movq %rsp, %rbp
  11207. pushq %r13
  11208. pushq %r12
  11209. pushq %rbx
  11210. pushq %r14
  11211. subq $0, %rsp
  11212. movq $16384, %rdi
  11213. movq $16384, %rsi
  11214. callq initialize
  11215. movq rootstack_begin(%rip), %r15
  11216. movq $0, (%r15)
  11217. addq $8, %r15
  11218. jmp start
  11219. conclusion:
  11220. subq $8, %r15
  11221. addq $0, %rsp
  11222. popq %r14
  11223. popq %rbx
  11224. popq %r12
  11225. popq %r13
  11226. popq %rbp
  11227. retq
  11228. \end{lstlisting}
  11229. \end{minipage}
  11230. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11231. \label{fig:print-x86-output-gc}
  11232. \end{figure}
  11233. \begin{figure}[p]
  11234. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11235. \node (Lvec) at (0,2) {\large \LangVec{}};
  11236. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11237. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11238. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11239. \node (Lvec-5) at (12,2) {\large \LangAllocANF{}};
  11240. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11241. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11242. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11243. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11244. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11245. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11246. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11247. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11248. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11249. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11250. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11251. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11252. \path[->,bend left=20] (Lvec-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11253. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11254. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11255. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11256. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11257. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11258. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11259. \end{tikzpicture}
  11260. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11261. \label{fig:Lvec-passes}
  11262. \end{figure}
  11263. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11264. for the compilation of \LangVec{}.
  11265. {\if\edition\racketEd
  11266. \section{Challenge: Simple Structures}
  11267. \label{sec:simple-structures}
  11268. \index{subject}{struct}
  11269. \index{subject}{structure}
  11270. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  11271. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  11272. Recall that a \code{struct} in Typed Racket is a user-defined data
  11273. type that contains named fields and that is heap allocated, similar to
  11274. a vector. The following is an example of a structure definition, in
  11275. this case the definition of a \code{point} type.
  11276. \begin{lstlisting}
  11277. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11278. \end{lstlisting}
  11279. \begin{figure}[tbp]
  11280. \centering
  11281. \fbox{
  11282. \begin{minipage}{0.96\textwidth}
  11283. \[
  11284. \begin{array}{lcl}
  11285. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  11286. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  11287. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  11288. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  11289. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  11290. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  11291. \MID (\key{and}\;\Exp\;\Exp)
  11292. \MID (\key{or}\;\Exp\;\Exp)
  11293. \MID (\key{not}\;\Exp) } \\
  11294. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  11295. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  11296. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  11297. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  11298. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  11299. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  11300. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11301. \LangStruct{} &::=& \Def \ldots \; \Exp
  11302. \end{array}
  11303. \]
  11304. \end{minipage}
  11305. }
  11306. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11307. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11308. \label{fig:r3s-concrete-syntax}
  11309. \end{figure}
  11310. An instance of a structure is created using function call syntax, with
  11311. the name of the structure in the function position:
  11312. \begin{lstlisting}
  11313. (point 7 12)
  11314. \end{lstlisting}
  11315. Function-call syntax is also used to read the value in a field of a
  11316. structure. The function name is formed by the structure name, a dash,
  11317. and the field name. The following example uses \code{point-x} and
  11318. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11319. instances.
  11320. \begin{center}
  11321. \begin{lstlisting}
  11322. (let ([pt1 (point 7 12)])
  11323. (let ([pt2 (point 4 3)])
  11324. (+ (- (point-x pt1) (point-x pt2))
  11325. (- (point-y pt1) (point-y pt2)))))
  11326. \end{lstlisting}
  11327. \end{center}
  11328. Similarly, to write to a field of a structure, use its set function,
  11329. whose name starts with \code{set-}, followed by the structure name,
  11330. then a dash, then the field name, and concluded with an exclamation
  11331. mark. The following example uses \code{set-point-x!} to change the
  11332. \code{x} field from \code{7} to \code{42}.
  11333. \begin{center}
  11334. \begin{lstlisting}
  11335. (let ([pt (point 7 12)])
  11336. (let ([_ (set-point-x! pt 42)])
  11337. (point-x pt)))
  11338. \end{lstlisting}
  11339. \end{center}
  11340. \begin{exercise}\normalfont
  11341. Extend your compiler with support for simple structures, compiling
  11342. \LangStruct{} to x86 assembly code. Create five new test cases that use
  11343. structures and test your compiler.
  11344. \end{exercise}
  11345. \section{Challenge: Arrays}
  11346. \label{sec:arrays}
  11347. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11348. elements whose length is determined at compile-time and where each
  11349. element of a tuple may have a different type (they are
  11350. heterogeous). This challenge is also about sequences, but this time
  11351. the length is determined at run-time and all the elements have the same
  11352. type (they are homogeneous). We use the term ``array'' for this later
  11353. kind of sequence.
  11354. The Racket language does not distinguish between tuples and arrays,
  11355. they are both represented by vectors. However, Typed Racket
  11356. distinguishes between tuples and arrays: the \code{Vector} type is for
  11357. tuples and the \code{Vectorof} type is for arrays.
  11358. %
  11359. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11360. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11361. and the \code{make-vector} primitive operator for creating an array,
  11362. whose arguments are the length of the array and an initial value for
  11363. all the elements in the array. The \code{vector-length},
  11364. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11365. for tuples become overloaded for use with arrays.
  11366. %
  11367. We also include integer multiplication in \LangArray{}, as it is
  11368. useful in many examples involving arrays such as computing the
  11369. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11370. \begin{figure}[tp]
  11371. \centering
  11372. \fbox{
  11373. \begin{minipage}{0.96\textwidth}
  11374. \small
  11375. \[
  11376. \begin{array}{lcl}
  11377. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11378. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11379. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11380. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11381. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11382. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11383. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11384. \MID \LP\key{not}\;\Exp\RP } \\
  11385. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11386. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11387. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11388. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11389. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11390. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11391. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11392. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11393. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11394. \MID \CWHILE{\Exp}{\Exp} } \\
  11395. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11396. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11397. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11398. \end{array}
  11399. \]
  11400. \end{minipage}
  11401. }
  11402. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11403. \label{fig:Lvecof-concrete-syntax}
  11404. \end{figure}
  11405. \begin{figure}[tp]
  11406. \begin{lstlisting}
  11407. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11408. [n : Integer]) : Integer
  11409. (let ([i 0])
  11410. (let ([prod 0])
  11411. (begin
  11412. (while (< i n)
  11413. (begin
  11414. (set! prod (+ prod (* (vector-ref A i)
  11415. (vector-ref B i))))
  11416. (set! i (+ i 1))
  11417. ))
  11418. prod))))
  11419. (let ([A (make-vector 2 2)])
  11420. (let ([B (make-vector 2 3)])
  11421. (+ (inner-product A B 2)
  11422. 30)))
  11423. \end{lstlisting}
  11424. \caption{Example program that computes the inner-product.}
  11425. \label{fig:inner-product}
  11426. \end{figure}
  11427. The type checker for \LangArray{} is define in
  11428. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11429. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11430. of the intializing expression. The length expression is required to
  11431. have type \code{Integer}. The type checking of the operators
  11432. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11433. updated to handle the situation where the vector has type
  11434. \code{Vectorof}. In these cases we translate the operators to their
  11435. \code{vectorof} form so that later passes can easily distinguish
  11436. between operations on tuples versus arrays. We override the
  11437. \code{operator-types} method to provide the type signature for
  11438. multiplication: it takes two integers and returns an integer. To
  11439. support injection and projection of arrays to the \code{Any} type
  11440. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11441. predicate.
  11442. \begin{figure}[tbp]
  11443. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11444. (define type-check-Lvecof_class
  11445. (class type-check-Rwhile_class
  11446. (super-new)
  11447. (inherit check-type-equal?)
  11448. (define/override (flat-ty? ty)
  11449. (match ty
  11450. ['(Vectorof Any) #t]
  11451. [else (super flat-ty? ty)]))
  11452. (define/override (operator-types)
  11453. (append '((* . ((Integer Integer) . Integer)))
  11454. (super operator-types)))
  11455. (define/override (type-check-exp env)
  11456. (lambda (e)
  11457. (define recur (type-check-exp env))
  11458. (match e
  11459. [(Prim 'make-vector (list e1 e2))
  11460. (define-values (e1^ t1) (recur e1))
  11461. (define-values (e2^ elt-type) (recur e2))
  11462. (define vec-type `(Vectorof ,elt-type))
  11463. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11464. vec-type)]
  11465. [(Prim 'vector-ref (list e1 e2))
  11466. (define-values (e1^ t1) (recur e1))
  11467. (define-values (e2^ t2) (recur e2))
  11468. (match* (t1 t2)
  11469. [(`(Vectorof ,elt-type) 'Integer)
  11470. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11471. [(other wise) ((super type-check-exp env) e)])]
  11472. [(Prim 'vector-set! (list e1 e2 e3) )
  11473. (define-values (e-vec t-vec) (recur e1))
  11474. (define-values (e2^ t2) (recur e2))
  11475. (define-values (e-arg^ t-arg) (recur e3))
  11476. (match t-vec
  11477. [`(Vectorof ,elt-type)
  11478. (check-type-equal? elt-type t-arg e)
  11479. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11480. [else ((super type-check-exp env) e)])]
  11481. [(Prim 'vector-length (list e1))
  11482. (define-values (e1^ t1) (recur e1))
  11483. (match t1
  11484. [`(Vectorof ,t)
  11485. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11486. [else ((super type-check-exp env) e)])]
  11487. [else ((super type-check-exp env) e)])))
  11488. ))
  11489. (define (type-check-Lvecof p)
  11490. (send (new type-check-Lvecof_class) type-check-program p))
  11491. \end{lstlisting}
  11492. \caption{Type checker for the \LangArray{} language.}
  11493. \label{fig:type-check-Lvecof}
  11494. \end{figure}
  11495. The interpreter for \LangArray{} is defined in
  11496. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11497. implemented with Racket's \code{make-vector} function and
  11498. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11499. integers.
  11500. \begin{figure}[tbp]
  11501. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11502. (define interp-Lvecof_class
  11503. (class interp-Rwhile_class
  11504. (super-new)
  11505. (define/override (interp-op op)
  11506. (verbose "Lvecof/interp-op" op)
  11507. (match op
  11508. ['make-vector make-vector]
  11509. ['* fx*]
  11510. [else (super interp-op op)]))
  11511. ))
  11512. (define (interp-Lvecof p)
  11513. (send (new interp-Lvecof_class) interp-program p))
  11514. \end{lstlisting}
  11515. \caption{Interpreter for \LangArray{}.}
  11516. \label{fig:interp-Lvecof}
  11517. \end{figure}
  11518. \subsection{Data Representation}
  11519. \label{sec:array-rep}
  11520. Just like tuples, we store arrays on the heap which means that the
  11521. garbage collector will need to inspect arrays. An immediate thought is
  11522. to use the same representation for arrays that we use for tuples.
  11523. However, we limit tuples to a length of $50$ so that their length and
  11524. pointer mask can fit into the 64-bit tag at the beginning of each
  11525. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11526. millions of elements, so we need more bits to store the length.
  11527. However, because arrays are homogeneous, we only need $1$ bit for the
  11528. pointer mask instead of one bit per array elements. Finally, the
  11529. garbage collector will need to be able to distinguish between tuples
  11530. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11531. arrive at the following layout for the 64-bit tag at the beginning of
  11532. an array:
  11533. \begin{itemize}
  11534. \item The right-most bit is the forwarding bit, just like in a tuple.
  11535. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11536. it is not.
  11537. \item The next bit to the left is the pointer mask. A $0$ indicates
  11538. that none of the elements are pointers to the heap and a $1$
  11539. indicates that all of the elements are pointers.
  11540. \item The next $61$ bits store the length of the array.
  11541. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11542. array ($1$).
  11543. \end{itemize}
  11544. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  11545. differentiate the kinds of values that have been injected into the
  11546. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11547. to indicate that the value is an array.
  11548. In the following subsections we provide hints regarding how to update
  11549. the passes to handle arrays.
  11550. \subsection{Reveal Casts}
  11551. The array-access operators \code{vectorof-ref} and
  11552. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11553. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  11554. that the type checker cannot tell whether the index will be in bounds,
  11555. so the bounds check must be performed at run time. Recall that the
  11556. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11557. an \code{If} arround a vector reference for update to check whether
  11558. the index is less than the length. You should do the same for
  11559. \code{vectorof-ref} and \code{vectorof-set!} .
  11560. In addition, the handling of the \code{any-vector} operators in
  11561. \code{reveal-casts} needs to be updated to account for arrays that are
  11562. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11563. generated code should test whether the tag is for tuples (\code{010})
  11564. or arrays (\code{110}) and then dispatch to either
  11565. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11566. we add a case in \code{select\_instructions} to generate the
  11567. appropriate instructions for accessing the array length from the
  11568. header of an array.
  11569. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11570. the generated code needs to check that the index is less than the
  11571. vector length, so like the code for \code{any-vector-length}, check
  11572. the tag to determine whether to use \code{any-vector-length} or
  11573. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11574. is complete, the generated code can use \code{any-vector-ref} and
  11575. \code{any-vector-set!} for both tuples and arrays because the
  11576. instructions used for those operators do not look at the tag at the
  11577. front of the tuple or array.
  11578. \subsection{Expose Allocation}
  11579. This pass should translate the \code{make-vector} operator into
  11580. lower-level operations. In particular, the new AST node
  11581. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11582. length specified by the $\Exp$, but does not initialize the elements
  11583. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11584. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11585. element type for the array. Regarding the initialization of the array,
  11586. we recommend generated a \code{while} loop that uses
  11587. \code{vector-set!} to put the initializing value into every element of
  11588. the array.
  11589. \subsection{Remove Complex Operands}
  11590. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11591. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11592. complex and its subexpression must be atomic.
  11593. \subsection{Explicate Control}
  11594. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11595. \code{explicate\_assign}.
  11596. \subsection{Select Instructions}
  11597. Generate instructions for \code{AllocateArray} similar to those for
  11598. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11599. that the tag at the front of the array should instead use the
  11600. representation discussed in Section~\ref{sec:array-rep}.
  11601. Regarding \code{vectorof-length}, extract the length from the tag
  11602. according to the representation discussed in
  11603. Section~\ref{sec:array-rep}.
  11604. The instructions generated for \code{vectorof-ref} differ from those
  11605. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11606. that the index is not a constant so the offset must be computed at
  11607. runtime, similar to the instructions generated for
  11608. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11609. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11610. appear in an assignment and as a stand-alone statement, so make sure
  11611. to handle both situations in this pass.
  11612. Finally, the instructions for \code{any-vectorof-length} should be
  11613. similar to those for \code{vectorof-length}, except that one must
  11614. first project the array by writing zeroes into the $3$-bit tag
  11615. \begin{exercise}\normalfont
  11616. Implement a compiler for the \LangArray{} language by extending your
  11617. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11618. programs, including the one in Figure~\ref{fig:inner-product} and also
  11619. a program that multiplies two matrices. Note that matrices are
  11620. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11621. arrays by laying out each row in the array, one after the next.
  11622. \end{exercise}
  11623. \section{Challenge: Generational Collection}
  11624. The copying collector described in Section~\ref{sec:GC} can incur
  11625. significant runtime overhead because the call to \code{collect} takes
  11626. time proportional to all of the live data. One way to reduce this
  11627. overhead is to reduce how much data is inspected in each call to
  11628. \code{collect}. In particular, researchers have observed that recently
  11629. allocated data is more likely to become garbage then data that has
  11630. survived one or more previous calls to \code{collect}. This insight
  11631. motivated the creation of \emph{generational garbage collectors}
  11632. \index{subject}{generational garbage collector} that
  11633. 1) segregates data according to its age into two or more generations,
  11634. 2) allocates less space for younger generations, so collecting them is
  11635. faster, and more space for the older generations, and 3) performs
  11636. collection on the younger generations more frequently then for older
  11637. generations~\citep{Wilson:1992fk}.
  11638. For this challenge assignment, the goal is to adapt the copying
  11639. collector implemented in \code{runtime.c} to use two generations, one
  11640. for young data and one for old data. Each generation consists of a
  11641. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11642. \code{collect} function to use the two generations.
  11643. \begin{enumerate}
  11644. \item Copy the young generation's FromSpace to its ToSpace then switch
  11645. the role of the ToSpace and FromSpace
  11646. \item If there is enough space for the requested number of bytes in
  11647. the young FromSpace, then return from \code{collect}.
  11648. \item If there is not enough space in the young FromSpace for the
  11649. requested bytes, then move the data from the young generation to the
  11650. old one with the following steps:
  11651. \begin{enumerate}
  11652. \item If there is enough room in the old FromSpace, copy the young
  11653. FromSpace to the old FromSpace and then return.
  11654. \item If there is not enough room in the old FromSpace, then collect
  11655. the old generation by copying the old FromSpace to the old ToSpace
  11656. and swap the roles of the old FromSpace and ToSpace.
  11657. \item If there is enough room now, copy the young FromSpace to the
  11658. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11659. and ToSpace for the old generation. Copy the young FromSpace and
  11660. the old FromSpace into the larger FromSpace for the old
  11661. generation and then return.
  11662. \end{enumerate}
  11663. \end{enumerate}
  11664. We recommend that you generalize the \code{cheney} function so that it
  11665. can be used for all the copies mentioned above: between the young
  11666. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11667. between the young FromSpace and old FromSpace. This can be
  11668. accomplished by adding parameters to \code{cheney} that replace its
  11669. use of the global variables \code{fromspace\_begin},
  11670. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11671. Note that the collection of the young generation does not traverse the
  11672. old generation. This introduces a potential problem: there may be
  11673. young data that is only reachable through pointers in the old
  11674. generation. If these pointers are not taken into account, the
  11675. collector could throw away young data that is live! One solution,
  11676. called \emph{pointer recording}, is to maintain a set of all the
  11677. pointers from the old generation into the new generation and consider
  11678. this set as part of the root set. To maintain this set, the compiler
  11679. must insert extra instructions around every \code{vector-set!}. If the
  11680. vector being modified is in the old generation, and if the value being
  11681. written is a pointer into the new generation, than that pointer must
  11682. be added to the set. Also, if the value being overwritten was a
  11683. pointer into the new generation, then that pointer should be removed
  11684. from the set.
  11685. \begin{exercise}\normalfont
  11686. Adapt the \code{collect} function in \code{runtime.c} to implement
  11687. generational garbage collection, as outlined in this section.
  11688. Update the code generation for \code{vector-set!} to implement
  11689. pointer recording. Make sure that your new compiler and runtime
  11690. passes your test suite.
  11691. \end{exercise}
  11692. \fi}
  11693. % Further Reading
  11694. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11695. \chapter{Functions}
  11696. \label{ch:Rfun}
  11697. \index{subject}{function}
  11698. \if\edition\racketEd
  11699. This chapter studies the compilation of functions similar to those
  11700. found in the C language. This corresponds to a subset of Typed Racket
  11701. in which only top-level function definitions are allowed. This kind of
  11702. function is an important stepping stone to implementing
  11703. lexically-scoped functions, that is, \key{lambda} abstractions, which
  11704. is the topic of Chapter~\ref{ch:Rlam}.
  11705. \section{The \LangFun{} Language}
  11706. The concrete and abstract syntax for function definitions and function
  11707. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11708. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11709. \LangFun{} begin with zero or more function definitions. The function
  11710. names from these definitions are in-scope for the entire program,
  11711. including all other function definitions (so the ordering of function
  11712. definitions does not matter). The concrete syntax for function
  11713. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  11714. where the first expression must
  11715. evaluate to a function and the rest are the arguments.
  11716. The abstract syntax for function application is
  11717. $\APPLY{\Exp}{\Exp\ldots}$.
  11718. %% The syntax for function application does not include an explicit
  11719. %% keyword, which is error prone when using \code{match}. To alleviate
  11720. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  11721. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  11722. Functions are first-class in the sense that a function pointer
  11723. \index{subject}{function pointer} is data and can be stored in memory or passed
  11724. as a parameter to another function. Thus, we introduce a function
  11725. type, written
  11726. \begin{lstlisting}
  11727. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  11728. \end{lstlisting}
  11729. for a function whose $n$ parameters have the types $\Type_1$ through
  11730. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  11731. these functions (with respect to Racket functions) is that they are
  11732. not lexically scoped. That is, the only external entities that can be
  11733. referenced from inside a function body are other globally-defined
  11734. functions. The syntax of \LangFun{} prevents functions from being nested
  11735. inside each other.
  11736. \newcommand{\LfunGrammarRacket}{
  11737. \begin{array}{lcl}
  11738. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11739. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  11740. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11741. \end{array}
  11742. }
  11743. \newcommand{\LfunAST}{
  11744. \begin{array}{lcl}
  11745. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11746. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  11747. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  11748. \end{array}
  11749. }
  11750. \begin{figure}[tp]
  11751. \centering
  11752. \fbox{
  11753. \begin{minipage}{0.96\textwidth}
  11754. \small
  11755. \[
  11756. \begin{array}{l}
  11757. \gray{\LintGrammarRacket{}} \\ \hline
  11758. \gray{\LvarGrammarRacket{}} \\ \hline
  11759. \gray{\LifGrammarRacket{}} \\ \hline
  11760. \gray{\LwhileGrammarRacket} \\ \hline
  11761. \gray{\LtupGrammarRacket} \\ \hline
  11762. \LfunGrammarRacket \\
  11763. \begin{array}{lcl}
  11764. %% \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  11765. %% \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  11766. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  11767. %% \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11768. %% &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11769. %% &\MID& \gray{ \key{\#t} \MID \key{\#f}
  11770. %% \MID (\key{and}\;\Exp\;\Exp)
  11771. %% \MID (\key{or}\;\Exp\;\Exp)
  11772. %% \MID (\key{not}\;\Exp)} \\
  11773. %% &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11774. %% &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  11775. %% (\key{vector-ref}\;\Exp\;\Int)} \\
  11776. %% &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11777. %% \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  11778. %% &\MID& \LP\Exp \; \Exp \ldots\RP \\
  11779. %% \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11780. \LangFunM{} &::=& \Def \ldots \; \Exp
  11781. \end{array}
  11782. \end{array}
  11783. \]
  11784. \end{minipage}
  11785. }
  11786. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11787. \label{fig:Rfun-concrete-syntax}
  11788. \end{figure}
  11789. \begin{figure}[tp]
  11790. \centering
  11791. \fbox{
  11792. \begin{minipage}{0.96\textwidth}
  11793. \small
  11794. \[
  11795. \begin{array}{l}
  11796. \gray{\LintOpAST} \\ \hline
  11797. \gray{\LvarAST{}} \\ \hline
  11798. \gray{\LifAST{}} \\ \hline
  11799. \gray{\LwhileAST{}} \\ \hline
  11800. \gray{\LtupAST{}} \\ \hline
  11801. \LfunAST \\
  11802. \begin{array}{lcl}
  11803. %% \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11804. %% &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11805. %% &\MID& \gray{ \BOOL{\itm{bool}}
  11806. %% \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11807. %% &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  11808. %% \MID \APPLY{\Exp}{\Exp\ldots}\\
  11809. %% \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  11810. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11811. \end{array}
  11812. \end{array}
  11813. \]
  11814. \end{minipage}
  11815. }
  11816. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  11817. \label{fig:Rfun-syntax}
  11818. \end{figure}
  11819. The program in Figure~\ref{fig:Rfun-function-example} is a
  11820. representative example of defining and using functions in \LangFun{}. We
  11821. define a function \code{map-vec} that applies some other function
  11822. \code{f} to both elements of a vector and returns a new
  11823. vector containing the results. We also define a function \code{add1}.
  11824. The program applies
  11825. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  11826. \code{(vector 1 42)}, from which we return the \code{42}.
  11827. \begin{figure}[tbp]
  11828. \begin{lstlisting}
  11829. (define (map-vec [f : (Integer -> Integer)]
  11830. [v : (Vector Integer Integer)])
  11831. : (Vector Integer Integer)
  11832. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11833. (define (add1 [x : Integer]) : Integer
  11834. (+ x 1))
  11835. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11836. \end{lstlisting}
  11837. \caption{Example of using functions in \LangFun{}.}
  11838. \label{fig:Rfun-function-example}
  11839. \end{figure}
  11840. The definitional interpreter for \LangFun{} is in
  11841. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  11842. responsible for setting up the mutual recursion between the top-level
  11843. function definitions. We use the classic back-patching \index{subject}{back-patching}
  11844. approach that uses mutable variables and makes two passes over the function
  11845. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  11846. top-level environment using a mutable cons cell for each function
  11847. definition. Note that the \code{lambda} value for each function is
  11848. incomplete; it does not yet include the environment. Once the
  11849. top-level environment is constructed, we then iterate over it and
  11850. update the \code{lambda} values to use the top-level environment.
  11851. \begin{figure}[tp]
  11852. \begin{lstlisting}
  11853. (define interp-Rfun_class
  11854. (class interp-Lvec_class
  11855. (super-new)
  11856. (define/override ((interp-exp env) e)
  11857. (define recur (interp-exp env))
  11858. (match e
  11859. [(Var x) (unbox (dict-ref env x))]
  11860. [(Let x e body)
  11861. (define new-env (dict-set env x (box (recur e))))
  11862. ((interp-exp new-env) body)]
  11863. [(Apply fun args)
  11864. (define fun-val (recur fun))
  11865. (define arg-vals (for/list ([e args]) (recur e)))
  11866. (match fun-val
  11867. [`(function (,xs ...) ,body ,fun-env)
  11868. (define params-args (for/list ([x xs] [arg arg-vals])
  11869. (cons x (box arg))))
  11870. (define new-env (append params-args fun-env))
  11871. ((interp-exp new-env) body)]
  11872. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  11873. [else ((super interp-exp env) e)]
  11874. ))
  11875. (define/public (interp-def d)
  11876. (match d
  11877. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  11878. (cons f (box `(function ,xs ,body ())))]))
  11879. (define/override (interp-program p)
  11880. (match p
  11881. [(ProgramDefsExp info ds body)
  11882. (let ([top-level (for/list ([d ds]) (interp-def d))])
  11883. (for/list ([f (in-dict-values top-level)])
  11884. (set-box! f (match (unbox f)
  11885. [`(function ,xs ,body ())
  11886. `(function ,xs ,body ,top-level)])))
  11887. ((interp-exp top-level) body))]))
  11888. ))
  11889. (define (interp-Rfun p)
  11890. (send (new interp-Rfun_class) interp-program p))
  11891. \end{lstlisting}
  11892. \caption{Interpreter for the \LangFun{} language.}
  11893. \label{fig:interp-Rfun}
  11894. \end{figure}
  11895. %\margincomment{TODO: explain type checker}
  11896. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  11897. \begin{figure}[tp]
  11898. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11899. (define type-check-Rfun_class
  11900. (class type-check-Lvec_class
  11901. (super-new)
  11902. (inherit check-type-equal?)
  11903. (define/public (type-check-apply env e es)
  11904. (define-values (e^ ty) ((type-check-exp env) e))
  11905. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  11906. ((type-check-exp env) e)))
  11907. (match ty
  11908. [`(,ty^* ... -> ,rt)
  11909. (for ([arg-ty ty*] [param-ty ty^*])
  11910. (check-type-equal? arg-ty param-ty (Apply e es)))
  11911. (values e^ e* rt)]))
  11912. (define/override (type-check-exp env)
  11913. (lambda (e)
  11914. (match e
  11915. [(FunRef f)
  11916. (values (FunRef f) (dict-ref env f))]
  11917. [(Apply e es)
  11918. (define-values (e^ es^ rt) (type-check-apply env e es))
  11919. (values (Apply e^ es^) rt)]
  11920. [(Call e es)
  11921. (define-values (e^ es^ rt) (type-check-apply env e es))
  11922. (values (Call e^ es^) rt)]
  11923. [else ((super type-check-exp env) e)])))
  11924. (define/public (type-check-def env)
  11925. (lambda (e)
  11926. (match e
  11927. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  11928. (define new-env (append (map cons xs ps) env))
  11929. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11930. (check-type-equal? ty^ rt body)
  11931. (Def f p:t* rt info body^)])))
  11932. (define/public (fun-def-type d)
  11933. (match d
  11934. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  11935. (define/override (type-check-program e)
  11936. (match e
  11937. [(ProgramDefsExp info ds body)
  11938. (define new-env (for/list ([d ds])
  11939. (cons (Def-name d) (fun-def-type d))))
  11940. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  11941. (define-values (body^ ty) ((type-check-exp new-env) body))
  11942. (check-type-equal? ty 'Integer body)
  11943. (ProgramDefsExp info ds^ body^)]))))
  11944. (define (type-check-Rfun p)
  11945. (send (new type-check-Rfun_class) type-check-program p))
  11946. \end{lstlisting}
  11947. \caption{Type checker for the \LangFun{} language.}
  11948. \label{fig:type-check-Rfun}
  11949. \end{figure}
  11950. \section{Functions in x86}
  11951. \label{sec:fun-x86}
  11952. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  11953. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  11954. %% \margincomment{\tiny Talk about the return address on the
  11955. %% stack and what callq and retq does.\\ --Jeremy }
  11956. The x86 architecture provides a few features to support the
  11957. implementation of functions. We have already seen that x86 provides
  11958. labels so that one can refer to the location of an instruction, as is
  11959. needed for jump instructions. Labels can also be used to mark the
  11960. beginning of the instructions for a function. Going further, we can
  11961. obtain the address of a label by using the \key{leaq} instruction and
  11962. PC-relative addressing. For example, the following puts the
  11963. address of the \code{add1} label into the \code{rbx} register.
  11964. \begin{lstlisting}
  11965. leaq add1(%rip), %rbx
  11966. \end{lstlisting}
  11967. The instruction pointer register \key{rip} (aka. the program counter
  11968. \index{subject}{program counter}) always points to the next instruction to be
  11969. executed. When combined with an label, as in \code{add1(\%rip)}, the
  11970. linker computes the distance $d$ between the address of \code{add1}
  11971. and where the \code{rip} would be at that moment and then changes
  11972. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  11973. the address of \code{add1}.
  11974. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  11975. to functions whose locations were given by a label, such as
  11976. \code{read\_int}. To support function calls in this chapter we instead
  11977. will be jumping to functions whose location are given by an address in
  11978. a register, that is, we need to make an \emph{indirect function
  11979. call}. The x86 syntax for this is a \code{callq} instruction but with
  11980. an asterisk before the register name.\index{subject}{indirect function
  11981. call}
  11982. \begin{lstlisting}
  11983. callq *%rbx
  11984. \end{lstlisting}
  11985. \subsection{Calling Conventions}
  11986. \index{subject}{calling conventions}
  11987. The \code{callq} instruction provides partial support for implementing
  11988. functions: it pushes the return address on the stack and it jumps to
  11989. the target. However, \code{callq} does not handle
  11990. \begin{enumerate}
  11991. \item parameter passing,
  11992. \item pushing frames on the procedure call stack and popping them off,
  11993. or
  11994. \item determining how registers are shared by different functions.
  11995. \end{enumerate}
  11996. Regarding (1) parameter passing, recall that the following six
  11997. registers are used to pass arguments to a function, in this order.
  11998. \begin{lstlisting}
  11999. rdi rsi rdx rcx r8 r9
  12000. \end{lstlisting}
  12001. If there are
  12002. more than six arguments, then the convention is to use space on the
  12003. frame of the caller for the rest of the arguments. However, to ease
  12004. the implementation of efficient tail calls
  12005. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12006. arguments.
  12007. %
  12008. Also recall that the register \code{rax} is for the return value of
  12009. the function.
  12010. \index{subject}{prelude}\index{subject}{conclusion}
  12011. Regarding (2) frames \index{subject}{frame} and the procedure call
  12012. stack, \index{subject}{procedure call stack} recall from
  12013. Section~\ref{sec:x86} that the stack grows down and each function call
  12014. uses a chunk of space on the stack called a frame. The caller sets the
  12015. stack pointer, register \code{rsp}, to the last data item in its
  12016. frame. The callee must not change anything in the caller's frame, that
  12017. is, anything that is at or above the stack pointer. The callee is free
  12018. to use locations that are below the stack pointer.
  12019. Recall that we are storing variables of tuple type on the root stack.
  12020. So the prelude needs to move the root stack pointer \code{r15} up and
  12021. the conclusion needs to move the root stack pointer back down. Also,
  12022. the prelude must initialize to \code{0} this frame's slots in the root
  12023. stack to signal to the garbage collector that those slots do not yet
  12024. contain a pointer to a vector. Otherwise the garbage collector will
  12025. interpret the garbage bits in those slots as memory addresses and try
  12026. to traverse them, causing serious mayhem!
  12027. Regarding (3) the sharing of registers between different functions,
  12028. recall from Section~\ref{sec:calling-conventions} that the registers
  12029. are divided into two groups, the caller-saved registers and the
  12030. callee-saved registers. The caller should assume that all the
  12031. caller-saved registers get overwritten with arbitrary values by the
  12032. callee. That is why we recommend in
  12033. Section~\ref{sec:calling-conventions} that variables that are live
  12034. during a function call should not be assigned to caller-saved
  12035. registers.
  12036. On the flip side, if the callee wants to use a callee-saved register,
  12037. the callee must save the contents of those registers on their stack
  12038. frame and then put them back prior to returning to the caller. That
  12039. is why we recommended in Section~\ref{sec:calling-conventions} that if
  12040. the register allocator assigns a variable to a callee-saved register,
  12041. then the prelude of the \code{main} function must save that register
  12042. to the stack and the conclusion of \code{main} must restore it. This
  12043. recommendation now generalizes to all functions.
  12044. Recall that the base pointer, register \code{rbp}, is used as a
  12045. point-of-reference within a frame, so that each local variable can be
  12046. accessed at a fixed offset from the base pointer
  12047. (Section~\ref{sec:x86}).
  12048. %
  12049. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12050. and callee frames.
  12051. \begin{figure}[tbp]
  12052. \centering
  12053. \begin{tabular}{r|r|l|l} \hline
  12054. Caller View & Callee View & Contents & Frame \\ \hline
  12055. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12056. 0(\key{\%rbp}) & & old \key{rbp} \\
  12057. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12058. \ldots & & \ldots \\
  12059. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12060. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12061. \ldots & & \ldots \\
  12062. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12063. %% & & \\
  12064. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12065. %% & \ldots & \ldots \\
  12066. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12067. \hline
  12068. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12069. & 0(\key{\%rbp}) & old \key{rbp} \\
  12070. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12071. & \ldots & \ldots \\
  12072. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12073. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12074. & \ldots & \ldots \\
  12075. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  12076. \end{tabular}
  12077. \caption{Memory layout of caller and callee frames.}
  12078. \label{fig:call-frames}
  12079. \end{figure}
  12080. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12081. %% local variables and for storing the values of callee-saved registers
  12082. %% (we shall refer to all of these collectively as ``locals''), and that
  12083. %% at the beginning of a function we move the stack pointer \code{rsp}
  12084. %% down to make room for them.
  12085. %% We recommend storing the local variables
  12086. %% first and then the callee-saved registers, so that the local variables
  12087. %% can be accessed using \code{rbp} the same as before the addition of
  12088. %% functions.
  12089. %% To make additional room for passing arguments, we shall
  12090. %% move the stack pointer even further down. We count how many stack
  12091. %% arguments are needed for each function call that occurs inside the
  12092. %% body of the function and find their maximum. Adding this number to the
  12093. %% number of locals gives us how much the \code{rsp} should be moved at
  12094. %% the beginning of the function. In preparation for a function call, we
  12095. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12096. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12097. %% so on.
  12098. %% Upon calling the function, the stack arguments are retrieved by the
  12099. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12100. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12101. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12102. %% the layout of the caller and callee frames. Notice how important it is
  12103. %% that we correctly compute the maximum number of arguments needed for
  12104. %% function calls; if that number is too small then the arguments and
  12105. %% local variables will smash into each other!
  12106. \subsection{Efficient Tail Calls}
  12107. \label{sec:tail-call}
  12108. In general, the amount of stack space used by a program is determined
  12109. by the longest chain of nested function calls. That is, if function
  12110. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  12111. $f_n$, then the amount of stack space is linear in $n$. The depth $n$
  12112. can grow quite large in the case of recursive or mutually recursive
  12113. functions. However, in some cases we can arrange to use only a
  12114. constant amount of space for a long chain of nested function calls.
  12115. If a function call is the last action in a function body, then that
  12116. call is said to be a \emph{tail call}\index{subject}{tail call}.
  12117. For example, in the following
  12118. program, the recursive call to \code{tail\_sum} is a tail call.
  12119. \begin{center}
  12120. \begin{lstlisting}
  12121. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12122. (if (eq? n 0)
  12123. r
  12124. (tail_sum (- n 1) (+ n r))))
  12125. (+ (tail_sum 5 0) 27)
  12126. \end{lstlisting}
  12127. \end{center}
  12128. At a tail call, the frame of the caller is no longer needed, so we can
  12129. pop the caller's frame before making the tail call. With this
  12130. approach, a recursive function that only makes tail calls will only
  12131. use a constant amount of stack space. Functional languages like
  12132. Racket typically rely heavily on recursive functions, so they
  12133. typically guarantee that all tail calls will be optimized in this way.
  12134. \index{subject}{frame}
  12135. Some care is needed with regards to argument passing in tail calls.
  12136. As mentioned above, for arguments beyond the sixth, the convention is
  12137. to use space in the caller's frame for passing arguments. But for a
  12138. tail call we pop the caller's frame and can no longer use it. An
  12139. alternative is to use space in the callee's frame for passing
  12140. arguments. However, this option is also problematic because the caller
  12141. and callee's frames overlap in memory. As we begin to copy the
  12142. arguments from their sources in the caller's frame, the target
  12143. locations in the callee's frame might collide with the sources for
  12144. later arguments! We solve this problem by using the heap instead of
  12145. the stack for passing more than six arguments, which we describe in
  12146. the Section~\ref{sec:limit-functions-r4}.
  12147. As mentioned above, for a tail call we pop the caller's frame prior to
  12148. making the tail call. The instructions for popping a frame are the
  12149. instructions that we usually place in the conclusion of a
  12150. function. Thus, we also need to place such code immediately before
  12151. each tail call. These instructions include restoring the callee-saved
  12152. registers, so it is fortunate that the argument passing registers are
  12153. all caller-saved registers!
  12154. One last note regarding which instruction to use to make the tail
  12155. call. When the callee is finished, it should not return to the current
  12156. function, but it should return to the function that called the current
  12157. one. Thus, the return address that is already on the stack is the
  12158. right one, and we should not use \key{callq} to make the tail call, as
  12159. that would unnecessarily overwrite the return address. Instead we can
  12160. simply use the \key{jmp} instruction. Like the indirect function call,
  12161. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12162. register prefixed with an asterisk. We recommend using \code{rax} to
  12163. hold the jump target because the preceding conclusion can overwrite
  12164. just about everything else.
  12165. \begin{lstlisting}
  12166. jmp *%rax
  12167. \end{lstlisting}
  12168. \section{Shrink \LangFun{}}
  12169. \label{sec:shrink-r4}
  12170. The \code{shrink} pass performs a minor modification to ease the
  12171. later passes. This pass introduces an explicit \code{main} function
  12172. and changes the top \code{ProgramDefsExp} form to
  12173. \code{ProgramDefs} as follows.
  12174. \begin{lstlisting}
  12175. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12176. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12177. \end{lstlisting}
  12178. where $\itm{mainDef}$ is
  12179. \begin{lstlisting}
  12180. (Def 'main '() 'Integer '() |$\Exp'$|)
  12181. \end{lstlisting}
  12182. \section{Reveal Functions and the \LangFunRef{} language}
  12183. \label{sec:reveal-functions-r4}
  12184. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  12185. respect: it conflates the use of function names and local
  12186. variables. This is a problem because we need to compile the use of a
  12187. function name differently than the use of a local variable; we need to
  12188. use \code{leaq} to convert the function name (a label in x86) to an
  12189. address in a register. Thus, it is a good idea to create a new pass
  12190. that changes function references from just a symbol $f$ to
  12191. $\FUNREF{f}$. This pass is named \code{reveal\_functions} and the
  12192. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  12193. The concrete syntax for a function reference is $\CFUNREF{f}$.
  12194. \begin{figure}[tp]
  12195. \centering
  12196. \fbox{
  12197. \begin{minipage}{0.96\textwidth}
  12198. \[
  12199. \begin{array}{lcl}
  12200. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  12201. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12202. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12203. \end{array}
  12204. \]
  12205. \end{minipage}
  12206. }
  12207. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12208. (Figure~\ref{fig:Rfun-syntax}).}
  12209. \label{fig:f1-syntax}
  12210. \end{figure}
  12211. %% Distinguishing between calls in tail position and non-tail position
  12212. %% requires the pass to have some notion of context. We recommend using
  12213. %% two mutually recursive functions, one for processing expressions in
  12214. %% tail position and another for the rest.
  12215. Placing this pass after \code{uniquify} will make sure that there are
  12216. no local variables and functions that share the same name. On the
  12217. other hand, \code{reveal\_functions} needs to come before the
  12218. \code{remove\_complex\_operands} pass because function references
  12219. should be categorized as complex expressions.
  12220. \section{Limit Functions}
  12221. \label{sec:limit-functions-r4}
  12222. Recall that we wish to limit the number of function parameters to six
  12223. so that we do not need to use the stack for argument passing, which
  12224. makes it easier to implement efficient tail calls. However, because
  12225. the input language \LangFun{} supports arbitrary numbers of function
  12226. arguments, we have some work to do!
  12227. This pass transforms functions and function calls that involve more
  12228. than six arguments to pass the first five arguments as usual, but it
  12229. packs the rest of the arguments into a vector and passes it as the
  12230. sixth argument.
  12231. Each function definition with too many parameters is transformed as
  12232. follows.
  12233. \begin{lstlisting}
  12234. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12235. |$\Rightarrow$|
  12236. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12237. \end{lstlisting}
  12238. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  12239. the occurrences of the later parameters with vector references.
  12240. \begin{lstlisting}
  12241. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  12242. \end{lstlisting}
  12243. For function calls with too many arguments, the \code{limit-functions}
  12244. pass transforms them in the following way.
  12245. \begin{tabular}{lll}
  12246. \begin{minipage}{0.2\textwidth}
  12247. \begin{lstlisting}
  12248. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12249. \end{lstlisting}
  12250. \end{minipage}
  12251. &
  12252. $\Rightarrow$
  12253. &
  12254. \begin{minipage}{0.4\textwidth}
  12255. \begin{lstlisting}
  12256. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12257. \end{lstlisting}
  12258. \end{minipage}
  12259. \end{tabular}
  12260. \section{Remove Complex Operands}
  12261. \label{sec:rco-r4}
  12262. The primary decisions to make for this pass is whether to classify
  12263. \code{FunRef} and \code{Apply} as either atomic or complex
  12264. expressions. Recall that a simple expression will eventually end up as
  12265. just an immediate argument of an x86 instruction. Function
  12266. application will be translated to a sequence of instructions, so
  12267. \code{Apply} must be classified as complex expression.
  12268. On the other hand, the arguments of \code{Apply} should be
  12269. atomic expressions.
  12270. %
  12271. Regarding \code{FunRef}, as discussed above, the function label needs
  12272. to be converted to an address using the \code{leaq} instruction. Thus,
  12273. even though \code{FunRef} seems rather simple, it needs to be
  12274. classified as a complex expression so that we generate an assignment
  12275. statement with a left-hand side that can serve as the target of the
  12276. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  12277. output language \LangFunANF{} of this pass.
  12278. \begin{figure}[tp]
  12279. \centering
  12280. \fbox{
  12281. \begin{minipage}{0.96\textwidth}
  12282. \small
  12283. \[
  12284. \begin{array}{rcl}
  12285. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12286. \MID \VOID{} } \\
  12287. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12288. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12289. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12290. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12291. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12292. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12293. \MID \LP\key{GlobalValue}~\Var\RP }\\
  12294. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12295. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12296. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12297. \end{array}
  12298. \]
  12299. \end{minipage}
  12300. }
  12301. \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12302. \label{fig:Rfun-anf-syntax}
  12303. \end{figure}
  12304. \section{Explicate Control and the \LangCFun{} language}
  12305. \label{sec:explicate-control-r4}
  12306. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12307. output of \code{explicate\_control}. (The concrete syntax is given in
  12308. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  12309. functions for assignment and tail contexts should be updated with
  12310. cases for \code{Apply} and \code{FunRef} and the function for
  12311. predicate context should be updated for \code{Apply} but not
  12312. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  12313. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  12314. tail position \code{Apply} becomes \code{TailCall}. We recommend
  12315. defining a new auxiliary function for processing function definitions.
  12316. This code is similar to the case for \code{Program} in \LangVec{}. The
  12317. top-level \code{explicate\_control} function that handles the
  12318. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  12319. all the function definitions.
  12320. \begin{figure}[tp]
  12321. \fbox{
  12322. \begin{minipage}{0.96\textwidth}
  12323. \small
  12324. \[
  12325. \begin{array}{lcl}
  12326. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  12327. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  12328. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  12329. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  12330. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  12331. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  12332. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  12333. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  12334. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  12335. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12336. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  12337. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  12338. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  12339. \MID \GOTO{\itm{label}} } \\
  12340. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  12341. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  12342. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  12343. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12344. \end{array}
  12345. \]
  12346. \end{minipage}
  12347. }
  12348. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12349. \label{fig:c3-syntax}
  12350. \end{figure}
  12351. \section{Select Instructions and the \LangXIndCall{} Language}
  12352. \label{sec:select-r4}
  12353. \index{subject}{instruction selection}
  12354. The output of select instructions is a program in the \LangXIndCall{}
  12355. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12356. \index{subject}{x86}
  12357. \begin{figure}[tp]
  12358. \fbox{
  12359. \begin{minipage}{0.96\textwidth}
  12360. \small
  12361. \[
  12362. \begin{array}{lcl}
  12363. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  12364. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  12365. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12366. \Instr &::=& \ldots
  12367. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12368. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12369. \Block &::= & \Instr\ldots \\
  12370. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  12371. \LangXIndCallM{} &::= & \Def\ldots
  12372. \end{array}
  12373. \]
  12374. \end{minipage}
  12375. }
  12376. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12377. \label{fig:x86-3-concrete}
  12378. \end{figure}
  12379. \begin{figure}[tp]
  12380. \fbox{
  12381. \begin{minipage}{0.96\textwidth}
  12382. \small
  12383. \[
  12384. \begin{array}{lcl}
  12385. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12386. \MID \BYTEREG{\Reg} } \\
  12387. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  12388. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12389. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12390. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  12391. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  12392. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  12393. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12394. \end{array}
  12395. \]
  12396. \end{minipage}
  12397. }
  12398. \caption{The abstract syntax of \LangXIndCall{} (extends
  12399. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  12400. \label{fig:x86-3}
  12401. \end{figure}
  12402. An assignment of a function reference to a variable becomes a
  12403. load-effective-address instruction as follows, where $\itm{lhs}'$
  12404. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  12405. to \Arg{} in \LangXIndCallVar{}. \\
  12406. \begin{tabular}{lcl}
  12407. \begin{minipage}{0.35\textwidth}
  12408. \begin{lstlisting}
  12409. |$\itm{lhs}$| = (fun-ref |$f$|);
  12410. \end{lstlisting}
  12411. \end{minipage}
  12412. &
  12413. $\Rightarrow$\qquad\qquad
  12414. &
  12415. \begin{minipage}{0.3\textwidth}
  12416. \begin{lstlisting}
  12417. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  12418. \end{lstlisting}
  12419. \end{minipage}
  12420. \end{tabular} \\
  12421. Regarding function definitions, we need to remove the parameters and
  12422. instead perform parameter passing using the conventions discussed in
  12423. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  12424. registers. We recommend turning the parameters into local variables
  12425. and generating instructions at the beginning of the function to move
  12426. from the argument passing registers to these local variables.
  12427. \begin{lstlisting}
  12428. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  12429. |$\Rightarrow$|
  12430. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  12431. \end{lstlisting}
  12432. The $G'$ control-flow graph is the same as $G$ except that the
  12433. \code{start} block is modified to add the instructions for moving from
  12434. the argument registers to the parameter variables. So the \code{start}
  12435. block of $G$ shown on the left is changed to the code on the right.
  12436. \begin{center}
  12437. \begin{minipage}{0.3\textwidth}
  12438. \begin{lstlisting}
  12439. start:
  12440. |$\itm{instr}_1$|
  12441. |$\vdots$|
  12442. |$\itm{instr}_n$|
  12443. \end{lstlisting}
  12444. \end{minipage}
  12445. $\Rightarrow$
  12446. \begin{minipage}{0.3\textwidth}
  12447. \begin{lstlisting}
  12448. start:
  12449. movq %rdi, |$x_1$|
  12450. movq %rsi, |$x_2$|
  12451. |$\vdots$|
  12452. |$\itm{instr}_1$|
  12453. |$\vdots$|
  12454. |$\itm{instr}_n$|
  12455. \end{lstlisting}
  12456. \end{minipage}
  12457. \end{center}
  12458. By changing the parameters to local variables, we are giving the
  12459. register allocator control over which registers or stack locations to
  12460. use for them. If you implemented the move-biasing challenge
  12461. (Section~\ref{sec:move-biasing}), the register allocator will try to
  12462. assign the parameter variables to the corresponding argument register,
  12463. in which case the \code{patch\_instructions} pass will remove the
  12464. \code{movq} instruction. This happens in the example translation in
  12465. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  12466. the \code{add} function.
  12467. %
  12468. Also, note that the register allocator will perform liveness analysis
  12469. on this sequence of move instructions and build the interference
  12470. graph. So, for example, $x_1$ will be marked as interfering with
  12471. \code{rsi} and that will prevent the assignment of $x_1$ to
  12472. \code{rsi}, which is good, because that would overwrite the argument
  12473. that needs to move into $x_2$.
  12474. Next, consider the compilation of function calls. In the mirror image
  12475. of handling the parameters of function definitions, the arguments need
  12476. to be moved to the argument passing registers. The function call
  12477. itself is performed with an indirect function call. The return value
  12478. from the function is stored in \code{rax}, so it needs to be moved
  12479. into the \itm{lhs}.
  12480. \begin{lstlisting}
  12481. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  12482. |$\Rightarrow$|
  12483. movq |$\itm{arg}_1$|, %rdi
  12484. movq |$\itm{arg}_2$|, %rsi
  12485. |$\vdots$|
  12486. callq *|\itm{fun}|
  12487. movq %rax, |\itm{lhs}|
  12488. \end{lstlisting}
  12489. The \code{IndirectCallq} AST node includes an integer for the arity of
  12490. the function, i.e., the number of parameters. That information is
  12491. useful in the \code{uncover-live} pass for determining which
  12492. argument-passing registers are potentially read during the call.
  12493. For tail calls, the parameter passing is the same as non-tail calls:
  12494. generate instructions to move the arguments into to the argument
  12495. passing registers. After that we need to pop the frame from the
  12496. procedure call stack. However, we do not yet know how big the frame
  12497. is; that gets determined during register allocation. So instead of
  12498. generating those instructions here, we invent a new instruction that
  12499. means ``pop the frame and then do an indirect jump'', which we name
  12500. \code{TailJmp}. The abstract syntax for this instruction includes an
  12501. argument that specifies where to jump and an integer that represents
  12502. the arity of the function being called.
  12503. Recall that in Section~\ref{sec:explicate-control-Lvar} we recommended
  12504. using the label \code{start} for the initial block of a program, and
  12505. in Section~\ref{sec:select-Lvar} we recommended labeling the conclusion
  12506. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  12507. can be compiled to an assignment to \code{rax} followed by a jump to
  12508. \code{conclusion}. With the addition of function definitions, we will
  12509. have a starting block and conclusion for each function, but their
  12510. labels need to be unique. We recommend prepending the function's name
  12511. to \code{start} and \code{conclusion}, respectively, to obtain unique
  12512. labels. (Alternatively, one could \code{gensym} labels for the start
  12513. and conclusion and store them in the $\itm{info}$ field of the
  12514. function definition.)
  12515. \section{Register Allocation}
  12516. \label{sec:register-allocation-r4}
  12517. \subsection{Liveness Analysis}
  12518. \label{sec:liveness-analysis-r4}
  12519. \index{subject}{liveness analysis}
  12520. %% The rest of the passes need only minor modifications to handle the new
  12521. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  12522. %% \code{leaq}.
  12523. The \code{IndirectCallq} instruction should be treated like
  12524. \code{Callq} regarding its written locations $W$, in that they should
  12525. include all the caller-saved registers. Recall that the reason for
  12526. that is to force call-live variables to be assigned to callee-saved
  12527. registers or to be spilled to the stack.
  12528. Regarding the set of read locations $R$ the arity field of
  12529. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  12530. argument-passing registers should be considered as read by those
  12531. instructions.
  12532. \subsection{Build Interference Graph}
  12533. \label{sec:build-interference-r4}
  12534. With the addition of function definitions, we compute an interference
  12535. graph for each function (not just one for the whole program).
  12536. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  12537. spill vector-typed variables that are live during a call to the
  12538. \code{collect}. With the addition of functions to our language, we
  12539. need to revisit this issue. Many functions perform allocation and
  12540. therefore have calls to the collector inside of them. Thus, we should
  12541. not only spill a vector-typed variable when it is live during a call
  12542. to \code{collect}, but we should spill the variable if it is live
  12543. during any function call. Thus, in the \code{build\_interference} pass,
  12544. we recommend adding interference edges between call-live vector-typed
  12545. variables and the callee-saved registers (in addition to the usual
  12546. addition of edges between call-live variables and the caller-saved
  12547. registers).
  12548. \subsection{Allocate Registers}
  12549. The primary change to the \code{allocate\_registers} pass is adding an
  12550. auxiliary function for handling definitions (the \Def{} non-terminal
  12551. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  12552. logic is the same as described in
  12553. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  12554. allocation is performed many times, once for each function definition,
  12555. instead of just once for the whole program.
  12556. \section{Patch Instructions}
  12557. In \code{patch\_instructions}, you should deal with the x86
  12558. idiosyncrasy that the destination argument of \code{leaq} must be a
  12559. register. Additionally, you should ensure that the argument of
  12560. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  12561. code generation more convenient, because we trample many registers
  12562. before the tail call (as explained in the next section).
  12563. \section{Print x86}
  12564. For the \code{print\_x86} pass, the cases for \code{FunRef} and
  12565. \code{IndirectCallq} are straightforward: output their concrete
  12566. syntax.
  12567. \begin{lstlisting}
  12568. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  12569. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  12570. \end{lstlisting}
  12571. The \code{TailJmp} node requires a bit work. A straightforward
  12572. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  12573. before the jump we need to pop the current frame. This sequence of
  12574. instructions is the same as the code for the conclusion of a function,
  12575. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  12576. Regarding function definitions, you will need to generate a prelude
  12577. and conclusion for each one. This code is similar to the prelude and
  12578. conclusion that you generated for the \code{main} function in
  12579. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  12580. should carry out the following steps.
  12581. \begin{enumerate}
  12582. \item Start with \code{.global} and \code{.align} directives followed
  12583. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  12584. example.)
  12585. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  12586. pointer.
  12587. \item Push to the stack all of the callee-saved registers that were
  12588. used for register allocation.
  12589. \item Move the stack pointer \code{rsp} down by the size of the stack
  12590. frame for this function, which depends on the number of regular
  12591. spills. (Aligned to 16 bytes.)
  12592. \item Move the root stack pointer \code{r15} up by the size of the
  12593. root-stack frame for this function, which depends on the number of
  12594. spilled vectors. \label{root-stack-init}
  12595. \item Initialize to zero all of the entries in the root-stack frame.
  12596. \item Jump to the start block.
  12597. \end{enumerate}
  12598. The prelude of the \code{main} function has one additional task: call
  12599. the \code{initialize} function to set up the garbage collector and
  12600. move the value of the global \code{rootstack\_begin} in
  12601. \code{r15}. This should happen before step \ref{root-stack-init}
  12602. above, which depends on \code{r15}.
  12603. The conclusion of every function should do the following.
  12604. \begin{enumerate}
  12605. \item Move the stack pointer back up by the size of the stack frame
  12606. for this function.
  12607. \item Restore the callee-saved registers by popping them from the
  12608. stack.
  12609. \item Move the root stack pointer back down by the size of the
  12610. root-stack frame for this function.
  12611. \item Restore \code{rbp} by popping it from the stack.
  12612. \item Return to the caller with the \code{retq} instruction.
  12613. \end{enumerate}
  12614. \begin{exercise}\normalfont
  12615. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  12616. Create 5 new programs that use functions, including examples that pass
  12617. functions and return functions from other functions, recursive
  12618. functions, functions that create vectors, and functions that make tail
  12619. calls. Test your compiler on these new programs and all of your
  12620. previously created test programs.
  12621. \end{exercise}
  12622. \begin{figure}[tbp]
  12623. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12624. \node (Rfun) at (0,2) {\large \LangFun{}};
  12625. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  12626. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  12627. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  12628. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  12629. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  12630. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  12631. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  12632. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12633. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12634. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12635. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12636. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12637. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12638. \path[->,bend left=15] (Rfun) edge [above] node
  12639. {\ttfamily\footnotesize shrink} (Rfun-1);
  12640. \path[->,bend left=15] (Rfun-1) edge [above] node
  12641. {\ttfamily\footnotesize uniquify} (Rfun-2);
  12642. \path[->,bend left=15] (Rfun-2) edge [right] node
  12643. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  12644. \path[->,bend left=15] (F1-1) edge [below] node
  12645. {\ttfamily\footnotesize limit\_functions} (F1-2);
  12646. \path[->,bend right=15] (F1-2) edge [above] node
  12647. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  12648. \path[->,bend right=15] (F1-3) edge [above] node
  12649. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  12650. \path[->,bend left=15] (F1-4) edge [right] node
  12651. {\ttfamily\footnotesize explicate\_control} (C3-2);
  12652. \path[->,bend right=15] (C3-2) edge [left] node
  12653. {\ttfamily\footnotesize select\_instr.} (x86-2);
  12654. \path[->,bend left=15] (x86-2) edge [left] node
  12655. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12656. \path[->,bend right=15] (x86-2-1) edge [below] node
  12657. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  12658. \path[->,bend right=15] (x86-2-2) edge [left] node
  12659. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  12660. \path[->,bend left=15] (x86-3) edge [above] node
  12661. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  12662. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  12663. \end{tikzpicture}
  12664. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  12665. \label{fig:Rfun-passes}
  12666. \end{figure}
  12667. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  12668. compiling \LangFun{} to x86.
  12669. \section{An Example Translation}
  12670. \label{sec:functions-example}
  12671. Figure~\ref{fig:add-fun} shows an example translation of a simple
  12672. function in \LangFun{} to x86. The figure also includes the results of the
  12673. \code{explicate\_control} and \code{select\_instructions} passes.
  12674. \begin{figure}[htbp]
  12675. \begin{tabular}{ll}
  12676. \begin{minipage}{0.5\textwidth}
  12677. % s3_2.rkt
  12678. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12679. (define (add [x : Integer] [y : Integer])
  12680. : Integer
  12681. (+ x y))
  12682. (add 40 2)
  12683. \end{lstlisting}
  12684. $\Downarrow$
  12685. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12686. (define (add86 [x87 : Integer]
  12687. [y88 : Integer]) : Integer
  12688. add86start:
  12689. return (+ x87 y88);
  12690. )
  12691. (define (main) : Integer ()
  12692. mainstart:
  12693. tmp89 = (fun-ref add86);
  12694. (tail-call tmp89 40 2)
  12695. )
  12696. \end{lstlisting}
  12697. \end{minipage}
  12698. &
  12699. $\Rightarrow$
  12700. \begin{minipage}{0.5\textwidth}
  12701. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12702. (define (add86) : Integer
  12703. add86start:
  12704. movq %rdi, x87
  12705. movq %rsi, y88
  12706. movq x87, %rax
  12707. addq y88, %rax
  12708. jmp add11389conclusion
  12709. )
  12710. (define (main) : Integer
  12711. mainstart:
  12712. leaq (fun-ref add86), tmp89
  12713. movq $40, %rdi
  12714. movq $2, %rsi
  12715. tail-jmp tmp89
  12716. )
  12717. \end{lstlisting}
  12718. $\Downarrow$
  12719. \end{minipage}
  12720. \end{tabular}
  12721. \begin{tabular}{ll}
  12722. \begin{minipage}{0.3\textwidth}
  12723. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12724. .globl add86
  12725. .align 16
  12726. add86:
  12727. pushq %rbp
  12728. movq %rsp, %rbp
  12729. jmp add86start
  12730. add86start:
  12731. movq %rdi, %rax
  12732. addq %rsi, %rax
  12733. jmp add86conclusion
  12734. add86conclusion:
  12735. popq %rbp
  12736. retq
  12737. \end{lstlisting}
  12738. \end{minipage}
  12739. &
  12740. \begin{minipage}{0.5\textwidth}
  12741. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12742. .globl main
  12743. .align 16
  12744. main:
  12745. pushq %rbp
  12746. movq %rsp, %rbp
  12747. movq $16384, %rdi
  12748. movq $16384, %rsi
  12749. callq initialize
  12750. movq rootstack_begin(%rip), %r15
  12751. jmp mainstart
  12752. mainstart:
  12753. leaq add86(%rip), %rcx
  12754. movq $40, %rdi
  12755. movq $2, %rsi
  12756. movq %rcx, %rax
  12757. popq %rbp
  12758. jmp *%rax
  12759. mainconclusion:
  12760. popq %rbp
  12761. retq
  12762. \end{lstlisting}
  12763. \end{minipage}
  12764. \end{tabular}
  12765. \caption{Example compilation of a simple function to x86.}
  12766. \label{fig:add-fun}
  12767. \end{figure}
  12768. % Challenge idea: inlining! (simple version)
  12769. % Further Reading
  12770. \fi % racketEd
  12771. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12772. \chapter{Lexically Scoped Functions}
  12773. \label{ch:Rlam}
  12774. \index{subject}{lambda}
  12775. \index{subject}{lexical scoping}
  12776. \if\edition\racketEd
  12777. This chapter studies lexically scoped functions as they appear in
  12778. functional languages such as Racket. By lexical scoping we mean that a
  12779. function's body may refer to variables whose binding site is outside
  12780. of the function, in an enclosing scope.
  12781. %
  12782. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  12783. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  12784. \key{lambda} form. The body of the \key{lambda}, refers to three
  12785. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  12786. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  12787. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  12788. parameter of function \code{f}. The \key{lambda} is returned from the
  12789. function \code{f}. The main expression of the program includes two
  12790. calls to \code{f} with different arguments for \code{x}, first
  12791. \code{5} then \code{3}. The functions returned from \code{f} are bound
  12792. to variables \code{g} and \code{h}. Even though these two functions
  12793. were created by the same \code{lambda}, they are really different
  12794. functions because they use different values for \code{x}. Applying
  12795. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  12796. \code{15} produces \code{22}. The result of this program is \code{42}.
  12797. \begin{figure}[btp]
  12798. % s4_6.rkt
  12799. \begin{lstlisting}
  12800. (define (f [x : Integer]) : (Integer -> Integer)
  12801. (let ([y 4])
  12802. (lambda: ([z : Integer]) : Integer
  12803. (+ x (+ y z)))))
  12804. (let ([g (f 5)])
  12805. (let ([h (f 3)])
  12806. (+ (g 11) (h 15))))
  12807. \end{lstlisting}
  12808. \caption{Example of a lexically scoped function.}
  12809. \label{fig:lexical-scoping}
  12810. \end{figure}
  12811. The approach that we take for implementing lexically scoped
  12812. functions is to compile them into top-level function definitions,
  12813. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  12814. provide special treatment for variable occurrences such as \code{x}
  12815. and \code{y} in the body of the \code{lambda} of
  12816. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  12817. refer to variables defined outside of it. To identify such variable
  12818. occurrences, we review the standard notion of free variable.
  12819. \begin{definition}
  12820. A variable is \emph{free in expression} $e$ if the variable occurs
  12821. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  12822. variable}
  12823. \end{definition}
  12824. For example, in the expression \code{(+ x (+ y z))} the variables
  12825. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  12826. only \code{x} and \code{y} are free in the following expression
  12827. because \code{z} is bound by the \code{lambda}.
  12828. \begin{lstlisting}
  12829. (lambda: ([z : Integer]) : Integer
  12830. (+ x (+ y z)))
  12831. \end{lstlisting}
  12832. So the free variables of a \code{lambda} are the ones that will need
  12833. special treatment. We need to arrange for some way to transport, at
  12834. runtime, the values of those variables from the point where the
  12835. \code{lambda} was created to the point where the \code{lambda} is
  12836. applied. An efficient solution to the problem, due to
  12837. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  12838. free variables together with the function pointer for the lambda's
  12839. code, an arrangement called a \emph{flat closure} (which we shorten to
  12840. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  12841. we have all the ingredients to make closures, Chapter~\ref{ch:Lvec}
  12842. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  12843. pointers. The function pointer resides at index $0$ and the
  12844. values for the free variables will fill in the rest of the vector.
  12845. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  12846. how closures work. It's a three-step dance. The program first calls
  12847. function \code{f}, which creates a closure for the \code{lambda}. The
  12848. closure is a vector whose first element is a pointer to the top-level
  12849. function that we will generate for the \code{lambda}, the second
  12850. element is the value of \code{x}, which is \code{5}, and the third
  12851. element is \code{4}, the value of \code{y}. The closure does not
  12852. contain an element for \code{z} because \code{z} is not a free
  12853. variable of the \code{lambda}. Creating the closure is step 1 of the
  12854. dance. The closure is returned from \code{f} and bound to \code{g}, as
  12855. shown in Figure~\ref{fig:closures}.
  12856. %
  12857. The second call to \code{f} creates another closure, this time with
  12858. \code{3} in the second slot (for \code{x}). This closure is also
  12859. returned from \code{f} but bound to \code{h}, which is also shown in
  12860. Figure~\ref{fig:closures}.
  12861. \begin{figure}[tbp]
  12862. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  12863. \caption{Example closure representation for the \key{lambda}'s
  12864. in Figure~\ref{fig:lexical-scoping}.}
  12865. \label{fig:closures}
  12866. \end{figure}
  12867. Continuing with the example, consider the application of \code{g} to
  12868. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  12869. obtain the function pointer in the first element of the closure and
  12870. call it, passing in the closure itself and then the regular arguments,
  12871. in this case \code{11}. This technique for applying a closure is step
  12872. 2 of the dance.
  12873. %
  12874. But doesn't this \code{lambda} only take 1 argument, for parameter
  12875. \code{z}? The third and final step of the dance is generating a
  12876. top-level function for a \code{lambda}. We add an additional
  12877. parameter for the closure and we insert a \code{let} at the beginning
  12878. of the function for each free variable, to bind those variables to the
  12879. appropriate elements from the closure parameter.
  12880. %
  12881. This three-step dance is known as \emph{closure conversion}. We
  12882. discuss the details of closure conversion in
  12883. Section~\ref{sec:closure-conversion} and the code generated from the
  12884. example in Section~\ref{sec:example-lambda}. But first we define the
  12885. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  12886. \section{The \LangLam{} Language}
  12887. \label{sec:r5}
  12888. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  12889. functions and lexical scoping, is defined in
  12890. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  12891. the \key{lambda} form to the grammar for \LangFun{}, which already has
  12892. syntax for function application.
  12893. \newcommand{\LlambdaGrammarRacket}{
  12894. \begin{array}{lcl}
  12895. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  12896. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  12897. \end{array}
  12898. }
  12899. \newcommand{\LlambdaAST}{
  12900. \begin{array}{lcl}
  12901. \itm{op} &::=& \code{procedure-arity} \\
  12902. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  12903. \end{array}
  12904. }
  12905. \begin{figure}[tp]
  12906. \centering
  12907. \fbox{
  12908. \begin{minipage}{0.96\textwidth}
  12909. \small
  12910. \[
  12911. \begin{array}{l}
  12912. \gray{\LintGrammarRacket{}} \\ \hline
  12913. \gray{\LvarGrammarRacket{}} \\ \hline
  12914. \gray{\LifGrammarRacket{}} \\ \hline
  12915. \gray{\LwhileGrammarRacket} \\ \hline
  12916. \gray{\LtupGrammarRacket} \\ \hline
  12917. \gray{\LfunGrammarRacket} \\ \hline
  12918. \LlambdaGrammarRacket \\
  12919. \begin{array}{lcl}
  12920. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  12921. %% \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  12922. %% \MID (\Type\ldots \; \key{->}\; \Type)} \\
  12923. %% \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12924. %% \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  12925. %% &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  12926. %% &\MID& \gray{\key{\#t} \MID \key{\#f}
  12927. %% \MID (\key{and}\;\Exp\;\Exp)
  12928. %% \MID (\key{or}\;\Exp\;\Exp)
  12929. %% \MID (\key{not}\;\Exp) } \\
  12930. %% &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  12931. %% &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  12932. %% (\key{vector-ref}\;\Exp\;\Int)} \\
  12933. %% &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  12934. %% \MID (\Exp \; \Exp\ldots) } \\
  12935. %% &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  12936. %% &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  12937. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12938. \LangLamM{} &::=& \Def\ldots \; \Exp
  12939. \end{array}
  12940. \end{array}
  12941. \]
  12942. \end{minipage}
  12943. }
  12944. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  12945. with \key{lambda}.}
  12946. \label{fig:Rlam-concrete-syntax}
  12947. \end{figure}
  12948. \begin{figure}[tp]
  12949. \centering
  12950. \fbox{
  12951. \begin{minipage}{0.96\textwidth}
  12952. \small
  12953. \[
  12954. \begin{array}{l}
  12955. \gray{\LintOpAST} \\ \hline
  12956. \gray{\LvarAST{}} \\ \hline
  12957. \gray{\LifAST{}} \\ \hline
  12958. \gray{\LwhileAST{}} \\ \hline
  12959. \gray{\LtupAST{}} \\ \hline
  12960. \gray{\LfunAST} \\ \hline
  12961. \LlambdaAST \\
  12962. \begin{array}{lcl}
  12963. %% \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  12964. %% \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  12965. %% &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  12966. %% &\MID& \gray{ \BOOL{\itm{bool}}
  12967. %% \MID \IF{\Exp}{\Exp}{\Exp} } \\
  12968. %% &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  12969. %% \MID \APPLY{\Exp}{\Exp\ldots} }\\
  12970. %% &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  12971. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  12972. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12973. \end{array}
  12974. \end{array}
  12975. \]
  12976. \end{minipage}
  12977. }
  12978. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  12979. \label{fig:Rlam-syntax}
  12980. \end{figure}
  12981. \index{subject}{interpreter}
  12982. \label{sec:interp-Rlambda}
  12983. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  12984. \LangLam{}. The case for \key{lambda} saves the current environment
  12985. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  12986. the environment from the \key{lambda}, the \code{lam-env}, when
  12987. interpreting the body of the \key{lambda}. The \code{lam-env}
  12988. environment is extended with the mapping of parameters to argument
  12989. values.
  12990. \begin{figure}[tbp]
  12991. \begin{lstlisting}
  12992. (define interp-Rlambda_class
  12993. (class interp-Rfun_class
  12994. (super-new)
  12995. (define/override (interp-op op)
  12996. (match op
  12997. ['procedure-arity
  12998. (lambda (v)
  12999. (match v
  13000. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13001. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13002. [else (super interp-op op)]))
  13003. (define/override ((interp-exp env) e)
  13004. (define recur (interp-exp env))
  13005. (match e
  13006. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13007. `(function ,xs ,body ,env)]
  13008. [else ((super interp-exp env) e)]))
  13009. ))
  13010. (define (interp-Rlambda p)
  13011. (send (new interp-Rlambda_class) interp-program p))
  13012. \end{lstlisting}
  13013. \caption{Interpreter for \LangLam{}.}
  13014. \label{fig:interp-Rlambda}
  13015. \end{figure}
  13016. \label{sec:type-check-r5}
  13017. \index{subject}{type checking}
  13018. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  13019. \key{lambda} form. The body of the \key{lambda} is checked in an
  13020. environment that includes the current environment (because it is
  13021. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13022. require the body's type to match the declared return type.
  13023. \begin{figure}[tbp]
  13024. \begin{lstlisting}
  13025. (define (type-check-Rlambda env)
  13026. (lambda (e)
  13027. (match e
  13028. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13029. (define-values (new-body bodyT)
  13030. ((type-check-exp (append (map cons xs Ts) env)) body))
  13031. (define ty `(,@Ts -> ,rT))
  13032. (cond
  13033. [(equal? rT bodyT)
  13034. (values (HasType (Lambda params rT new-body) ty) ty)]
  13035. [else
  13036. (error "mismatch in return type" bodyT rT)])]
  13037. ...
  13038. )))
  13039. \end{lstlisting}
  13040. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  13041. \label{fig:type-check-Rlambda}
  13042. \end{figure}
  13043. \section{Assignment and Lexically Scoped Functions}
  13044. \label{sec:assignment-scoping}
  13045. [UNDER CONSTRUCTION: This section was just moved into this location
  13046. and may need to be updated. -Jeremy]
  13047. The combination of lexically-scoped functions and assignment
  13048. (i.e. \code{set!}) raises a challenge with our approach to
  13049. implementing lexically-scoped functions. Consider the following
  13050. example in which function \code{f} has a free variable \code{x} that
  13051. is changed after \code{f} is created but before the call to \code{f}.
  13052. % loop_test_11.rkt
  13053. \begin{lstlisting}
  13054. (let ([x 0])
  13055. (let ([y 0])
  13056. (let ([z 20])
  13057. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13058. (begin
  13059. (set! x 10)
  13060. (set! y 12)
  13061. (f y))))))
  13062. \end{lstlisting}
  13063. The correct output for this example is \code{42} because the call to
  13064. \code{f} is required to use the current value of \code{x} (which is
  13065. \code{10}). Unfortunately, the closure conversion pass
  13066. (Section~\ref{sec:closure-conversion}) generates code for the
  13067. \code{lambda} that copies the old value of \code{x} into a
  13068. closure. Thus, if we naively add support for assignment to our current
  13069. compiler, the output of this program would be \code{32}.
  13070. A first attempt at solving this problem would be to save a pointer to
  13071. \code{x} in the closure and change the occurrences of \code{x} inside
  13072. the lambda to dereference the pointer. Of course, this would require
  13073. assigning \code{x} to the stack and not to a register. However, the
  13074. problem goes a bit deeper. Consider the following example in which we
  13075. create a counter abstraction by creating a pair of functions that
  13076. share the free variable \code{x}.
  13077. % similar to loop_test_10.rkt
  13078. \begin{lstlisting}
  13079. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  13080. (vector
  13081. (lambda: () : Integer x)
  13082. (lambda: () : Void (set! x (+ 1 x)))))
  13083. (let ([counter (f 0)])
  13084. (let ([get (vector-ref counter 0)])
  13085. (let ([inc (vector-ref counter 1)])
  13086. (begin
  13087. (inc)
  13088. (get)))))
  13089. \end{lstlisting}
  13090. In this example, the lifetime of \code{x} extends beyond the lifetime
  13091. of the call to \code{f}. Thus, if we were to store \code{x} on the
  13092. stack frame for the call to \code{f}, it would be gone by the time we
  13093. call \code{inc} and \code{get}, leaving us with dangling pointers for
  13094. \code{x}. This example demonstrates that when a variable occurs free
  13095. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  13096. value of the variable needs to live on the heap. The verb ``box'' is
  13097. often used for allocating a single value on the heap, producing a
  13098. pointer, and ``unbox'' for dereferencing the pointer.
  13099. We recommend solving these problems by ``boxing'' the local variables
  13100. that are in the intersection of 1) variables that appear on the
  13101. left-hand-side of a \code{set!} and 2) variables that occur free
  13102. inside a \code{lambda}. We shall introduce a new pass named
  13103. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  13104. perform this translation. But before diving into the compiler passes,
  13105. we one more problem to discuss.
  13106. \section{Reveal Functions and the $F_2$ language}
  13107. \label{sec:reveal-functions-r5}
  13108. To support the \code{procedure-arity} operator we need to communicate
  13109. the arity of a function to the point of closure creation. We can
  13110. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  13111. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  13112. output of this pass is the language $F_2$, whose syntax is defined in
  13113. Figure~\ref{fig:f2-syntax}.
  13114. \begin{figure}[tp]
  13115. \centering
  13116. \fbox{
  13117. \begin{minipage}{0.96\textwidth}
  13118. \[
  13119. \begin{array}{lcl}
  13120. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  13121. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13122. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  13123. \end{array}
  13124. \]
  13125. \end{minipage}
  13126. }
  13127. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  13128. (Figure~\ref{fig:Rlam-syntax}).}
  13129. \label{fig:f2-syntax}
  13130. \end{figure}
  13131. \section{Convert Assignments}
  13132. \label{sec:convert-assignments}
  13133. [UNDER CONSTRUCTION: This section was just moved into this location
  13134. and may need to be updated. -Jeremy]
  13135. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  13136. the combination of assignments and lexically-scoped functions requires
  13137. that we box those variables that are both assigned-to and that appear
  13138. free inside a \code{lambda}. The purpose of the
  13139. \code{convert-assignments} pass is to carry out that transformation.
  13140. We recommend placing this pass after \code{uniquify} but before
  13141. \code{reveal\_functions}.
  13142. Consider again the first example from
  13143. Section~\ref{sec:assignment-scoping}:
  13144. \begin{lstlisting}
  13145. (let ([x 0])
  13146. (let ([y 0])
  13147. (let ([z 20])
  13148. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13149. (begin
  13150. (set! x 10)
  13151. (set! y 12)
  13152. (f y))))))
  13153. \end{lstlisting}
  13154. The variables \code{x} and \code{y} are assigned-to. The variables
  13155. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  13156. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  13157. The boxing of \code{x} consists of three transformations: initialize
  13158. \code{x} with a vector, replace reads from \code{x} with
  13159. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  13160. \code{vector-set!}. The output of \code{convert-assignments} for this
  13161. example is as follows.
  13162. \begin{lstlisting}
  13163. (define (main) : Integer
  13164. (let ([x0 (vector 0)])
  13165. (let ([y1 0])
  13166. (let ([z2 20])
  13167. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  13168. (+ a3 (+ (vector-ref x0 0) z2)))])
  13169. (begin
  13170. (vector-set! x0 0 10)
  13171. (set! y1 12)
  13172. (f4 y1)))))))
  13173. \end{lstlisting}
  13174. \paragraph{Assigned \& Free}
  13175. We recommend defining an auxiliary function named
  13176. \code{assigned\&free} that takes an expression and simultaneously
  13177. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  13178. that occur free within lambda's, and 3) a new version of the
  13179. expression that records which bound variables occurred in the
  13180. intersection of $A$ and $F$. You can use the struct
  13181. \code{AssignedFree} to do this. Consider the case for
  13182. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  13183. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  13184. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  13185. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  13186. \begin{lstlisting}
  13187. (Let |$x$| |$rhs$| |$body$|)
  13188. |$\Rightarrow$|
  13189. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  13190. \end{lstlisting}
  13191. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  13192. The set of assigned variables for this \code{Let} is
  13193. $A_r \cup (A_b - \{x\})$
  13194. and the set of variables free in lambda's is
  13195. $F_r \cup (F_b - \{x\})$.
  13196. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  13197. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  13198. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  13199. and $F_r$.
  13200. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  13201. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  13202. recursively processing \itm{body}. Wrap each of parameter that occurs
  13203. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  13204. Let $P$ be the set of parameter names in \itm{params}. The result is
  13205. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  13206. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  13207. variables of an expression (see Chapter~\ref{ch:Rlam}).
  13208. \paragraph{Convert Assignments}
  13209. Next we discuss the \code{convert-assignment} pass with its auxiliary
  13210. functions for expressions and definitions. The function for
  13211. expressions, \code{cnvt-assign-exp}, should take an expression and a
  13212. set of assigned-and-free variables (obtained from the result of
  13213. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  13214. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  13215. \code{vector-ref}.
  13216. \begin{lstlisting}
  13217. (Var |$x$|)
  13218. |$\Rightarrow$|
  13219. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  13220. \end{lstlisting}
  13221. %
  13222. In the case for $\LET{\LP\code{AssignedFree}\,
  13223. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  13224. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  13225. \itm{body'} but with $x$ added to the set of assigned-and-free
  13226. variables. Translate the let-expression as follows to bind $x$ to a
  13227. boxed value.
  13228. \begin{lstlisting}
  13229. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  13230. |$\Rightarrow$|
  13231. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  13232. \end{lstlisting}
  13233. %
  13234. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  13235. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  13236. variables, translate the \code{set!} into a \code{vector-set!}
  13237. as follows.
  13238. \begin{lstlisting}
  13239. (SetBang |$x$| |$\itm{rhs}$|)
  13240. |$\Rightarrow$|
  13241. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  13242. \end{lstlisting}
  13243. %
  13244. The case for \code{Lambda} is non-trivial, but it is similar to the
  13245. case for function definitions, which we discuss next.
  13246. The auxiliary function for definitions, \code{cnvt-assign-def},
  13247. applies assignment conversion to function definitions.
  13248. We translate a function definition as follows.
  13249. \begin{lstlisting}
  13250. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  13251. |$\Rightarrow$|
  13252. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  13253. \end{lstlisting}
  13254. So it remains to explain \itm{params'} and $\itm{body}_4$.
  13255. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  13256. \code{assigned\&free} on $\itm{body_1}$.
  13257. Let $P$ be the parameter names in \itm{params}.
  13258. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  13259. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  13260. as the set of assigned-and-free variables.
  13261. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  13262. in a sequence of let-expressions that box the parameters
  13263. that are in $A_b \cap F_b$.
  13264. %
  13265. Regarding \itm{params'}, change the names of the parameters that are
  13266. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  13267. variables can retain the original names). Recall the second example in
  13268. Section~\ref{sec:assignment-scoping} involving a counter
  13269. abstraction. The following is the output of assignment version for
  13270. function \code{f}.
  13271. \begin{lstlisting}
  13272. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  13273. (vector
  13274. (lambda: () : Integer x1)
  13275. (lambda: () : Void (set! x1 (+ 1 x1)))))
  13276. |$\Rightarrow$|
  13277. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  13278. (let ([x1 (vector param_x1)])
  13279. (vector (lambda: () : Integer (vector-ref x1 0))
  13280. (lambda: () : Void
  13281. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  13282. \end{lstlisting}
  13283. \section{Closure Conversion}
  13284. \label{sec:closure-conversion}
  13285. \index{subject}{closure conversion}
  13286. The compiling of lexically-scoped functions into top-level function
  13287. definitions is accomplished in the pass \code{convert-to-closures}
  13288. that comes after \code{reveal\_functions} and before
  13289. \code{limit-functions}.
  13290. As usual, we implement the pass as a recursive function over the
  13291. AST. All of the action is in the cases for \key{Lambda} and
  13292. \key{Apply}. We transform a \key{Lambda} expression into an expression
  13293. that creates a closure, that is, a vector whose first element is a
  13294. function pointer and the rest of the elements are the free variables
  13295. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  13296. using \code{vector} so that we can distinguish closures from vectors
  13297. in Section~\ref{sec:optimize-closures} and to record the arity. In
  13298. the generated code below, the \itm{name} is a unique symbol generated
  13299. to identify the function and the \itm{arity} is the number of
  13300. parameters (the length of \itm{ps}).
  13301. \begin{lstlisting}
  13302. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  13303. |$\Rightarrow$|
  13304. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  13305. \end{lstlisting}
  13306. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  13307. create a top-level function definition for each \key{Lambda}, as
  13308. shown below.\\
  13309. \begin{minipage}{0.8\textwidth}
  13310. \begin{lstlisting}
  13311. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  13312. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  13313. ...
  13314. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  13315. |\itm{body'}|)...))
  13316. \end{lstlisting}
  13317. \end{minipage}\\
  13318. The \code{clos} parameter refers to the closure. Translate the type
  13319. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  13320. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  13321. $\itm{fvts}$ are the types of the free variables in the lambda and the
  13322. underscore \code{\_} is a dummy type that we use because it is rather
  13323. difficult to give a type to the function in the closure's
  13324. type.\footnote{To give an accurate type to a closure, we would need to
  13325. add existential types to the type checker~\citep{Minamide:1996ys}.}
  13326. The dummy type is considered to be equal to any other type during type
  13327. checking. The sequence of \key{Let} forms bind the free variables to
  13328. their values obtained from the closure.
  13329. Closure conversion turns functions into vectors, so the type
  13330. annotations in the program must also be translated. We recommend
  13331. defining a auxiliary recursive function for this purpose. Function
  13332. types should be translated as follows.
  13333. \begin{lstlisting}
  13334. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  13335. |$\Rightarrow$|
  13336. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  13337. \end{lstlisting}
  13338. The above type says that the first thing in the vector is a function
  13339. pointer. The first parameter of the function pointer is a vector (a
  13340. closure) and the rest of the parameters are the ones from the original
  13341. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  13342. the closure omits the types of the free variables because 1) those
  13343. types are not available in this context and 2) we do not need them in
  13344. the code that is generated for function application.
  13345. We transform function application into code that retrieves the
  13346. function pointer from the closure and then calls the function, passing
  13347. in the closure as the first argument. We bind $e'$ to a temporary
  13348. variable to avoid code duplication.
  13349. \begin{lstlisting}
  13350. (Apply |$e$| |\itm{es}|)
  13351. |$\Rightarrow$|
  13352. (Let |\itm{tmp}| |$e'$|
  13353. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  13354. \end{lstlisting}
  13355. There is also the question of what to do with references top-level
  13356. function definitions. To maintain a uniform translation of function
  13357. application, we turn function references into closures.
  13358. \begin{tabular}{lll}
  13359. \begin{minipage}{0.3\textwidth}
  13360. \begin{lstlisting}
  13361. (FunRefArity |$f$| |$n$|)
  13362. \end{lstlisting}
  13363. \end{minipage}
  13364. &
  13365. $\Rightarrow$
  13366. &
  13367. \begin{minipage}{0.5\textwidth}
  13368. \begin{lstlisting}
  13369. (Closure |$n$| (FunRef |$f$|) '())
  13370. \end{lstlisting}
  13371. \end{minipage}
  13372. \end{tabular} \\
  13373. %
  13374. The top-level function definitions need to be updated as well to take
  13375. an extra closure parameter.
  13376. \section{An Example Translation}
  13377. \label{sec:example-lambda}
  13378. Figure~\ref{fig:lexical-functions-example} shows the result of
  13379. \code{reveal\_functions} and \code{convert-to-closures} for the example
  13380. program demonstrating lexical scoping that we discussed at the
  13381. beginning of this chapter.
  13382. \begin{figure}[tbp]
  13383. \begin{minipage}{0.8\textwidth}
  13384. % tests/lambda_test_6.rkt
  13385. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13386. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  13387. (let ([y8 4])
  13388. (lambda: ([z9 : Integer]) : Integer
  13389. (+ x7 (+ y8 z9)))))
  13390. (define (main) : Integer
  13391. (let ([g0 ((fun-ref-arity f6 1) 5)])
  13392. (let ([h1 ((fun-ref-arity f6 1) 3)])
  13393. (+ (g0 11) (h1 15)))))
  13394. \end{lstlisting}
  13395. $\Rightarrow$
  13396. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13397. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  13398. (let ([y8 4])
  13399. (closure 1 (list (fun-ref lambda2) x7 y8))))
  13400. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  13401. (let ([x7 (vector-ref fvs3 1)])
  13402. (let ([y8 (vector-ref fvs3 2)])
  13403. (+ x7 (+ y8 z9)))))
  13404. (define (main) : Integer
  13405. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  13406. ((vector-ref clos5 0) clos5 5))])
  13407. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  13408. ((vector-ref clos6 0) clos6 3))])
  13409. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  13410. \end{lstlisting}
  13411. \end{minipage}
  13412. \caption{Example of closure conversion.}
  13413. \label{fig:lexical-functions-example}
  13414. \end{figure}
  13415. \begin{exercise}\normalfont
  13416. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  13417. Create 5 new programs that use \key{lambda} functions and make use of
  13418. lexical scoping. Test your compiler on these new programs and all of
  13419. your previously created test programs.
  13420. \end{exercise}
  13421. \section{Expose Allocation}
  13422. \label{sec:expose-allocation-r5}
  13423. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  13424. that allocates and initializes a vector, similar to the translation of
  13425. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  13426. The only difference is replacing the use of
  13427. \ALLOC{\itm{len}}{\itm{type}} with
  13428. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  13429. \section{Explicate Control and \LangCLam{}}
  13430. \label{sec:explicate-r5}
  13431. The output language of \code{explicate\_control} is \LangCLam{} whose
  13432. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  13433. difference with respect to \LangCFun{} is the addition of the
  13434. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  13435. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  13436. similar to the handling of other expressions such as primitive
  13437. operators.
  13438. \begin{figure}[tp]
  13439. \fbox{
  13440. \begin{minipage}{0.96\textwidth}
  13441. \small
  13442. \[
  13443. \begin{array}{lcl}
  13444. \Exp &::= & \ldots
  13445. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  13446. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  13447. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  13448. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  13449. \MID \GOTO{\itm{label}} } \\
  13450. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  13451. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  13452. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  13453. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  13454. \end{array}
  13455. \]
  13456. \end{minipage}
  13457. }
  13458. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  13459. \label{fig:c4-syntax}
  13460. \end{figure}
  13461. \section{Select Instructions}
  13462. \label{sec:select-instructions-Rlambda}
  13463. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  13464. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  13465. (Section~\ref{sec:select-instructions-gc}). The only difference is
  13466. that you should place the \itm{arity} in the tag that is stored at
  13467. position $0$ of the vector. Recall that in
  13468. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  13469. was not used. We store the arity in the $5$ bits starting at position
  13470. $58$.
  13471. Compile the \code{procedure-arity} operator into a sequence of
  13472. instructions that access the tag from position $0$ of the vector and
  13473. extract the $5$-bits starting at position $58$ from the tag.
  13474. \begin{figure}[p]
  13475. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13476. \node (Rfun) at (0,2) {\large \LangLam{}};
  13477. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  13478. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  13479. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  13480. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  13481. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13482. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  13483. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13484. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13485. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13486. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13487. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13488. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13489. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13490. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13491. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13492. \path[->,bend left=15] (Rfun) edge [above] node
  13493. {\ttfamily\footnotesize shrink} (Rfun-2);
  13494. \path[->,bend left=15] (Rfun-2) edge [above] node
  13495. {\ttfamily\footnotesize uniquify} (Rfun-3);
  13496. \path[->,bend left=15] (Rfun-3) edge [above] node
  13497. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  13498. \path[->,bend left=15] (F1-0) edge [right] node
  13499. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  13500. \path[->,bend left=15] (F1-1) edge [below] node
  13501. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  13502. \path[->,bend right=15] (F1-2) edge [above] node
  13503. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  13504. \path[->,bend right=15] (F1-3) edge [above] node
  13505. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  13506. \path[->,bend right=15] (F1-4) edge [above] node
  13507. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13508. \path[->,bend right=15] (F1-5) edge [right] node
  13509. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13510. \path[->,bend left=15] (C3-2) edge [left] node
  13511. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13512. \path[->,bend right=15] (x86-2) edge [left] node
  13513. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13514. \path[->,bend right=15] (x86-2-1) edge [below] node
  13515. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13516. \path[->,bend right=15] (x86-2-2) edge [left] node
  13517. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13518. \path[->,bend left=15] (x86-3) edge [above] node
  13519. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13520. \path[->,bend left=15] (x86-4) edge [right] node
  13521. {\ttfamily\footnotesize print\_x86} (x86-5);
  13522. \end{tikzpicture}
  13523. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  13524. functions.}
  13525. \label{fig:Rlambda-passes}
  13526. \end{figure}
  13527. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  13528. for the compilation of \LangLam{}.
  13529. \clearpage
  13530. \section{Challenge: Optimize Closures}
  13531. \label{sec:optimize-closures}
  13532. In this chapter we compiled lexically-scoped functions into a
  13533. relatively efficient representation: flat closures. However, even this
  13534. representation comes with some overhead. For example, consider the
  13535. following program with a function \code{tail\_sum} that does not have
  13536. any free variables and where all the uses of \code{tail\_sum} are in
  13537. applications where we know that only \code{tail\_sum} is being applied
  13538. (and not any other functions).
  13539. \begin{center}
  13540. \begin{minipage}{0.95\textwidth}
  13541. \begin{lstlisting}
  13542. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13543. (if (eq? n 0)
  13544. r
  13545. (tail_sum (- n 1) (+ n r))))
  13546. (+ (tail_sum 5 0) 27)
  13547. \end{lstlisting}
  13548. \end{minipage}
  13549. \end{center}
  13550. As described in this chapter, we uniformly apply closure conversion to
  13551. all functions, obtaining the following output for this program.
  13552. \begin{center}
  13553. \begin{minipage}{0.95\textwidth}
  13554. \begin{lstlisting}
  13555. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  13556. (if (eq? n2 0)
  13557. r3
  13558. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  13559. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  13560. (define (main) : Integer
  13561. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  13562. ((vector-ref clos6 0) clos6 5 0)) 27))
  13563. \end{lstlisting}
  13564. \end{minipage}
  13565. \end{center}
  13566. In the previous Chapter, there would be no allocation in the program
  13567. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  13568. the above program allocates memory for each \code{closure} and the
  13569. calls to \code{tail\_sum} are indirect. These two differences incur
  13570. considerable overhead in a program such as this one, where the
  13571. allocations and indirect calls occur inside a tight loop.
  13572. One might think that this problem is trivial to solve: can't we just
  13573. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  13574. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  13575. e'_n$)} instead of treating it like a call to a closure? We would
  13576. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  13577. %
  13578. However, this problem is not so trivial because a global function may
  13579. ``escape'' and become involved in applications that also involve
  13580. closures. Consider the following example in which the application
  13581. \code{(f 41)} needs to be compiled into a closure application, because
  13582. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  13583. function might also get bound to \code{f}.
  13584. \begin{lstlisting}
  13585. (define (add1 [x : Integer]) : Integer
  13586. (+ x 1))
  13587. (let ([y (read)])
  13588. (let ([f (if (eq? (read) 0)
  13589. add1
  13590. (lambda: ([x : Integer]) : Integer (- x y)))])
  13591. (f 41)))
  13592. \end{lstlisting}
  13593. If a global function name is used in any way other than as the
  13594. operator in a direct call, then we say that the function
  13595. \emph{escapes}. If a global function does not escape, then we do not
  13596. need to perform closure conversion on the function.
  13597. \begin{exercise}\normalfont
  13598. Implement an auxiliary function for detecting which global
  13599. functions escape. Using that function, implement an improved version
  13600. of closure conversion that does not apply closure conversion to
  13601. global functions that do not escape but instead compiles them as
  13602. regular functions. Create several new test cases that check whether
  13603. you properly detect whether global functions escape or not.
  13604. \end{exercise}
  13605. So far we have reduced the overhead of calling global functions, but
  13606. it would also be nice to reduce the overhead of calling a
  13607. \code{lambda} when we can determine at compile time which
  13608. \code{lambda} will be called. We refer to such calls as \emph{known
  13609. calls}. Consider the following example in which a \code{lambda} is
  13610. bound to \code{f} and then applied.
  13611. \begin{lstlisting}
  13612. (let ([y (read)])
  13613. (let ([f (lambda: ([x : Integer]) : Integer
  13614. (+ x y))])
  13615. (f 21)))
  13616. \end{lstlisting}
  13617. Closure conversion compiles \code{(f 21)} into an indirect call:
  13618. \begin{lstlisting}
  13619. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  13620. (let ([y2 (vector-ref fvs6 1)])
  13621. (+ x3 y2)))
  13622. (define (main) : Integer
  13623. (let ([y2 (read)])
  13624. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  13625. ((vector-ref f4 0) f4 21))))
  13626. \end{lstlisting}
  13627. but we can instead compile the application \code{(f 21)} into a direct call
  13628. to \code{lambda5}:
  13629. \begin{lstlisting}
  13630. (define (main) : Integer
  13631. (let ([y2 (read)])
  13632. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  13633. ((fun-ref lambda5) f4 21))))
  13634. \end{lstlisting}
  13635. The problem of determining which lambda will be called from a
  13636. particular application is quite challenging in general and the topic
  13637. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  13638. following exercise we recommend that you compile an application to a
  13639. direct call when the operator is a variable and the variable is
  13640. \code{let}-bound to a closure. This can be accomplished by maintaining
  13641. an environment mapping \code{let}-bound variables to function names.
  13642. Extend the environment whenever you encounter a closure on the
  13643. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  13644. to the name of the global function for the closure. This pass should
  13645. come after closure conversion.
  13646. \begin{exercise}\normalfont
  13647. Implement a compiler pass, named \code{optimize-known-calls}, that
  13648. compiles known calls into direct calls. Verify that your compiler is
  13649. successful in this regard on several example programs.
  13650. \end{exercise}
  13651. These exercises only scratches the surface of optimizing of
  13652. closures. A good next step for the interested reader is to look at the
  13653. work of \citet{Keep:2012ab}.
  13654. \section{Further Reading}
  13655. The notion of lexically scoped anonymous functions predates modern
  13656. computers by about a decade. They were invented by
  13657. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  13658. foundation for logic. Anonymous functions were included in the
  13659. LISP~\citep{McCarthy:1960dz} programming language but were initially
  13660. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  13661. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  13662. compile Scheme programs. However, environments were represented as
  13663. linked lists, so variable lookup was linear in the size of the
  13664. environment. In this chapter we represent environments using flat
  13665. closures, which were invented by
  13666. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  13667. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  13668. closures, variable lookup is constant time but the time to create a
  13669. closure is proportional to the number of its free variables. Flat
  13670. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  13671. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  13672. \fi
  13673. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13674. \chapter{Dynamic Typing}
  13675. \label{ch:Rdyn}
  13676. \index{subject}{dynamic typing}
  13677. \if\edition\racketEd
  13678. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  13679. typed language that is a subset of Racket. This is in contrast to the
  13680. previous chapters, which have studied the compilation of Typed
  13681. Racket. In dynamically typed languages such as \LangDyn{}, a given
  13682. expression may produce a value of a different type each time it is
  13683. executed. Consider the following example with a conditional \code{if}
  13684. expression that may return a Boolean or an integer depending on the
  13685. input to the program.
  13686. % part of dynamic_test_25.rkt
  13687. \begin{lstlisting}
  13688. (not (if (eq? (read) 1) #f 0))
  13689. \end{lstlisting}
  13690. Languages that allow expressions to produce different kinds of values
  13691. are called \emph{polymorphic}, a word composed of the Greek roots
  13692. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  13693. are several kinds of polymorphism in programming languages, such as
  13694. subtype polymorphism and parametric
  13695. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  13696. study in this chapter does not have a special name but it is the kind
  13697. that arises in dynamically typed languages.
  13698. Another characteristic of dynamically typed languages is that
  13699. primitive operations, such as \code{not}, are often defined to operate
  13700. on many different types of values. In fact, in Racket, the \code{not}
  13701. operator produces a result for any kind of value: given \code{\#f} it
  13702. returns \code{\#t} and given anything else it returns \code{\#f}.
  13703. Furthermore, even when primitive operations restrict their inputs to
  13704. values of a certain type, this restriction is enforced at runtime
  13705. instead of during compilation. For example, the following vector
  13706. reference results in a run-time contract violation because the index
  13707. must be in integer, not a Boolean such as \code{\#t}.
  13708. \begin{lstlisting}
  13709. (vector-ref (vector 42) #t)
  13710. \end{lstlisting}
  13711. \begin{figure}[tp]
  13712. \centering
  13713. \fbox{
  13714. \begin{minipage}{0.97\textwidth}
  13715. \[
  13716. \begin{array}{rcl}
  13717. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  13718. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  13719. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  13720. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  13721. &\MID& \key{\#t} \MID \key{\#f}
  13722. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  13723. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  13724. \MID \CUNIOP{\key{not}}{\Exp} \\
  13725. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  13726. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  13727. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  13728. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  13729. &\MID& \LP\Exp \; \Exp\ldots\RP
  13730. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  13731. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  13732. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  13733. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  13734. \LangDynM{} &::=& \Def\ldots\; \Exp
  13735. \end{array}
  13736. \]
  13737. \end{minipage}
  13738. }
  13739. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  13740. \label{fig:r7-concrete-syntax}
  13741. \end{figure}
  13742. \begin{figure}[tp]
  13743. \centering
  13744. \fbox{
  13745. \begin{minipage}{0.96\textwidth}
  13746. \small
  13747. \[
  13748. \begin{array}{lcl}
  13749. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  13750. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  13751. &\MID& \BOOL{\itm{bool}}
  13752. \MID \IF{\Exp}{\Exp}{\Exp} \\
  13753. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  13754. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  13755. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  13756. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13757. \end{array}
  13758. \]
  13759. \end{minipage}
  13760. }
  13761. \caption{The abstract syntax of \LangDyn{}.}
  13762. \label{fig:r7-syntax}
  13763. \end{figure}
  13764. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  13765. defined in Figures~\ref{fig:r7-concrete-syntax} and
  13766. \ref{fig:r7-syntax}.
  13767. %
  13768. There is no type checker for \LangDyn{} because it is not a statically
  13769. typed language (it's dynamically typed!).
  13770. The definitional interpreter for \LangDyn{} is presented in
  13771. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  13772. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  13773. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  13774. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  13775. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  13776. value} that combines an underlying value with a tag that identifies
  13777. what kind of value it is. We define the following struct
  13778. to represented tagged values.
  13779. \begin{lstlisting}
  13780. (struct Tagged (value tag) #:transparent)
  13781. \end{lstlisting}
  13782. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  13783. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  13784. but don't always capture all the information that a type does. For
  13785. example, a vector of type \code{(Vector Any Any)} is tagged with
  13786. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  13787. is tagged with \code{Procedure}.
  13788. Next consider the match case for \code{vector-ref}. The
  13789. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  13790. is used to ensure that the first argument is a vector and the second
  13791. is an integer. If they are not, a \code{trapped-error} is raised.
  13792. Recall from Section~\ref{sec:interp_Lint} that when a definition
  13793. interpreter raises a \code{trapped-error} error, the compiled code
  13794. must also signal an error by exiting with return code \code{255}. A
  13795. \code{trapped-error} is also raised if the index is not less than
  13796. length of the vector.
  13797. \begin{figure}[tbp]
  13798. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13799. (define ((interp-Rdyn-exp env) ast)
  13800. (define recur (interp-Rdyn-exp env))
  13801. (match ast
  13802. [(Var x) (lookup x env)]
  13803. [(Int n) (Tagged n 'Integer)]
  13804. [(Bool b) (Tagged b 'Boolean)]
  13805. [(Lambda xs rt body)
  13806. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  13807. [(Prim 'vector es)
  13808. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  13809. [(Prim 'vector-ref (list e1 e2))
  13810. (define vec (recur e1)) (define i (recur e2))
  13811. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  13812. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  13813. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  13814. (vector-ref (Tagged-value vec) (Tagged-value i))]
  13815. [(Prim 'vector-set! (list e1 e2 e3))
  13816. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  13817. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  13818. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  13819. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  13820. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  13821. (Tagged (void) 'Void)]
  13822. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  13823. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  13824. [(Prim 'or (list e1 e2))
  13825. (define v1 (recur e1))
  13826. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  13827. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  13828. [(Prim op (list e1))
  13829. #:when (set-member? type-predicates op)
  13830. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  13831. [(Prim op es)
  13832. (define args (map recur es))
  13833. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  13834. (unless (for/or ([expected-tags (op-tags op)])
  13835. (equal? expected-tags tags))
  13836. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  13837. (tag-value
  13838. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  13839. [(If q t f)
  13840. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  13841. [(Apply f es)
  13842. (define new-f (recur f)) (define args (map recur es))
  13843. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  13844. (match f-val
  13845. [`(function ,xs ,body ,lam-env)
  13846. (unless (eq? (length xs) (length args))
  13847. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  13848. (define new-env (append (map cons xs args) lam-env))
  13849. ((interp-Rdyn-exp new-env) body)]
  13850. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  13851. \end{lstlisting}
  13852. \caption{Interpreter for the \LangDyn{} language.}
  13853. \label{fig:interp-Rdyn}
  13854. \end{figure}
  13855. \begin{figure}[tbp]
  13856. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13857. (define (interp-op op)
  13858. (match op
  13859. ['+ fx+]
  13860. ['- fx-]
  13861. ['read read-fixnum]
  13862. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  13863. ['< (lambda (v1 v2)
  13864. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  13865. ['<= (lambda (v1 v2)
  13866. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  13867. ['> (lambda (v1 v2)
  13868. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  13869. ['>= (lambda (v1 v2)
  13870. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  13871. ['boolean? boolean?]
  13872. ['integer? fixnum?]
  13873. ['void? void?]
  13874. ['vector? vector?]
  13875. ['vector-length vector-length]
  13876. ['procedure? (match-lambda
  13877. [`(functions ,xs ,body ,env) #t] [else #f])]
  13878. [else (error 'interp-op "unknown operator" op)]))
  13879. (define (op-tags op)
  13880. (match op
  13881. ['+ '((Integer Integer))]
  13882. ['- '((Integer Integer) (Integer))]
  13883. ['read '(())]
  13884. ['not '((Boolean))]
  13885. ['< '((Integer Integer))]
  13886. ['<= '((Integer Integer))]
  13887. ['> '((Integer Integer))]
  13888. ['>= '((Integer Integer))]
  13889. ['vector-length '((Vector))]))
  13890. (define type-predicates
  13891. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  13892. (define (tag-value v)
  13893. (cond [(boolean? v) (Tagged v 'Boolean)]
  13894. [(fixnum? v) (Tagged v 'Integer)]
  13895. [(procedure? v) (Tagged v 'Procedure)]
  13896. [(vector? v) (Tagged v 'Vector)]
  13897. [(void? v) (Tagged v 'Void)]
  13898. [else (error 'tag-value "unidentified value ~a" v)]))
  13899. (define (check-tag val expected ast)
  13900. (define tag (Tagged-tag val))
  13901. (unless (eq? tag expected)
  13902. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  13903. \end{lstlisting}
  13904. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  13905. \label{fig:interp-Rdyn-aux}
  13906. \end{figure}
  13907. \clearpage
  13908. \section{Representation of Tagged Values}
  13909. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  13910. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  13911. values at the bit level. Because almost every operation in \LangDyn{}
  13912. involves manipulating tagged values, the representation must be
  13913. efficient. Recall that all of our values are 64 bits. We shall steal
  13914. the 3 right-most bits to encode the tag. We use $001$ to identify
  13915. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  13916. and $101$ for the void value. We define the following auxiliary
  13917. function for mapping types to tag codes.
  13918. \begin{align*}
  13919. \itm{tagof}(\key{Integer}) &= 001 \\
  13920. \itm{tagof}(\key{Boolean}) &= 100 \\
  13921. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  13922. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  13923. \itm{tagof}(\key{Void}) &= 101
  13924. \end{align*}
  13925. This stealing of 3 bits comes at some price: our integers are reduced
  13926. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  13927. affect vectors and procedures because those values are addresses, and
  13928. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  13929. they are always $000$. Thus, we do not lose information by overwriting
  13930. the rightmost 3 bits with the tag and we can simply zero-out the tag
  13931. to recover the original address.
  13932. To make tagged values into first-class entities, we can give them a
  13933. type, called \code{Any}, and define operations such as \code{Inject}
  13934. and \code{Project} for creating and using them, yielding the \LangAny{}
  13935. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  13936. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  13937. in greater detail.
  13938. \section{The \LangAny{} Language}
  13939. \label{sec:Rany-lang}
  13940. \newcommand{\LAnyAST}{
  13941. \begin{array}{lcl}
  13942. \Type &::= & \key{Any} \\
  13943. \itm{op} &::= & \code{any-vector-length}
  13944. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  13945. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  13946. \MID \code{procedure?} \MID \code{void?} \\
  13947. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  13948. \end{array}
  13949. }
  13950. \begin{figure}[tp]
  13951. \centering
  13952. \fbox{
  13953. \begin{minipage}{0.96\textwidth}
  13954. \small
  13955. \[
  13956. \begin{array}{l}
  13957. \gray{\LintOpAST} \\ \hline
  13958. \gray{\LvarAST{}} \\ \hline
  13959. \gray{\LifAST{}} \\ \hline
  13960. \gray{\LwhileAST{}} \\ \hline
  13961. \gray{\LtupAST{}} \\ \hline
  13962. \gray{\LfunAST} \\ \hline
  13963. \gray{\LlambdaAST} \\ \hline
  13964. \LAnyAST \\
  13965. \begin{array}{lcl}
  13966. %% \Type &::= & \ldots \MID \key{Any} \\
  13967. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  13968. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  13969. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  13970. %% \MID \code{procedure?} \MID \code{void?} \\
  13971. %% \Exp &::=& \ldots
  13972. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  13973. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  13974. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  13975. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13976. \end{array}
  13977. \end{array}
  13978. \]
  13979. \end{minipage}
  13980. }
  13981. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  13982. \label{fig:Rany-syntax}
  13983. \end{figure}
  13984. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  13985. (The concrete syntax of \LangAny{} is in the Appendix,
  13986. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  13987. converts the value produced by expression $e$ of type $T$ into a
  13988. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  13989. produced by expression $e$ into a value of type $T$ or else halts the
  13990. program if the type tag is not equivalent to $T$.
  13991. %
  13992. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  13993. restricted to a flat type $\FType$, which simplifies the
  13994. implementation and corresponds with what is needed for compiling \LangDyn{}.
  13995. The \code{any-vector} operators adapt the vector operations so that
  13996. they can be applied to a value of type \code{Any}. They also
  13997. generalize the vector operations in that the index is not restricted
  13998. to be a literal integer in the grammar but is allowed to be any
  13999. expression.
  14000. The type predicates such as \key{boolean?} expect their argument to
  14001. produce a tagged value; they return \key{\#t} if the tag corresponds
  14002. to the predicate and they return \key{\#f} otherwise.
  14003. The type checker for \LangAny{} is shown in
  14004. Figures~\ref{fig:type-check-Rany-part-1} and
  14005. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  14006. Figure~\ref{fig:type-check-Rany-aux}.
  14007. %
  14008. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  14009. auxiliary functions \code{apply-inject} and \code{apply-project} are
  14010. in Figure~\ref{fig:apply-project}.
  14011. \begin{figure}[btp]
  14012. \begin{lstlisting}[basicstyle=\ttfamily\small]
  14013. (define type-check-Rany_class
  14014. (class type-check-Rlambda_class
  14015. (super-new)
  14016. (inherit check-type-equal?)
  14017. (define/override (type-check-exp env)
  14018. (lambda (e)
  14019. (define recur (type-check-exp env))
  14020. (match e
  14021. [(Inject e1 ty)
  14022. (unless (flat-ty? ty)
  14023. (error 'type-check "may only inject from flat type, not ~a" ty))
  14024. (define-values (new-e1 e-ty) (recur e1))
  14025. (check-type-equal? e-ty ty e)
  14026. (values (Inject new-e1 ty) 'Any)]
  14027. [(Project e1 ty)
  14028. (unless (flat-ty? ty)
  14029. (error 'type-check "may only project to flat type, not ~a" ty))
  14030. (define-values (new-e1 e-ty) (recur e1))
  14031. (check-type-equal? e-ty 'Any e)
  14032. (values (Project new-e1 ty) ty)]
  14033. [(Prim 'any-vector-length (list e1))
  14034. (define-values (e1^ t1) (recur e1))
  14035. (check-type-equal? t1 'Any e)
  14036. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  14037. [(Prim 'any-vector-ref (list e1 e2))
  14038. (define-values (e1^ t1) (recur e1))
  14039. (define-values (e2^ t2) (recur e2))
  14040. (check-type-equal? t1 'Any e)
  14041. (check-type-equal? t2 'Integer e)
  14042. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  14043. [(Prim 'any-vector-set! (list e1 e2 e3))
  14044. (define-values (e1^ t1) (recur e1))
  14045. (define-values (e2^ t2) (recur e2))
  14046. (define-values (e3^ t3) (recur e3))
  14047. (check-type-equal? t1 'Any e)
  14048. (check-type-equal? t2 'Integer e)
  14049. (check-type-equal? t3 'Any e)
  14050. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  14051. \end{lstlisting}
  14052. \caption{Type checker for the \LangAny{} language, part 1.}
  14053. \label{fig:type-check-Rany-part-1}
  14054. \end{figure}
  14055. \begin{figure}[btp]
  14056. \begin{lstlisting}[basicstyle=\ttfamily\small]
  14057. [(ValueOf e ty)
  14058. (define-values (new-e e-ty) (recur e))
  14059. (values (ValueOf new-e ty) ty)]
  14060. [(Prim pred (list e1))
  14061. #:when (set-member? (type-predicates) pred)
  14062. (define-values (new-e1 e-ty) (recur e1))
  14063. (check-type-equal? e-ty 'Any e)
  14064. (values (Prim pred (list new-e1)) 'Boolean)]
  14065. [(If cnd thn els)
  14066. (define-values (cnd^ Tc) (recur cnd))
  14067. (define-values (thn^ Tt) (recur thn))
  14068. (define-values (els^ Te) (recur els))
  14069. (check-type-equal? Tc 'Boolean cnd)
  14070. (check-type-equal? Tt Te e)
  14071. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  14072. [(Exit) (values (Exit) '_)]
  14073. [(Prim 'eq? (list arg1 arg2))
  14074. (define-values (e1 t1) (recur arg1))
  14075. (define-values (e2 t2) (recur arg2))
  14076. (match* (t1 t2)
  14077. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  14078. [(other wise) (check-type-equal? t1 t2 e)])
  14079. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  14080. [else ((super type-check-exp env) e)])))
  14081. ))
  14082. \end{lstlisting}
  14083. \caption{Type checker for the \LangAny{} language, part 2.}
  14084. \label{fig:type-check-Rany-part-2}
  14085. \end{figure}
  14086. \begin{figure}[tbp]
  14087. \begin{lstlisting}
  14088. (define/override (operator-types)
  14089. (append
  14090. '((integer? . ((Any) . Boolean))
  14091. (vector? . ((Any) . Boolean))
  14092. (procedure? . ((Any) . Boolean))
  14093. (void? . ((Any) . Boolean))
  14094. (tag-of-any . ((Any) . Integer))
  14095. (make-any . ((_ Integer) . Any))
  14096. )
  14097. (super operator-types)))
  14098. (define/public (type-predicates)
  14099. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  14100. (define/public (combine-types t1 t2)
  14101. (match (list t1 t2)
  14102. [(list '_ t2) t2]
  14103. [(list t1 '_) t1]
  14104. [(list `(Vector ,ts1 ...)
  14105. `(Vector ,ts2 ...))
  14106. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  14107. (combine-types t1 t2)))]
  14108. [(list `(,ts1 ... -> ,rt1)
  14109. `(,ts2 ... -> ,rt2))
  14110. `(,@(for/list ([t1 ts1] [t2 ts2])
  14111. (combine-types t1 t2))
  14112. -> ,(combine-types rt1 rt2))]
  14113. [else t1]))
  14114. (define/public (flat-ty? ty)
  14115. (match ty
  14116. [(or `Integer `Boolean '_ `Void) #t]
  14117. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  14118. [`(,ts ... -> ,rt)
  14119. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  14120. [else #f]))
  14121. \end{lstlisting}
  14122. \caption{Auxiliary methods for type checking \LangAny{}.}
  14123. \label{fig:type-check-Rany-aux}
  14124. \end{figure}
  14125. \begin{figure}[btp]
  14126. \begin{lstlisting}
  14127. (define interp-Rany_class
  14128. (class interp-Rlambda_class
  14129. (super-new)
  14130. (define/override (interp-op op)
  14131. (match op
  14132. ['boolean? (match-lambda
  14133. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  14134. [else #f])]
  14135. ['integer? (match-lambda
  14136. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  14137. [else #f])]
  14138. ['vector? (match-lambda
  14139. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  14140. [else #f])]
  14141. ['procedure? (match-lambda
  14142. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  14143. [else #f])]
  14144. ['eq? (match-lambda*
  14145. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  14146. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  14147. [ls (apply (super interp-op op) ls)])]
  14148. ['any-vector-ref (lambda (v i)
  14149. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  14150. ['any-vector-set! (lambda (v i a)
  14151. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  14152. ['any-vector-length (lambda (v)
  14153. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  14154. [else (super interp-op op)]))
  14155. (define/override ((interp-exp env) e)
  14156. (define recur (interp-exp env))
  14157. (match e
  14158. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  14159. [(Project e ty2) (apply-project (recur e) ty2)]
  14160. [else ((super interp-exp env) e)]))
  14161. ))
  14162. (define (interp-Rany p)
  14163. (send (new interp-Rany_class) interp-program p))
  14164. \end{lstlisting}
  14165. \caption{Interpreter for \LangAny{}.}
  14166. \label{fig:interp-Rany}
  14167. \end{figure}
  14168. \begin{figure}[tbp]
  14169. \begin{lstlisting}
  14170. (define/public (apply-inject v tg) (Tagged v tg))
  14171. (define/public (apply-project v ty2)
  14172. (define tag2 (any-tag ty2))
  14173. (match v
  14174. [(Tagged v1 tag1)
  14175. (cond
  14176. [(eq? tag1 tag2)
  14177. (match ty2
  14178. [`(Vector ,ts ...)
  14179. (define l1 ((interp-op 'vector-length) v1))
  14180. (cond
  14181. [(eq? l1 (length ts)) v1]
  14182. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  14183. l1 (length ts))])]
  14184. [`(,ts ... -> ,rt)
  14185. (match v1
  14186. [`(function ,xs ,body ,env)
  14187. (cond [(eq? (length xs) (length ts)) v1]
  14188. [else
  14189. (error 'apply-project "arity mismatch ~a != ~a"
  14190. (length xs) (length ts))])]
  14191. [else (error 'apply-project "expected function not ~a" v1)])]
  14192. [else v1])]
  14193. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  14194. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  14195. \end{lstlisting}
  14196. \caption{Auxiliary functions for injection and projection.}
  14197. \label{fig:apply-project}
  14198. \end{figure}
  14199. \clearpage
  14200. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  14201. \label{sec:compile-r7}
  14202. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  14203. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  14204. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  14205. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  14206. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  14207. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  14208. the Boolean \code{\#t}, which must be injected to produce an
  14209. expression of type \key{Any}.
  14210. %
  14211. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  14212. addition, is representative of compilation for many primitive
  14213. operations: the arguments have type \key{Any} and must be projected to
  14214. \key{Integer} before the addition can be performed.
  14215. The compilation of \key{lambda} (third row of
  14216. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  14217. produce type annotations: we simply use \key{Any}.
  14218. %
  14219. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  14220. has to account for some differences in behavior between \LangDyn{} and
  14221. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  14222. kind of values can be used in various places. For example, the
  14223. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  14224. the arguments need not be of the same type (in that case the
  14225. result is \code{\#f}).
  14226. \begin{figure}[btp]
  14227. \centering
  14228. \begin{tabular}{|lll|} \hline
  14229. \begin{minipage}{0.27\textwidth}
  14230. \begin{lstlisting}
  14231. #t
  14232. \end{lstlisting}
  14233. \end{minipage}
  14234. &
  14235. $\Rightarrow$
  14236. &
  14237. \begin{minipage}{0.65\textwidth}
  14238. \begin{lstlisting}
  14239. (inject #t Boolean)
  14240. \end{lstlisting}
  14241. \end{minipage}
  14242. \\[2ex]\hline
  14243. \begin{minipage}{0.27\textwidth}
  14244. \begin{lstlisting}
  14245. (+ |$e_1$| |$e_2$|)
  14246. \end{lstlisting}
  14247. \end{minipage}
  14248. &
  14249. $\Rightarrow$
  14250. &
  14251. \begin{minipage}{0.65\textwidth}
  14252. \begin{lstlisting}
  14253. (inject
  14254. (+ (project |$e'_1$| Integer)
  14255. (project |$e'_2$| Integer))
  14256. Integer)
  14257. \end{lstlisting}
  14258. \end{minipage}
  14259. \\[2ex]\hline
  14260. \begin{minipage}{0.27\textwidth}
  14261. \begin{lstlisting}
  14262. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  14263. \end{lstlisting}
  14264. \end{minipage}
  14265. &
  14266. $\Rightarrow$
  14267. &
  14268. \begin{minipage}{0.65\textwidth}
  14269. \begin{lstlisting}
  14270. (inject
  14271. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  14272. (Any|$\ldots$|Any -> Any))
  14273. \end{lstlisting}
  14274. \end{minipage}
  14275. \\[2ex]\hline
  14276. \begin{minipage}{0.27\textwidth}
  14277. \begin{lstlisting}
  14278. (|$e_0$| |$e_1 \ldots e_n$|)
  14279. \end{lstlisting}
  14280. \end{minipage}
  14281. &
  14282. $\Rightarrow$
  14283. &
  14284. \begin{minipage}{0.65\textwidth}
  14285. \begin{lstlisting}
  14286. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  14287. \end{lstlisting}
  14288. \end{minipage}
  14289. \\[2ex]\hline
  14290. \begin{minipage}{0.27\textwidth}
  14291. \begin{lstlisting}
  14292. (vector-ref |$e_1$| |$e_2$|)
  14293. \end{lstlisting}
  14294. \end{minipage}
  14295. &
  14296. $\Rightarrow$
  14297. &
  14298. \begin{minipage}{0.65\textwidth}
  14299. \begin{lstlisting}
  14300. (any-vector-ref |$e_1'$| |$e_2'$|)
  14301. \end{lstlisting}
  14302. \end{minipage}
  14303. \\[2ex]\hline
  14304. \begin{minipage}{0.27\textwidth}
  14305. \begin{lstlisting}
  14306. (if |$e_1$| |$e_2$| |$e_3$|)
  14307. \end{lstlisting}
  14308. \end{minipage}
  14309. &
  14310. $\Rightarrow$
  14311. &
  14312. \begin{minipage}{0.65\textwidth}
  14313. \begin{lstlisting}
  14314. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  14315. \end{lstlisting}
  14316. \end{minipage}
  14317. \\[2ex]\hline
  14318. \begin{minipage}{0.27\textwidth}
  14319. \begin{lstlisting}
  14320. (eq? |$e_1$| |$e_2$|)
  14321. \end{lstlisting}
  14322. \end{minipage}
  14323. &
  14324. $\Rightarrow$
  14325. &
  14326. \begin{minipage}{0.65\textwidth}
  14327. \begin{lstlisting}
  14328. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  14329. \end{lstlisting}
  14330. \end{minipage}
  14331. \\[2ex]\hline
  14332. \begin{minipage}{0.27\textwidth}
  14333. \begin{lstlisting}
  14334. (not |$e_1$|)
  14335. \end{lstlisting}
  14336. \end{minipage}
  14337. &
  14338. $\Rightarrow$
  14339. &
  14340. \begin{minipage}{0.65\textwidth}
  14341. \begin{lstlisting}
  14342. (if (eq? |$e'_1$| (inject #f Boolean))
  14343. (inject #t Boolean) (inject #f Boolean))
  14344. \end{lstlisting}
  14345. \end{minipage}
  14346. \\[2ex]\hline
  14347. \end{tabular}
  14348. \caption{Cast Insertion}
  14349. \label{fig:compile-r7-Rany}
  14350. \end{figure}
  14351. \section{Reveal Casts}
  14352. \label{sec:reveal-casts-Rany}
  14353. % TODO: define R'_6
  14354. In the \code{reveal-casts} pass we recommend compiling \code{project}
  14355. into an \code{if} expression that checks whether the value's tag
  14356. matches the target type; if it does, the value is converted to a value
  14357. of the target type by removing the tag; if it does not, the program
  14358. exits. To perform these actions we need a new primitive operation,
  14359. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  14360. The \code{tag-of-any} operation retrieves the type tag from a tagged
  14361. value of type \code{Any}. The \code{ValueOf} form retrieves the
  14362. underlying value from a tagged value. The \code{ValueOf} form
  14363. includes the type for the underlying value which is used by the type
  14364. checker. Finally, the \code{Exit} form ends the execution of the
  14365. program.
  14366. If the target type of the projection is \code{Boolean} or
  14367. \code{Integer}, then \code{Project} can be translated as follows.
  14368. \begin{center}
  14369. \begin{minipage}{1.0\textwidth}
  14370. \begin{lstlisting}
  14371. (Project |$e$| |$\FType$|)
  14372. |$\Rightarrow$|
  14373. (Let |$\itm{tmp}$| |$e'$|
  14374. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  14375. (Int |$\itm{tagof}(\FType)$|)))
  14376. (ValueOf |$\itm{tmp}$| |$\FType$|)
  14377. (Exit)))
  14378. \end{lstlisting}
  14379. \end{minipage}
  14380. \end{center}
  14381. If the target type of the projection is a vector or function type,
  14382. then there is a bit more work to do. For vectors, check that the
  14383. length of the vector type matches the length of the vector (using the
  14384. \code{vector-length} primitive). For functions, check that the number
  14385. of parameters in the function type matches the function's arity (using
  14386. \code{procedure-arity}).
  14387. Regarding \code{inject}, we recommend compiling it to a slightly
  14388. lower-level primitive operation named \code{make-any}. This operation
  14389. takes a tag instead of a type.
  14390. \begin{center}
  14391. \begin{minipage}{1.0\textwidth}
  14392. \begin{lstlisting}
  14393. (Inject |$e$| |$\FType$|)
  14394. |$\Rightarrow$|
  14395. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  14396. \end{lstlisting}
  14397. \end{minipage}
  14398. \end{center}
  14399. The type predicates (\code{boolean?}, etc.) can be translated into
  14400. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  14401. translation of \code{Project}.
  14402. The \code{any-vector-ref} and \code{any-vector-set!} operations
  14403. combine the projection action with the vector operation. Also, the
  14404. read and write operations allow arbitrary expressions for the index so
  14405. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  14406. cannot guarantee that the index is within bounds. Thus, we insert code
  14407. to perform bounds checking at runtime. The translation for
  14408. \code{any-vector-ref} is as follows and the other two operations are
  14409. translated in a similar way.
  14410. \begin{lstlisting}
  14411. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  14412. |$\Rightarrow$|
  14413. (Let |$v$| |$e'_1$|
  14414. (Let |$i$| |$e'_2$|
  14415. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  14416. (If (Prim '< (list (Var |$i$|)
  14417. (Prim 'any-vector-length (list (Var |$v$|)))))
  14418. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  14419. (Exit))))
  14420. \end{lstlisting}
  14421. \section{Remove Complex Operands}
  14422. \label{sec:rco-Rany}
  14423. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  14424. The subexpression of \code{ValueOf} must be atomic.
  14425. \section{Explicate Control and \LangCAny{}}
  14426. \label{sec:explicate-Rany}
  14427. The output of \code{explicate\_control} is the \LangCAny{} language whose
  14428. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  14429. form that we added to \LangAny{} remains an expression and the \code{Exit}
  14430. expression becomes a $\Tail$. Also, note that the index argument of
  14431. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  14432. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  14433. \begin{figure}[tp]
  14434. \fbox{
  14435. \begin{minipage}{0.96\textwidth}
  14436. \small
  14437. \[
  14438. \begin{array}{lcl}
  14439. \Exp &::= & \ldots
  14440. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  14441. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  14442. &\MID& \VALUEOF{\Exp}{\FType} \\
  14443. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14444. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  14445. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14446. \MID \GOTO{\itm{label}} } \\
  14447. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14448. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  14449. \MID \LP\key{Exit}\RP \\
  14450. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14451. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14452. \end{array}
  14453. \]
  14454. \end{minipage}
  14455. }
  14456. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  14457. \label{fig:c5-syntax}
  14458. \end{figure}
  14459. \section{Select Instructions}
  14460. \label{sec:select-Rany}
  14461. In the \code{select\_instructions} pass we translate the primitive
  14462. operations on the \code{Any} type to x86 instructions that involve
  14463. manipulating the 3 tag bits of the tagged value.
  14464. \paragraph{Make-any}
  14465. We recommend compiling the \key{make-any} primitive as follows if the
  14466. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  14467. shifts the destination to the left by the number of bits specified its
  14468. source argument (in this case $3$, the length of the tag) and it
  14469. preserves the sign of the integer. We use the \key{orq} instruction to
  14470. combine the tag and the value to form the tagged value. \\
  14471. \begin{lstlisting}
  14472. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  14473. |$\Rightarrow$|
  14474. movq |$e'$|, |\itm{lhs'}|
  14475. salq $3, |\itm{lhs'}|
  14476. orq $|$\itm{tag}$|, |\itm{lhs'}|
  14477. \end{lstlisting}
  14478. The instruction selection for vectors and procedures is different
  14479. because their is no need to shift them to the left. The rightmost 3
  14480. bits are already zeros as described at the beginning of this
  14481. chapter. So we just combine the value and the tag using \key{orq}. \\
  14482. \begin{lstlisting}
  14483. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  14484. |$\Rightarrow$|
  14485. movq |$e'$|, |\itm{lhs'}|
  14486. orq $|$\itm{tag}$|, |\itm{lhs'}|
  14487. \end{lstlisting}
  14488. \paragraph{Tag-of-any}
  14489. Recall that the \code{tag-of-any} operation extracts the type tag from
  14490. a value of type \code{Any}. The type tag is the bottom three bits, so
  14491. we obtain the tag by taking the bitwise-and of the value with $111$
  14492. ($7$ in decimal).
  14493. \begin{lstlisting}
  14494. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  14495. |$\Rightarrow$|
  14496. movq |$e'$|, |\itm{lhs'}|
  14497. andq $7, |\itm{lhs'}|
  14498. \end{lstlisting}
  14499. \paragraph{ValueOf}
  14500. Like \key{make-any}, the instructions for \key{ValueOf} are different
  14501. depending on whether the type $T$ is a pointer (vector or procedure)
  14502. or not (Integer or Boolean). The following shows the instruction
  14503. selection for Integer and Boolean. We produce an untagged value by
  14504. shifting it to the right by 3 bits.
  14505. \begin{lstlisting}
  14506. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  14507. |$\Rightarrow$|
  14508. movq |$e'$|, |\itm{lhs'}|
  14509. sarq $3, |\itm{lhs'}|
  14510. \end{lstlisting}
  14511. %
  14512. In the case for vectors and procedures, there is no need to
  14513. shift. Instead we just need to zero-out the rightmost 3 bits. We
  14514. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  14515. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  14516. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  14517. then apply \code{andq} with the tagged value to get the desired
  14518. result. \\
  14519. \begin{lstlisting}
  14520. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  14521. |$\Rightarrow$|
  14522. movq $|$-8$|, |\itm{lhs'}|
  14523. andq |$e'$|, |\itm{lhs'}|
  14524. \end{lstlisting}
  14525. %% \paragraph{Type Predicates} We leave it to the reader to
  14526. %% devise a sequence of instructions to implement the type predicates
  14527. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  14528. \paragraph{Any-vector-length}
  14529. \begin{lstlisting}
  14530. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  14531. |$\Longrightarrow$|
  14532. movq |$\neg 111$|, %r11
  14533. andq |$a_1'$|, %r11
  14534. movq 0(%r11), %r11
  14535. andq $126, %r11
  14536. sarq $1, %r11
  14537. movq %r11, |$\itm{lhs'}$|
  14538. \end{lstlisting}
  14539. \paragraph{Any-vector-ref}
  14540. The index may be an arbitrary atom so instead of computing the offset
  14541. at compile time, instructions need to be generated to compute the
  14542. offset at runtime as follows. Note the use of the new instruction
  14543. \code{imulq}.
  14544. \begin{center}
  14545. \begin{minipage}{0.96\textwidth}
  14546. \begin{lstlisting}
  14547. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  14548. |$\Longrightarrow$|
  14549. movq |$\neg 111$|, %r11
  14550. andq |$a_1'$|, %r11
  14551. movq |$a_2'$|, %rax
  14552. addq $1, %rax
  14553. imulq $8, %rax
  14554. addq %rax, %r11
  14555. movq 0(%r11) |$\itm{lhs'}$|
  14556. \end{lstlisting}
  14557. \end{minipage}
  14558. \end{center}
  14559. \paragraph{Any-vector-set!}
  14560. The code generation for \code{any-vector-set!} is similar to the other
  14561. \code{any-vector} operations.
  14562. \section{Register Allocation for \LangAny{}}
  14563. \label{sec:register-allocation-Rany}
  14564. \index{subject}{register allocation}
  14565. There is an interesting interaction between tagged values and garbage
  14566. collection that has an impact on register allocation. A variable of
  14567. type \code{Any} might refer to a vector and therefore it might be a
  14568. root that needs to be inspected and copied during garbage
  14569. collection. Thus, we need to treat variables of type \code{Any} in a
  14570. similar way to variables of type \code{Vector} for purposes of
  14571. register allocation. In particular,
  14572. \begin{itemize}
  14573. \item If a variable of type \code{Any} is live during a function call,
  14574. then it must be spilled. This can be accomplished by changing
  14575. \code{build\_interference} to mark all variables of type \code{Any}
  14576. that are live after a \code{callq} as interfering with all the
  14577. registers.
  14578. \item If a variable of type \code{Any} is spilled, it must be spilled
  14579. to the root stack instead of the normal procedure call stack.
  14580. \end{itemize}
  14581. Another concern regarding the root stack is that the garbage collector
  14582. needs to differentiate between (1) plain old pointers to tuples, (2) a
  14583. tagged value that points to a tuple, and (3) a tagged value that is
  14584. not a tuple. We enable this differentiation by choosing not to use the
  14585. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  14586. reserved for identifying plain old pointers to tuples. That way, if
  14587. one of the first three bits is set, then we have a tagged value and
  14588. inspecting the tag can differentiation between vectors ($010$) and the
  14589. other kinds of values.
  14590. \begin{exercise}\normalfont
  14591. Expand your compiler to handle \LangAny{} as discussed in the last few
  14592. sections. Create 5 new programs that use the \code{Any} type and the
  14593. new operations (\code{inject}, \code{project}, \code{boolean?},
  14594. etc.). Test your compiler on these new programs and all of your
  14595. previously created test programs.
  14596. \end{exercise}
  14597. \begin{exercise}\normalfont
  14598. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  14599. Create tests for \LangDyn{} by adapting ten of your previous test programs
  14600. by removing type annotations. Add 5 more tests programs that
  14601. specifically rely on the language being dynamically typed. That is,
  14602. they should not be legal programs in a statically typed language, but
  14603. nevertheless, they should be valid \LangDyn{} programs that run to
  14604. completion without error.
  14605. \end{exercise}
  14606. \begin{figure}[p]
  14607. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14608. \node (Rfun) at (0,4) {\large \LangDyn{}};
  14609. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  14610. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  14611. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  14612. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  14613. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  14614. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  14615. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  14616. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  14617. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  14618. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  14619. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  14620. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14621. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14622. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14623. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14624. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14625. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14626. \path[->,bend left=15] (Rfun) edge [above] node
  14627. {\ttfamily\footnotesize shrink} (Rfun-2);
  14628. \path[->,bend left=15] (Rfun-2) edge [above] node
  14629. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14630. \path[->,bend left=15] (Rfun-3) edge [above] node
  14631. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  14632. \path[->,bend right=15] (Rfun-4) edge [left] node
  14633. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  14634. \path[->,bend left=15] (Rfun-5) edge [above] node
  14635. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  14636. \path[->,bend left=15] (Rfun-6) edge [left] node
  14637. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  14638. \path[->,bend left=15] (Rfun-7) edge [below] node
  14639. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14640. \path[->,bend right=15] (F1-2) edge [above] node
  14641. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14642. \path[->,bend right=15] (F1-3) edge [above] node
  14643. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14644. \path[->,bend right=15] (F1-4) edge [above] node
  14645. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14646. \path[->,bend right=15] (F1-5) edge [right] node
  14647. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14648. \path[->,bend left=15] (C3-2) edge [left] node
  14649. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14650. \path[->,bend right=15] (x86-2) edge [left] node
  14651. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14652. \path[->,bend right=15] (x86-2-1) edge [below] node
  14653. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14654. \path[->,bend right=15] (x86-2-2) edge [left] node
  14655. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14656. \path[->,bend left=15] (x86-3) edge [above] node
  14657. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14658. \path[->,bend left=15] (x86-4) edge [right] node
  14659. {\ttfamily\footnotesize print\_x86} (x86-5);
  14660. \end{tikzpicture}
  14661. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  14662. \label{fig:Rdyn-passes}
  14663. \end{figure}
  14664. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  14665. for the compilation of \LangDyn{}.
  14666. % Further Reading
  14667. \fi % racketEd
  14668. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14669. {\if\edition\pythonEd
  14670. \chapter{Objects}
  14671. \label{ch:Robject}
  14672. \index{subject}{objects}
  14673. \index{subject}{classes}
  14674. \fi}
  14675. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14676. \chapter{Gradual Typing}
  14677. \label{ch:Rgrad}
  14678. \index{subject}{gradual typing}
  14679. \if\edition\racketEd
  14680. This chapter studies a language, \LangGrad{}, in which the programmer
  14681. can choose between static and dynamic type checking in different parts
  14682. of a program, thereby mixing the statically typed \LangLoop{} language
  14683. with the dynamically typed \LangDyn{}. There are several approaches to
  14684. mixing static and dynamic typing, including multi-language
  14685. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  14686. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  14687. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  14688. programmer controls the amount of static versus dynamic checking by
  14689. adding or removing type annotations on parameters and
  14690. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  14691. %
  14692. The concrete syntax of \LangGrad{} is defined in
  14693. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  14694. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  14695. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  14696. non-terminals that make type annotations optional. The return types
  14697. are not optional in the abstract syntax; the parser fills in
  14698. \code{Any} when the return type is not specified in the concrete
  14699. syntax.
  14700. \begin{figure}[tp]
  14701. \centering
  14702. \fbox{
  14703. \begin{minipage}{0.96\textwidth}
  14704. \small
  14705. \[
  14706. \begin{array}{lcl}
  14707. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  14708. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  14709. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  14710. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  14711. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  14712. &\MID& \gray{\key{\#t} \MID \key{\#f}
  14713. \MID (\key{and}\;\Exp\;\Exp)
  14714. \MID (\key{or}\;\Exp\;\Exp)
  14715. \MID (\key{not}\;\Exp) } \\
  14716. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  14717. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  14718. (\key{vector-ref}\;\Exp\;\Int)} \\
  14719. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  14720. \MID (\Exp \; \Exp\ldots) } \\
  14721. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  14722. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  14723. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  14724. \MID \CBEGIN{\Exp\ldots}{\Exp}
  14725. \MID \CWHILE{\Exp}{\Exp} } \\
  14726. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  14727. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  14728. \end{array}
  14729. \]
  14730. \end{minipage}
  14731. }
  14732. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  14733. \label{fig:Rgrad-concrete-syntax}
  14734. \end{figure}
  14735. \begin{figure}[tp]
  14736. \centering
  14737. \fbox{
  14738. \begin{minipage}{0.96\textwidth}
  14739. \small
  14740. \[
  14741. \begin{array}{lcl}
  14742. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  14743. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  14744. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  14745. &\MID& \gray{ \BOOL{\itm{bool}}
  14746. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  14747. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  14748. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  14749. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  14750. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  14751. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  14752. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  14753. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14754. \end{array}
  14755. \]
  14756. \end{minipage}
  14757. }
  14758. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  14759. \label{fig:Rgrad-syntax}
  14760. \end{figure}
  14761. Both the type checker and the interpreter for \LangGrad{} require some
  14762. interesting changes to enable gradual typing, which we discuss in the
  14763. next two sections in the context of the \code{map-vec} example from
  14764. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  14765. revised the \code{map-vec} example, omitting the type annotations from
  14766. the \code{add1} function.
  14767. \begin{figure}[btp]
  14768. % gradual_test_9.rkt
  14769. \begin{lstlisting}
  14770. (define (map-vec [f : (Integer -> Integer)]
  14771. [v : (Vector Integer Integer)])
  14772. : (Vector Integer Integer)
  14773. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14774. (define (add1 x) (+ x 1))
  14775. (vector-ref (map-vec add1 (vector 0 41)) 1)
  14776. \end{lstlisting}
  14777. \caption{A partially-typed version of the \code{map-vec} example.}
  14778. \label{fig:gradual-map-vec}
  14779. \end{figure}
  14780. \section{Type Checking \LangGrad{} and \LangCast{}}
  14781. \label{sec:gradual-type-check}
  14782. The type checker for \LangGrad{} uses the \code{Any} type for missing
  14783. parameter and return types. For example, the \code{x} parameter of
  14784. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  14785. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  14786. consider the \code{+} operator inside \code{add1}. It expects both
  14787. arguments to have type \code{Integer}, but its first argument \code{x}
  14788. has type \code{Any}. In a gradually typed language, such differences
  14789. are allowed so long as the types are \emph{consistent}, that is, they
  14790. are equal except in places where there is an \code{Any} type. The type
  14791. \code{Any} is consistent with every other type.
  14792. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  14793. \begin{figure}[tbp]
  14794. \begin{lstlisting}
  14795. (define/public (consistent? t1 t2)
  14796. (match* (t1 t2)
  14797. [('Integer 'Integer) #t]
  14798. [('Boolean 'Boolean) #t]
  14799. [('Void 'Void) #t]
  14800. [('Any t2) #t]
  14801. [(t1 'Any) #t]
  14802. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14803. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  14804. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14805. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  14806. (consistent? rt1 rt2))]
  14807. [(other wise) #f]))
  14808. \end{lstlisting}
  14809. \caption{The consistency predicate on types.}
  14810. \label{fig:consistent}
  14811. \end{figure}
  14812. Returning to the \code{map-vec} example of
  14813. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  14814. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  14815. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  14816. because the two types are consistent. In particular, \code{->} is
  14817. equal to \code{->} and because \code{Any} is consistent with
  14818. \code{Integer}.
  14819. Next consider a program with an error, such as applying the
  14820. \code{map-vec} to a function that sometimes returns a Boolean, as
  14821. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  14822. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  14823. consistent with the type of parameter \code{f} of \code{map-vec}, that
  14824. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  14825. Integer)}. One might say that a gradual type checker is optimistic
  14826. in that it accepts programs that might execute without a runtime type
  14827. error.
  14828. %
  14829. Unfortunately, running this program with input \code{1} triggers an
  14830. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  14831. performs checking at runtime to ensure the integrity of the static
  14832. types, such as the \code{(Integer -> Integer)} annotation on parameter
  14833. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  14834. new \code{Cast} form that is inserted by the type checker. Thus, the
  14835. output of the type checker is a program in the \LangCast{} language, which
  14836. adds \code{Cast} to \LangLoop{}, as shown in
  14837. Figure~\ref{fig:Rgrad-prime-syntax}.
  14838. \begin{figure}[tp]
  14839. \centering
  14840. \fbox{
  14841. \begin{minipage}{0.96\textwidth}
  14842. \small
  14843. \[
  14844. \begin{array}{lcl}
  14845. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  14846. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14847. \end{array}
  14848. \]
  14849. \end{minipage}
  14850. }
  14851. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  14852. \label{fig:Rgrad-prime-syntax}
  14853. \end{figure}
  14854. \begin{figure}[tbp]
  14855. \begin{lstlisting}
  14856. (define (map-vec [f : (Integer -> Integer)]
  14857. [v : (Vector Integer Integer)])
  14858. : (Vector Integer Integer)
  14859. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14860. (define (add1 x) (+ x 1))
  14861. (define (true) #t)
  14862. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  14863. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  14864. \end{lstlisting}
  14865. \caption{A variant of the \code{map-vec} example with an error.}
  14866. \label{fig:map-vec-maybe-add1}
  14867. \end{figure}
  14868. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  14869. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  14870. inserted every time the type checker sees two types that are
  14871. consistent but not equal. In the \code{add1} function, \code{x} is
  14872. cast to \code{Integer} and the result of the \code{+} is cast to
  14873. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  14874. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  14875. \begin{figure}[btp]
  14876. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14877. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  14878. : (Vector Integer Integer)
  14879. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14880. (define (add1 [x : Any]) : Any
  14881. (cast (+ (cast x Any Integer) 1) Integer Any))
  14882. (define (true) : Any (cast #t Boolean Any))
  14883. (define (maybe-add1 [x : Any]) : Any
  14884. (if (eq? 0 (read)) (add1 x) (true)))
  14885. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  14886. (vector 0 41)) 0)
  14887. \end{lstlisting}
  14888. \caption{Output of type checking \code{map-vec}
  14889. and \code{maybe-add1}.}
  14890. \label{fig:map-vec-cast}
  14891. \end{figure}
  14892. The type checker for \LangGrad{} is defined in
  14893. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  14894. and \ref{fig:type-check-Rgradual-3}.
  14895. \begin{figure}[tbp]
  14896. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14897. (define type-check-gradual_class
  14898. (class type-check-Rwhile_class
  14899. (super-new)
  14900. (inherit operator-types type-predicates)
  14901. (define/override (type-check-exp env)
  14902. (lambda (e)
  14903. (define recur (type-check-exp env))
  14904. (match e
  14905. [(Prim 'vector-length (list e1))
  14906. (define-values (e1^ t) (recur e1))
  14907. (match t
  14908. [`(Vector ,ts ...)
  14909. (values (Prim 'vector-length (list e1^)) 'Integer)]
  14910. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  14911. [(Prim 'vector-ref (list e1 e2))
  14912. (define-values (e1^ t1) (recur e1))
  14913. (define-values (e2^ t2) (recur e2))
  14914. (check-consistent? t2 'Integer e)
  14915. (match t1
  14916. [`(Vector ,ts ...)
  14917. (match e2^
  14918. [(Int i)
  14919. (unless (and (0 . <= . i) (i . < . (length ts)))
  14920. (error 'type-check "invalid index ~a in ~a" i e))
  14921. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  14922. [else (define e1^^ (make-cast e1^ t1 'Any))
  14923. (define e2^^ (make-cast e2^ t2 'Integer))
  14924. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  14925. ['Any
  14926. (define e2^^ (make-cast e2^ t2 'Integer))
  14927. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  14928. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  14929. [(Prim 'vector-set! (list e1 e2 e3) )
  14930. (define-values (e1^ t1) (recur e1))
  14931. (define-values (e2^ t2) (recur e2))
  14932. (define-values (e3^ t3) (recur e3))
  14933. (check-consistent? t2 'Integer e)
  14934. (match t1
  14935. [`(Vector ,ts ...)
  14936. (match e2^
  14937. [(Int i)
  14938. (unless (and (0 . <= . i) (i . < . (length ts)))
  14939. (error 'type-check "invalid index ~a in ~a" i e))
  14940. (check-consistent? (list-ref ts i) t3 e)
  14941. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  14942. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  14943. [else
  14944. (define e1^^ (make-cast e1^ t1 'Any))
  14945. (define e2^^ (make-cast e2^ t2 'Integer))
  14946. (define e3^^ (make-cast e3^ t3 'Any))
  14947. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  14948. ['Any
  14949. (define e2^^ (make-cast e2^ t2 'Integer))
  14950. (define e3^^ (make-cast e3^ t3 'Any))
  14951. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  14952. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  14953. \end{lstlisting}
  14954. \caption{Type checker for the \LangGrad{} language, part 1.}
  14955. \label{fig:type-check-Rgradual-1}
  14956. \end{figure}
  14957. \begin{figure}[tbp]
  14958. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14959. [(Prim 'eq? (list e1 e2))
  14960. (define-values (e1^ t1) (recur e1))
  14961. (define-values (e2^ t2) (recur e2))
  14962. (check-consistent? t1 t2 e)
  14963. (define T (meet t1 t2))
  14964. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  14965. 'Boolean)]
  14966. [(Prim 'not (list e1))
  14967. (define-values (e1^ t1) (recur e1))
  14968. (match t1
  14969. ['Any
  14970. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  14971. (Bool #t) (Bool #f)))]
  14972. [else
  14973. (define-values (t-ret new-es^)
  14974. (type-check-op 'not (list t1) (list e1^) e))
  14975. (values (Prim 'not new-es^) t-ret)])]
  14976. [(Prim 'and (list e1 e2))
  14977. (recur (If e1 e2 (Bool #f)))]
  14978. [(Prim 'or (list e1 e2))
  14979. (define tmp (gensym 'tmp))
  14980. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  14981. [(Prim op es)
  14982. #:when (not (set-member? explicit-prim-ops op))
  14983. (define-values (new-es ts)
  14984. (for/lists (exprs types) ([e es])
  14985. (recur e)))
  14986. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  14987. (values (Prim op new-es^) t-ret)]
  14988. [(If e1 e2 e3)
  14989. (define-values (e1^ T1) (recur e1))
  14990. (define-values (e2^ T2) (recur e2))
  14991. (define-values (e3^ T3) (recur e3))
  14992. (check-consistent? T2 T3 e)
  14993. (match T1
  14994. ['Boolean
  14995. (define Tif (join T2 T3))
  14996. (values (If e1^ (make-cast e2^ T2 Tif)
  14997. (make-cast e3^ T3 Tif)) Tif)]
  14998. ['Any
  14999. (define Tif (meet T2 T3))
  15000. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  15001. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  15002. Tif)]
  15003. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  15004. [(HasType e1 T)
  15005. (define-values (e1^ T1) (recur e1))
  15006. (check-consistent? T1 T)
  15007. (values (make-cast e1^ T1 T) T)]
  15008. [(SetBang x e1)
  15009. (define-values (e1^ T1) (recur e1))
  15010. (define varT (dict-ref env x))
  15011. (check-consistent? T1 varT e)
  15012. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  15013. [(WhileLoop e1 e2)
  15014. (define-values (e1^ T1) (recur e1))
  15015. (check-consistent? T1 'Boolean e)
  15016. (define-values (e2^ T2) ((type-check-exp env) e2))
  15017. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  15018. \end{lstlisting}
  15019. \caption{Type checker for the \LangGrad{} language, part 2.}
  15020. \label{fig:type-check-Rgradual-2}
  15021. \end{figure}
  15022. \begin{figure}[tbp]
  15023. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15024. [(Apply e1 e2s)
  15025. (define-values (e1^ T1) (recur e1))
  15026. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  15027. (match T1
  15028. [`(,T1ps ... -> ,T1rt)
  15029. (for ([T2 T2s] [Tp T1ps])
  15030. (check-consistent? T2 Tp e))
  15031. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  15032. (make-cast e2 src tgt)))
  15033. (values (Apply e1^ e2s^^) T1rt)]
  15034. [`Any
  15035. (define e1^^ (make-cast e1^ 'Any
  15036. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  15037. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  15038. (make-cast e2 src 'Any)))
  15039. (values (Apply e1^^ e2s^^) 'Any)]
  15040. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  15041. [(Lambda params Tr e1)
  15042. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  15043. (match p
  15044. [`[,x : ,T] (values x T)]
  15045. [(? symbol? x) (values x 'Any)])))
  15046. (define-values (e1^ T1)
  15047. ((type-check-exp (append (map cons xs Ts) env)) e1))
  15048. (check-consistent? Tr T1 e)
  15049. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  15050. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  15051. [else ((super type-check-exp env) e)]
  15052. )))
  15053. \end{lstlisting}
  15054. \caption{Type checker for the \LangGrad{} language, part 3.}
  15055. \label{fig:type-check-Rgradual-3}
  15056. \end{figure}
  15057. \begin{figure}[tbp]
  15058. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15059. (define/public (join t1 t2)
  15060. (match* (t1 t2)
  15061. [('Integer 'Integer) 'Integer]
  15062. [('Boolean 'Boolean) 'Boolean]
  15063. [('Void 'Void) 'Void]
  15064. [('Any t2) t2]
  15065. [(t1 'Any) t1]
  15066. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15067. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  15068. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15069. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  15070. -> ,(join rt1 rt2))]))
  15071. (define/public (meet t1 t2)
  15072. (match* (t1 t2)
  15073. [('Integer 'Integer) 'Integer]
  15074. [('Boolean 'Boolean) 'Boolean]
  15075. [('Void 'Void) 'Void]
  15076. [('Any t2) 'Any]
  15077. [(t1 'Any) 'Any]
  15078. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15079. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  15080. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15081. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  15082. -> ,(meet rt1 rt2))]))
  15083. (define/public (make-cast e src tgt)
  15084. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  15085. (define/public (check-consistent? t1 t2 e)
  15086. (unless (consistent? t1 t2)
  15087. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  15088. (define/override (type-check-op op arg-types args e)
  15089. (match (dict-ref (operator-types) op)
  15090. [`(,param-types . ,return-type)
  15091. (for ([at arg-types] [pt param-types])
  15092. (check-consistent? at pt e))
  15093. (values return-type
  15094. (for/list ([e args] [s arg-types] [t param-types])
  15095. (make-cast e s t)))]
  15096. [else (error 'type-check-op "unrecognized ~a" op)]))
  15097. (define explicit-prim-ops
  15098. (set-union
  15099. (type-predicates)
  15100. (set 'procedure-arity 'eq?
  15101. 'vector 'vector-length 'vector-ref 'vector-set!
  15102. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  15103. (define/override (fun-def-type d)
  15104. (match d
  15105. [(Def f params rt info body)
  15106. (define ps
  15107. (for/list ([p params])
  15108. (match p
  15109. [`[,x : ,T] T]
  15110. [(? symbol?) 'Any]
  15111. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  15112. `(,@ps -> ,rt)]
  15113. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  15114. \end{lstlisting}
  15115. \caption{Auxiliary functions for type checking \LangGrad{}.}
  15116. \label{fig:type-check-Rgradual-aux}
  15117. \end{figure}
  15118. \clearpage
  15119. \section{Interpreting \LangCast{}}
  15120. \label{sec:interp-casts}
  15121. The runtime behavior of first-order casts is straightforward, that is,
  15122. casts involving simple types such as \code{Integer} and
  15123. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  15124. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  15125. puts the integer into a tagged value
  15126. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  15127. \code{Integer} is accomplished with the \code{Project} operator, that
  15128. is, by checking the value's tag and either retrieving the underlying
  15129. integer or signaling an error if it the tag is not the one for
  15130. integers (Figure~\ref{fig:apply-project}).
  15131. %
  15132. Things get more interesting for higher-order casts, that is, casts
  15133. involving function or vector types.
  15134. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  15135. Any)} to \code{(Integer -> Integer)}. When a function flows through
  15136. this cast at runtime, we can't know in general whether the function
  15137. will always return an integer.\footnote{Predicting the return value of
  15138. a function is equivalent to the halting problem, which is
  15139. undecidable.} The \LangCast{} interpreter therefore delays the checking
  15140. of the cast until the function is applied. This is accomplished by
  15141. wrapping \code{maybe-add1} in a new function that casts its parameter
  15142. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  15143. casts the return value from \code{Any} to \code{Integer}.
  15144. Turning our attention to casts involving vector types, we consider the
  15145. example in Figure~\ref{fig:map-vec-bang} that defines a
  15146. partially-typed version of \code{map-vec} whose parameter \code{v} has
  15147. type \code{(Vector Any Any)} and that updates \code{v} in place
  15148. instead of returning a new vector. So we name this function
  15149. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  15150. the type checker inserts a cast from \code{(Vector Integer Integer)}
  15151. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  15152. cast between vector types would be a build a new vector whose elements
  15153. are the result of casting each of the original elements to the
  15154. appropriate target type. However, this approach is only valid for
  15155. immutable vectors; and our vectors are mutable. In the example of
  15156. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  15157. the updates inside of \code{map-vec!} would happen to the new vector
  15158. and not the original one.
  15159. \begin{figure}[tbp]
  15160. % gradual_test_11.rkt
  15161. \begin{lstlisting}
  15162. (define (map-vec! [f : (Any -> Any)]
  15163. [v : (Vector Any Any)]) : Void
  15164. (begin
  15165. (vector-set! v 0 (f (vector-ref v 0)))
  15166. (vector-set! v 1 (f (vector-ref v 1)))))
  15167. (define (add1 x) (+ x 1))
  15168. (let ([v (vector 0 41)])
  15169. (begin (map-vec! add1 v) (vector-ref v 1)))
  15170. \end{lstlisting}
  15171. \caption{An example involving casts on vectors.}
  15172. \label{fig:map-vec-bang}
  15173. \end{figure}
  15174. Instead the interpreter needs to create a new kind of value, a
  15175. \emph{vector proxy}, that intercepts every vector operation. On a
  15176. read, the proxy reads from the underlying vector and then applies a
  15177. cast to the resulting value. On a write, the proxy casts the argument
  15178. value and then performs the write to the underlying vector. For the
  15179. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  15180. \code{0} from \code{Integer} to \code{Any}. For the first
  15181. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  15182. to \code{Integer}.
  15183. The final category of cast that we need to consider are casts between
  15184. the \code{Any} type and either a function or a vector
  15185. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  15186. in which parameter \code{v} does not have a type annotation, so it is
  15187. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  15188. type \code{(Vector Integer Integer)} so the type checker inserts a
  15189. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  15190. thought is to use \code{Inject}, but that doesn't work because
  15191. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  15192. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  15193. to \code{Any}.
  15194. \begin{figure}[tbp]
  15195. \begin{lstlisting}
  15196. (define (map-vec! [f : (Any -> Any)] v) : Void
  15197. (begin
  15198. (vector-set! v 0 (f (vector-ref v 0)))
  15199. (vector-set! v 1 (f (vector-ref v 1)))))
  15200. (define (add1 x) (+ x 1))
  15201. (let ([v (vector 0 41)])
  15202. (begin (map-vec! add1 v) (vector-ref v 1)))
  15203. \end{lstlisting}
  15204. \caption{Casting a vector to \code{Any}.}
  15205. \label{fig:map-vec-any}
  15206. \end{figure}
  15207. The \LangCast{} interpreter uses an auxiliary function named
  15208. \code{apply-cast} to cast a value from a source type to a target type,
  15209. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  15210. of the kinds of casts that we've discussed in this section.
  15211. \begin{figure}[tbp]
  15212. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15213. (define/public (apply-cast v s t)
  15214. (match* (s t)
  15215. [(t1 t2) #:when (equal? t1 t2) v]
  15216. [('Any t2)
  15217. (match t2
  15218. [`(,ts ... -> ,rt)
  15219. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  15220. (define v^ (apply-project v any->any))
  15221. (apply-cast v^ any->any `(,@ts -> ,rt))]
  15222. [`(Vector ,ts ...)
  15223. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  15224. (define v^ (apply-project v vec-any))
  15225. (apply-cast v^ vec-any `(Vector ,@ts))]
  15226. [else (apply-project v t2)])]
  15227. [(t1 'Any)
  15228. (match t1
  15229. [`(,ts ... -> ,rt)
  15230. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  15231. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  15232. (apply-inject v^ (any-tag any->any))]
  15233. [`(Vector ,ts ...)
  15234. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  15235. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  15236. (apply-inject v^ (any-tag vec-any))]
  15237. [else (apply-inject v (any-tag t1))])]
  15238. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15239. (define x (gensym 'x))
  15240. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  15241. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  15242. (define cast-writes
  15243. (for/list ([t1 ts1] [t2 ts2])
  15244. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  15245. `(vector-proxy ,(vector v (apply vector cast-reads)
  15246. (apply vector cast-writes)))]
  15247. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15248. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  15249. `(function ,xs ,(Cast
  15250. (Apply (Value v)
  15251. (for/list ([x xs][t1 ts1][t2 ts2])
  15252. (Cast (Var x) t2 t1)))
  15253. rt1 rt2) ())]
  15254. ))
  15255. \end{lstlisting}
  15256. \caption{The \code{apply-cast} auxiliary method.}
  15257. \label{fig:apply-cast}
  15258. \end{figure}
  15259. The interpreter for \LangCast{} is defined in
  15260. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  15261. dispatching to \code{apply-cast}. To handle the addition of vector
  15262. proxies, we update the vector primitives in \code{interp-op} using the
  15263. functions in Figure~\ref{fig:guarded-vector}.
  15264. \begin{figure}[tbp]
  15265. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15266. (define interp-Rcast_class
  15267. (class interp-Rwhile_class
  15268. (super-new)
  15269. (inherit apply-fun apply-inject apply-project)
  15270. (define/override (interp-op op)
  15271. (match op
  15272. ['vector-length guarded-vector-length]
  15273. ['vector-ref guarded-vector-ref]
  15274. ['vector-set! guarded-vector-set!]
  15275. ['any-vector-ref (lambda (v i)
  15276. (match v [`(tagged ,v^ ,tg)
  15277. (guarded-vector-ref v^ i)]))]
  15278. ['any-vector-set! (lambda (v i a)
  15279. (match v [`(tagged ,v^ ,tg)
  15280. (guarded-vector-set! v^ i a)]))]
  15281. ['any-vector-length (lambda (v)
  15282. (match v [`(tagged ,v^ ,tg)
  15283. (guarded-vector-length v^)]))]
  15284. [else (super interp-op op)]
  15285. ))
  15286. (define/override ((interp-exp env) e)
  15287. (define (recur e) ((interp-exp env) e))
  15288. (match e
  15289. [(Value v) v]
  15290. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  15291. [else ((super interp-exp env) e)]))
  15292. ))
  15293. (define (interp-Rcast p)
  15294. (send (new interp-Rcast_class) interp-program p))
  15295. \end{lstlisting}
  15296. \caption{The interpreter for \LangCast{}.}
  15297. \label{fig:interp-Rcast}
  15298. \end{figure}
  15299. \begin{figure}[tbp]
  15300. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15301. (define (guarded-vector-ref vec i)
  15302. (match vec
  15303. [`(vector-proxy ,proxy)
  15304. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  15305. (define rd (vector-ref (vector-ref proxy 1) i))
  15306. (apply-fun rd (list val) 'guarded-vector-ref)]
  15307. [else (vector-ref vec i)]))
  15308. (define (guarded-vector-set! vec i arg)
  15309. (match vec
  15310. [`(vector-proxy ,proxy)
  15311. (define wr (vector-ref (vector-ref proxy 2) i))
  15312. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  15313. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  15314. [else (vector-set! vec i arg)]))
  15315. (define (guarded-vector-length vec)
  15316. (match vec
  15317. [`(vector-proxy ,proxy)
  15318. (guarded-vector-length (vector-ref proxy 0))]
  15319. [else (vector-length vec)]))
  15320. \end{lstlisting}
  15321. \caption{The guarded-vector auxiliary functions.}
  15322. \label{fig:guarded-vector}
  15323. \end{figure}
  15324. \section{Lower Casts}
  15325. \label{sec:lower-casts}
  15326. The next step in the journey towards x86 is the \code{lower-casts}
  15327. pass that translates the casts in \LangCast{} to the lower-level
  15328. \code{Inject} and \code{Project} operators and a new operator for
  15329. creating vector proxies, extending the \LangLoop{} language to create
  15330. \LangProxy{}. We recommend creating an auxiliary function named
  15331. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  15332. and a target type, and translates it to expression in \LangProxy{} that has
  15333. the same behavior as casting the expression from the source to the
  15334. target type in the interpreter.
  15335. The \code{lower-cast} function can follow a code structure similar to
  15336. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  15337. the interpreter for \LangCast{} because it must handle the same cases as
  15338. \code{apply-cast} and it needs to mimic the behavior of
  15339. \code{apply-cast}. The most interesting cases are those concerning the
  15340. casts between two vector types and between two function types.
  15341. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  15342. type to another vector type is accomplished by creating a proxy that
  15343. intercepts the operations on the underlying vector. Here we make the
  15344. creation of the proxy explicit with the \code{vector-proxy} primitive
  15345. operation. It takes three arguments, the first is an expression for
  15346. the vector, the second is a vector of functions for casting an element
  15347. that is being read from the vector, and the third is a vector of
  15348. functions for casting an element that is being written to the vector.
  15349. You can create the functions using \code{Lambda}. Also, as we shall
  15350. see in the next section, we need to differentiate these vectors from
  15351. the user-created ones, so we recommend using a new primitive operator
  15352. named \code{raw-vector} instead of \code{vector} to create these
  15353. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  15354. the output of \code{lower-casts} on the example in
  15355. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  15356. integers to a vector of \code{Any}.
  15357. \begin{figure}[tbp]
  15358. \begin{lstlisting}
  15359. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  15360. (begin
  15361. (vector-set! v 0 (f (vector-ref v 0)))
  15362. (vector-set! v 1 (f (vector-ref v 1)))))
  15363. (define (add1 [x : Any]) : Any
  15364. (inject (+ (project x Integer) 1) Integer))
  15365. (let ([v (vector 0 41)])
  15366. (begin
  15367. (map-vec! add1 (vector-proxy v
  15368. (raw-vector (lambda: ([x9 : Integer]) : Any
  15369. (inject x9 Integer))
  15370. (lambda: ([x9 : Integer]) : Any
  15371. (inject x9 Integer)))
  15372. (raw-vector (lambda: ([x9 : Any]) : Integer
  15373. (project x9 Integer))
  15374. (lambda: ([x9 : Any]) : Integer
  15375. (project x9 Integer)))))
  15376. (vector-ref v 1)))
  15377. \end{lstlisting}
  15378. \caption{Output of \code{lower-casts} on the example in
  15379. Figure~\ref{fig:map-vec-bang}.}
  15380. \label{fig:map-vec-bang-lower-cast}
  15381. \end{figure}
  15382. A cast from one function type to another function type is accomplished
  15383. by generating a \code{Lambda} whose parameter and return types match
  15384. the target function type. The body of the \code{Lambda} should cast
  15385. the parameters from the target type to the source type (yes,
  15386. backwards! functions are contravariant\index{subject}{contravariant} in the
  15387. parameters), then call the underlying function, and finally cast the
  15388. result from the source return type to the target return type.
  15389. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  15390. \code{lower-casts} pass on the \code{map-vec} example in
  15391. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  15392. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  15393. \begin{figure}[tbp]
  15394. \begin{lstlisting}
  15395. (define (map-vec [f : (Integer -> Integer)]
  15396. [v : (Vector Integer Integer)])
  15397. : (Vector Integer Integer)
  15398. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15399. (define (add1 [x : Any]) : Any
  15400. (inject (+ (project x Integer) 1) Integer))
  15401. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  15402. (project (add1 (inject x9 Integer)) Integer))
  15403. (vector 0 41)) 1)
  15404. \end{lstlisting}
  15405. \caption{Output of \code{lower-casts} on the example in
  15406. Figure~\ref{fig:gradual-map-vec}.}
  15407. \label{fig:map-vec-lower-cast}
  15408. \end{figure}
  15409. \section{Differentiate Proxies}
  15410. \label{sec:differentiate-proxies}
  15411. So far the job of differentiating vectors and vector proxies has been
  15412. the job of the interpreter. For example, the interpreter for \LangCast{}
  15413. implements \code{vector-ref} using the \code{guarded-vector-ref}
  15414. function in Figure~\ref{fig:guarded-vector}. In the
  15415. \code{differentiate-proxies} pass we shift this responsibility to the
  15416. generated code.
  15417. We begin by designing the output language $R^p_8$. In
  15418. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  15419. proxies. In $R^p_8$ we return the \code{Vector} type to
  15420. its original meaning, as the type of real vectors, and we introduce a
  15421. new type, \code{PVector}, whose values can be either real vectors or
  15422. vector proxies. This new type comes with a suite of new primitive
  15423. operations for creating and using values of type \code{PVector}. We
  15424. don't need to introduce a new type to represent vector proxies. A
  15425. proxy is represented by a vector containing three things: 1) the
  15426. underlying vector, 2) a vector of functions for casting elements that
  15427. are read from the vector, and 3) a vector of functions for casting
  15428. values to be written to the vector. So we define the following
  15429. abbreviation for the type of a vector proxy:
  15430. \[
  15431. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  15432. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  15433. \to (\key{PVector}~ T' \ldots)
  15434. \]
  15435. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  15436. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  15437. %
  15438. Next we describe each of the new primitive operations.
  15439. \begin{description}
  15440. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  15441. (\key{PVector} $T \ldots$)]\ \\
  15442. %
  15443. This operation brands a vector as a value of the \code{PVector} type.
  15444. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  15445. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  15446. %
  15447. This operation brands a vector proxy as value of the \code{PVector} type.
  15448. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  15449. \code{Boolean}] \ \\
  15450. %
  15451. returns true if the value is a vector proxy and false if it is a
  15452. real vector.
  15453. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  15454. (\key{Vector} $T \ldots$)]\ \\
  15455. %
  15456. Assuming that the input is a vector (and not a proxy), this
  15457. operation returns the vector.
  15458. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  15459. $\to$ \code{Boolean}]\ \\
  15460. %
  15461. Given a vector proxy, this operation returns the length of the
  15462. underlying vector.
  15463. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  15464. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  15465. %
  15466. Given a vector proxy, this operation returns the $i$th element of
  15467. the underlying vector.
  15468. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  15469. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  15470. proxy, this operation writes a value to the $i$th element of the
  15471. underlying vector.
  15472. \end{description}
  15473. Now to discuss the translation that differentiates vectors from
  15474. proxies. First, every type annotation in the program must be
  15475. translated (recursively) to replace \code{Vector} with \code{PVector}.
  15476. Next, we must insert uses of \code{PVector} operations in the
  15477. appropriate places. For example, we wrap every vector creation with an
  15478. \code{inject-vector}.
  15479. \begin{lstlisting}
  15480. (vector |$e_1 \ldots e_n$|)
  15481. |$\Rightarrow$|
  15482. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  15483. \end{lstlisting}
  15484. The \code{raw-vector} operator that we introduced in the previous
  15485. section does not get injected.
  15486. \begin{lstlisting}
  15487. (raw-vector |$e_1 \ldots e_n$|)
  15488. |$\Rightarrow$|
  15489. (vector |$e'_1 \ldots e'_n$|)
  15490. \end{lstlisting}
  15491. The \code{vector-proxy} primitive translates as follows.
  15492. \begin{lstlisting}
  15493. (vector-proxy |$e_1~e_2~e_3$|)
  15494. |$\Rightarrow$|
  15495. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  15496. \end{lstlisting}
  15497. We translate the vector operations into conditional expressions that
  15498. check whether the value is a proxy and then dispatch to either the
  15499. appropriate proxy vector operation or the regular vector operation.
  15500. For example, the following is the translation for \code{vector-ref}.
  15501. \begin{lstlisting}
  15502. (vector-ref |$e_1$| |$i$|)
  15503. |$\Rightarrow$|
  15504. (let ([|$v~e_1$|])
  15505. (if (proxy? |$v$|)
  15506. (proxy-vector-ref |$v$| |$i$|)
  15507. (vector-ref (project-vector |$v$|) |$i$|)
  15508. \end{lstlisting}
  15509. Note in the case of a real vector, we must apply \code{project-vector}
  15510. before the \code{vector-ref}.
  15511. \section{Reveal Casts}
  15512. \label{sec:reveal-casts-gradual}
  15513. Recall that the \code{reveal-casts} pass
  15514. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  15515. \code{Inject} and \code{Project} into lower-level operations. In
  15516. particular, \code{Project} turns into a conditional expression that
  15517. inspects the tag and retrieves the underlying value. Here we need to
  15518. augment the translation of \code{Project} to handle the situation when
  15519. the target type is \code{PVector}. Instead of using
  15520. \code{vector-length} we need to use \code{proxy-vector-length}.
  15521. \begin{lstlisting}
  15522. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  15523. |$\Rightarrow$|
  15524. (let |$\itm{tmp}$| |$e'$|
  15525. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  15526. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  15527. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  15528. (exit)))
  15529. \end{lstlisting}
  15530. \section{Closure Conversion}
  15531. \label{sec:closure-conversion-gradual}
  15532. The closure conversion pass only requires one minor adjustment. The
  15533. auxiliary function that translates type annotations needs to be
  15534. updated to handle the \code{PVector} type.
  15535. \section{Explicate Control}
  15536. \label{sec:explicate-control-gradual}
  15537. Update the \code{explicate\_control} pass to handle the new primitive
  15538. operations on the \code{PVector} type.
  15539. \section{Select Instructions}
  15540. \label{sec:select-instructions-gradual}
  15541. Recall that the \code{select\_instructions} pass is responsible for
  15542. lowering the primitive operations into x86 instructions. So we need
  15543. to translate the new \code{PVector} operations to x86. To do so, the
  15544. first question we need to answer is how will we differentiate the two
  15545. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  15546. We need just one bit to accomplish this, and use the bit in position
  15547. $57$ of the 64-bit tag at the front of every vector (see
  15548. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  15549. for \code{inject-vector} we leave it that way.
  15550. \begin{lstlisting}
  15551. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  15552. |$\Rightarrow$|
  15553. movq |$e'_1$|, |$\itm{lhs'}$|
  15554. \end{lstlisting}
  15555. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  15556. \begin{lstlisting}
  15557. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  15558. |$\Rightarrow$|
  15559. movq |$e'_1$|, %r11
  15560. movq |$(1 << 57)$|, %rax
  15561. orq 0(%r11), %rax
  15562. movq %rax, 0(%r11)
  15563. movq %r11, |$\itm{lhs'}$|
  15564. \end{lstlisting}
  15565. The \code{proxy?} operation consumes the information so carefully
  15566. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  15567. isolates the $57$th bit to tell whether the value is a real vector or
  15568. a proxy.
  15569. \begin{lstlisting}
  15570. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  15571. |$\Rightarrow$|
  15572. movq |$e_1'$|, %r11
  15573. movq 0(%r11), %rax
  15574. sarq $57, %rax
  15575. andq $1, %rax
  15576. movq %rax, |$\itm{lhs'}$|
  15577. \end{lstlisting}
  15578. The \code{project-vector} operation is straightforward to translate,
  15579. so we leave it up to the reader.
  15580. Regarding the \code{proxy-vector} operations, the runtime provides
  15581. procedures that implement them (they are recursive functions!) so
  15582. here we simply need to translate these vector operations into the
  15583. appropriate function call. For example, here is the translation for
  15584. \code{proxy-vector-ref}.
  15585. \begin{lstlisting}
  15586. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  15587. |$\Rightarrow$|
  15588. movq |$e_1'$|, %rdi
  15589. movq |$e_2'$|, %rsi
  15590. callq proxy_vector_ref
  15591. movq %rax, |$\itm{lhs'}$|
  15592. \end{lstlisting}
  15593. We have another batch of vector operations to deal with, those for the
  15594. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  15595. \code{any-vector-ref} when there is a \code{vector-ref} on something
  15596. of type \code{Any}, and similarly for \code{any-vector-set!} and
  15597. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  15598. Section~\ref{sec:select-Rany} we selected instructions for these
  15599. operations based on the idea that the underlying value was a real
  15600. vector. But in the current setting, the underlying value is of type
  15601. \code{PVector}. So \code{any-vector-ref} can be translates to
  15602. pseudo-x86 as follows. We begin by projecting the underlying value out
  15603. of the tagged value and then call the \code{proxy\_vector\_ref}
  15604. procedure in the runtime.
  15605. \begin{lstlisting}
  15606. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  15607. movq |$\neg 111$|, %rdi
  15608. andq |$e_1'$|, %rdi
  15609. movq |$e_2'$|, %rsi
  15610. callq proxy_vector_ref
  15611. movq %rax, |$\itm{lhs'}$|
  15612. \end{lstlisting}
  15613. The \code{any-vector-set!} and \code{any-vector-length} operators can
  15614. be translated in a similar way.
  15615. \begin{exercise}\normalfont
  15616. Implement a compiler for the gradually-typed \LangGrad{} language by
  15617. extending and adapting your compiler for \LangLoop{}. Create 10 new
  15618. partially-typed test programs. In addition to testing with these
  15619. new programs, also test your compiler on all the tests for \LangLoop{}
  15620. and tests for \LangDyn{}. Sometimes you may get a type checking error
  15621. on the \LangDyn{} programs but you can adapt them by inserting
  15622. a cast to the \code{Any} type around each subexpression
  15623. causing a type error. While \LangDyn{} doesn't have explicit casts,
  15624. you can induce one by wrapping the subexpression \code{e}
  15625. with a call to an un-annotated identity function, like this:
  15626. \code{((lambda (x) x) e)}.
  15627. \end{exercise}
  15628. \begin{figure}[p]
  15629. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15630. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  15631. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  15632. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  15633. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  15634. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  15635. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  15636. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  15637. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  15638. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  15639. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  15640. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  15641. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  15642. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  15643. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  15644. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15645. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15646. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15647. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15648. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15649. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15650. \path[->,bend right=15] (Rgradual) edge [above] node
  15651. {\ttfamily\footnotesize type\_check} (Rgradualp);
  15652. \path[->,bend right=15] (Rgradualp) edge [above] node
  15653. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  15654. \path[->,bend right=15] (Rwhilepp) edge [right] node
  15655. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  15656. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  15657. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  15658. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  15659. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  15660. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  15661. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  15662. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  15663. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  15664. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  15665. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15666. \path[->,bend left=15] (F1-1) edge [below] node
  15667. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15668. \path[->,bend right=15] (F1-2) edge [above] node
  15669. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15670. \path[->,bend right=15] (F1-3) edge [above] node
  15671. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15672. \path[->,bend right=15] (F1-4) edge [above] node
  15673. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15674. \path[->,bend right=15] (F1-5) edge [right] node
  15675. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15676. \path[->,bend left=15] (C3-2) edge [left] node
  15677. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15678. \path[->,bend right=15] (x86-2) edge [left] node
  15679. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15680. \path[->,bend right=15] (x86-2-1) edge [below] node
  15681. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15682. \path[->,bend right=15] (x86-2-2) edge [left] node
  15683. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15684. \path[->,bend left=15] (x86-3) edge [above] node
  15685. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15686. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  15687. \end{tikzpicture}
  15688. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  15689. \label{fig:Rgradual-passes}
  15690. \end{figure}
  15691. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  15692. for the compilation of \LangGrad{}.
  15693. \section{Further Reading}
  15694. This chapter just scratches the surface of gradual typing. The basic
  15695. approach described here is missing two key ingredients that one would
  15696. want in a implementation of gradual typing: blame
  15697. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  15698. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  15699. problem addressed by blame tracking is that when a cast on a
  15700. higher-order value fails, it often does so at a point in the program
  15701. that is far removed from the original cast. Blame tracking is a
  15702. technique for propagating extra information through casts and proxies
  15703. so that when a cast fails, the error message can point back to the
  15704. original location of the cast in the source program.
  15705. The problem addressed by space-efficient casts also relates to
  15706. higher-order casts. It turns out that in partially typed programs, a
  15707. function or vector can flow through very-many casts at runtime. With
  15708. the approach described in this chapter, each cast adds another
  15709. \code{lambda} wrapper or a vector proxy. Not only does this take up
  15710. considerable space, but it also makes the function calls and vector
  15711. operations slow. For example, a partially-typed version of quicksort
  15712. could, in the worst case, build a chain of proxies of length $O(n)$
  15713. around the vector, changing the overall time complexity of the
  15714. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  15715. solution to this problem by representing casts using the coercion
  15716. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  15717. long chains of proxies by compressing them into a concise normal
  15718. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  15719. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  15720. the Grift compiler.
  15721. \begin{center}
  15722. \url{https://github.com/Gradual-Typing/Grift}
  15723. \end{center}
  15724. There are also interesting interactions between gradual typing and
  15725. other language features, such as parametetric polymorphism,
  15726. information-flow types, and type inference, to name a few. We
  15727. recommend the reader to the online gradual typing bibliography:
  15728. \begin{center}
  15729. \url{http://samth.github.io/gradual-typing-bib/}
  15730. \end{center}
  15731. % TODO: challenge problem:
  15732. % type analysis and type specialization?
  15733. % coercions?
  15734. \fi
  15735. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15736. \chapter{Parametric Polymorphism}
  15737. \label{ch:Rpoly}
  15738. \index{subject}{parametric polymorphism}
  15739. \index{subject}{generics}
  15740. \if\edition\racketEd
  15741. This chapter studies the compilation of parametric
  15742. polymorphism\index{subject}{parametric polymorphism}
  15743. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  15744. Racket. Parametric polymorphism enables improved code reuse by
  15745. parameterizing functions and data structures with respect to the types
  15746. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  15747. revisits the \code{map-vec} example but this time gives it a more
  15748. fitting type. This \code{map-vec} function is parameterized with
  15749. respect to the element type of the vector. The type of \code{map-vec}
  15750. is the following polymorphic type as specified by the \code{All} and
  15751. the type parameter \code{a}.
  15752. \begin{lstlisting}
  15753. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  15754. \end{lstlisting}
  15755. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  15756. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  15757. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  15758. \code{a}, but we could have just as well applied \code{map-vec} to a
  15759. vector of Booleans (and a function on Booleans).
  15760. \begin{figure}[tbp]
  15761. % poly_test_2.rkt
  15762. \begin{lstlisting}
  15763. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  15764. (define (map-vec f v)
  15765. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15766. (define (add1 [x : Integer]) : Integer (+ x 1))
  15767. (vector-ref (map-vec add1 (vector 0 41)) 1)
  15768. \end{lstlisting}
  15769. \caption{The \code{map-vec} example using parametric polymorphism.}
  15770. \label{fig:map-vec-poly}
  15771. \end{figure}
  15772. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  15773. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  15774. syntax. We add a second form for function definitions in which a type
  15775. declaration comes before the \code{define}. In the abstract syntax,
  15776. the return type in the \code{Def} is \code{Any}, but that should be
  15777. ignored in favor of the return type in the type declaration. (The
  15778. \code{Any} comes from using the same parser as in
  15779. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  15780. enables the use of an \code{All} type for a function, thereby making
  15781. it polymorphic. The grammar for types is extended to include
  15782. polymorphic types and type variables.
  15783. \begin{figure}[tp]
  15784. \centering
  15785. \fbox{
  15786. \begin{minipage}{0.96\textwidth}
  15787. \small
  15788. \[
  15789. \begin{array}{lcl}
  15790. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15791. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  15792. &\MID& \LP\key{:}~\Var~\Type\RP \\
  15793. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  15794. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  15795. \end{array}
  15796. \]
  15797. \end{minipage}
  15798. }
  15799. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  15800. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  15801. \label{fig:Rpoly-concrete-syntax}
  15802. \end{figure}
  15803. \begin{figure}[tp]
  15804. \centering
  15805. \fbox{
  15806. \begin{minipage}{0.96\textwidth}
  15807. \small
  15808. \[
  15809. \begin{array}{lcl}
  15810. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15811. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  15812. &\MID& \DECL{\Var}{\Type} \\
  15813. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  15814. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15815. \end{array}
  15816. \]
  15817. \end{minipage}
  15818. }
  15819. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  15820. (Figure~\ref{fig:Lwhile-syntax}).}
  15821. \label{fig:Rpoly-syntax}
  15822. \end{figure}
  15823. By including polymorphic types in the $\Type$ non-terminal we choose
  15824. to make them first-class which has interesting repercussions on the
  15825. compiler. Many languages with polymorphism, such as
  15826. C++~\citep{stroustrup88:_param_types} and Standard
  15827. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  15828. it is useful to see an example of first-class polymorphism. In
  15829. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  15830. whose parameter is a polymorphic function. The occurrence of a
  15831. polymorphic type underneath a function type is enabled by the normal
  15832. recursive structure of the grammar for $\Type$ and the categorization
  15833. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  15834. applies the polymorphic function to a Boolean and to an integer.
  15835. \begin{figure}[tbp]
  15836. \begin{lstlisting}
  15837. (: apply-twice ((All (b) (b -> b)) -> Integer))
  15838. (define (apply-twice f)
  15839. (if (f #t) (f 42) (f 777)))
  15840. (: id (All (a) (a -> a)))
  15841. (define (id x) x)
  15842. (apply-twice id)
  15843. \end{lstlisting}
  15844. \caption{An example illustrating first-class polymorphism.}
  15845. \label{fig:apply-twice}
  15846. \end{figure}
  15847. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  15848. three new responsibilities (compared to \LangLoop{}). The type checking of
  15849. function application is extended to handle the case where the operator
  15850. expression is a polymorphic function. In that case the type arguments
  15851. are deduced by matching the type of the parameters with the types of
  15852. the arguments.
  15853. %
  15854. The \code{match-types} auxiliary function carries out this deduction
  15855. by recursively descending through a parameter type \code{pt} and the
  15856. corresponding argument type \code{at}, making sure that they are equal
  15857. except when there is a type parameter on the left (in the parameter
  15858. type). If it's the first time that the type parameter has been
  15859. encountered, then the algorithm deduces an association of the type
  15860. parameter to the corresponding type on the right (in the argument
  15861. type). If it's not the first time that the type parameter has been
  15862. encountered, the algorithm looks up its deduced type and makes sure
  15863. that it is equal to the type on the right.
  15864. %
  15865. Once the type arguments are deduced, the operator expression is
  15866. wrapped in an \code{Inst} AST node (for instantiate) that records the
  15867. type of the operator, but more importantly, records the deduced type
  15868. arguments. The return type of the application is the return type of
  15869. the polymorphic function, but with the type parameters replaced by the
  15870. deduced type arguments, using the \code{subst-type} function.
  15871. The second responsibility of the type checker is extending the
  15872. function \code{type-equal?} to handle the \code{All} type. This is
  15873. not quite a simple as equal on other types, such as function and
  15874. vector types, because two polymorphic types can be syntactically
  15875. different even though they are equivalent types. For example,
  15876. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  15877. Two polymorphic types should be considered equal if they differ only
  15878. in the choice of the names of the type parameters. The
  15879. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  15880. renames the type parameters of the first type to match the type
  15881. parameters of the second type.
  15882. The third responsibility of the type checker is making sure that only
  15883. defined type variables appear in type annotations. The
  15884. \code{check-well-formed} function defined in
  15885. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  15886. sure that each type variable has been defined.
  15887. The output language of the type checker is \LangInst{}, defined in
  15888. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  15889. declaration and polymorphic function into a single definition, using
  15890. the \code{Poly} form, to make polymorphic functions more convenient to
  15891. process in next pass of the compiler.
  15892. \begin{figure}[tp]
  15893. \centering
  15894. \fbox{
  15895. \begin{minipage}{0.96\textwidth}
  15896. \small
  15897. \[
  15898. \begin{array}{lcl}
  15899. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15900. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  15901. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  15902. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  15903. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15904. \end{array}
  15905. \]
  15906. \end{minipage}
  15907. }
  15908. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  15909. (Figure~\ref{fig:Lwhile-syntax}).}
  15910. \label{fig:Rpoly-prime-syntax}
  15911. \end{figure}
  15912. The output of the type checker on the polymorphic \code{map-vec}
  15913. example is listed in Figure~\ref{fig:map-vec-type-check}.
  15914. \begin{figure}[tbp]
  15915. % poly_test_2.rkt
  15916. \begin{lstlisting}
  15917. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  15918. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  15919. (define (add1 [x : Integer]) : Integer (+ x 1))
  15920. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  15921. (Integer))
  15922. add1 (vector 0 41)) 1)
  15923. \end{lstlisting}
  15924. \caption{Output of the type checker on the \code{map-vec} example.}
  15925. \label{fig:map-vec-type-check}
  15926. \end{figure}
  15927. \begin{figure}[tbp]
  15928. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15929. (define type-check-poly-class
  15930. (class type-check-Rwhile-class
  15931. (super-new)
  15932. (inherit check-type-equal?)
  15933. (define/override (type-check-apply env e1 es)
  15934. (define-values (e^ ty) ((type-check-exp env) e1))
  15935. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  15936. ((type-check-exp env) e)))
  15937. (match ty
  15938. [`(,ty^* ... -> ,rt)
  15939. (for ([arg-ty ty*] [param-ty ty^*])
  15940. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  15941. (values e^ es^ rt)]
  15942. [`(All ,xs (,tys ... -> ,rt))
  15943. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  15944. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  15945. (match-types env^^ param-ty arg-ty)))
  15946. (define targs
  15947. (for/list ([x xs])
  15948. (match (dict-ref env^^ x (lambda () #f))
  15949. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  15950. x (Apply e1 es))]
  15951. [ty ty])))
  15952. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  15953. [else (error 'type-check "expected a function, not ~a" ty)]))
  15954. (define/override ((type-check-exp env) e)
  15955. (match e
  15956. [(Lambda `([,xs : ,Ts] ...) rT body)
  15957. (for ([T Ts]) ((check-well-formed env) T))
  15958. ((check-well-formed env) rT)
  15959. ((super type-check-exp env) e)]
  15960. [(HasType e1 ty)
  15961. ((check-well-formed env) ty)
  15962. ((super type-check-exp env) e)]
  15963. [else ((super type-check-exp env) e)]))
  15964. (define/override ((type-check-def env) d)
  15965. (verbose 'type-check "poly/def" d)
  15966. (match d
  15967. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  15968. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  15969. (for ([p ps]) ((check-well-formed ts-env) p))
  15970. ((check-well-formed ts-env) rt)
  15971. (define new-env (append ts-env (map cons xs ps) env))
  15972. (define-values (body^ ty^) ((type-check-exp new-env) body))
  15973. (check-type-equal? ty^ rt body)
  15974. (Generic ts (Def f p:t* rt info body^))]
  15975. [else ((super type-check-def env) d)]))
  15976. (define/override (type-check-program p)
  15977. (match p
  15978. [(Program info body)
  15979. (type-check-program (ProgramDefsExp info '() body))]
  15980. [(ProgramDefsExp info ds body)
  15981. (define ds^ (combine-decls-defs ds))
  15982. (define new-env (for/list ([d ds^])
  15983. (cons (def-name d) (fun-def-type d))))
  15984. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  15985. (define-values (body^ ty) ((type-check-exp new-env) body))
  15986. (check-type-equal? ty 'Integer body)
  15987. (ProgramDefsExp info ds^^ body^)]))
  15988. ))
  15989. \end{lstlisting}
  15990. \caption{Type checker for the \LangPoly{} language.}
  15991. \label{fig:type-check-Lvar0}
  15992. \end{figure}
  15993. \begin{figure}[tbp]
  15994. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15995. (define/override (type-equal? t1 t2)
  15996. (match* (t1 t2)
  15997. [(`(All ,xs ,T1) `(All ,ys ,T2))
  15998. (define env (map cons xs ys))
  15999. (type-equal? (subst-type env T1) T2)]
  16000. [(other wise)
  16001. (super type-equal? t1 t2)]))
  16002. (define/public (match-types env pt at)
  16003. (match* (pt at)
  16004. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  16005. [('Void 'Void) env] [('Any 'Any) env]
  16006. [(`(Vector ,pts ...) `(Vector ,ats ...))
  16007. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  16008. (match-types env^ pt1 at1))]
  16009. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  16010. (define env^ (match-types env prt art))
  16011. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  16012. (match-types env^^ pt1 at1))]
  16013. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  16014. (define env^ (append (map cons pxs axs) env))
  16015. (match-types env^ pt1 at1)]
  16016. [((? symbol? x) at)
  16017. (match (dict-ref env x (lambda () #f))
  16018. [#f (error 'type-check "undefined type variable ~a" x)]
  16019. ['Type (cons (cons x at) env)]
  16020. [t^ (check-type-equal? at t^ 'matching) env])]
  16021. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  16022. (define/public (subst-type env pt)
  16023. (match pt
  16024. ['Integer 'Integer] ['Boolean 'Boolean]
  16025. ['Void 'Void] ['Any 'Any]
  16026. [`(Vector ,ts ...)
  16027. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  16028. [`(,ts ... -> ,rt)
  16029. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  16030. [`(All ,xs ,t)
  16031. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  16032. [(? symbol? x) (dict-ref env x)]
  16033. [else (error 'type-check "expected a type not ~a" pt)]))
  16034. (define/public (combine-decls-defs ds)
  16035. (match ds
  16036. ['() '()]
  16037. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  16038. (unless (equal? name f)
  16039. (error 'type-check "name mismatch, ~a != ~a" name f))
  16040. (match type
  16041. [`(All ,xs (,ps ... -> ,rt))
  16042. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  16043. (cons (Generic xs (Def name params^ rt info body))
  16044. (combine-decls-defs ds^))]
  16045. [`(,ps ... -> ,rt)
  16046. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  16047. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  16048. [else (error 'type-check "expected a function type, not ~a" type) ])]
  16049. [`(,(Def f params rt info body) . ,ds^)
  16050. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  16051. \end{lstlisting}
  16052. \caption{Auxiliary functions for type checking \LangPoly{}.}
  16053. \label{fig:type-check-Lvar0-aux}
  16054. \end{figure}
  16055. \begin{figure}[tbp]
  16056. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  16057. (define/public ((check-well-formed env) ty)
  16058. (match ty
  16059. ['Integer (void)]
  16060. ['Boolean (void)]
  16061. ['Void (void)]
  16062. [(? symbol? a)
  16063. (match (dict-ref env a (lambda () #f))
  16064. ['Type (void)]
  16065. [else (error 'type-check "undefined type variable ~a" a)])]
  16066. [`(Vector ,ts ...)
  16067. (for ([t ts]) ((check-well-formed env) t))]
  16068. [`(,ts ... -> ,t)
  16069. (for ([t ts]) ((check-well-formed env) t))
  16070. ((check-well-formed env) t)]
  16071. [`(All ,xs ,t)
  16072. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  16073. ((check-well-formed env^) t)]
  16074. [else (error 'type-check "unrecognized type ~a" ty)]))
  16075. \end{lstlisting}
  16076. \caption{Well-formed types.}
  16077. \label{fig:well-formed-types}
  16078. \end{figure}
  16079. % TODO: interpreter for R'_10
  16080. \section{Compiling Polymorphism}
  16081. \label{sec:compiling-poly}
  16082. Broadly speaking, there are four approaches to compiling parametric
  16083. polymorphism, which we describe below.
  16084. \begin{description}
  16085. \item[Monomorphization] generates a different version of a polymorphic
  16086. function for each set of type arguments that it is used with,
  16087. producing type-specialized code. This approach results in the most
  16088. efficient code but requires whole-program compilation (no separate
  16089. compilation) and increases code size. For our current purposes
  16090. monomorphization is a non-starter because, with first-class
  16091. polymorphism, it is sometimes not possible to determine which
  16092. generic functions are used with which type arguments during
  16093. compilation. (It can be done at runtime, with just-in-time
  16094. compilation.) This approach is used to compile C++
  16095. templates~\citep{stroustrup88:_param_types} and polymorphic
  16096. functions in NESL~\citep{Blelloch:1993aa} and
  16097. ML~\citep{Weeks:2006aa}.
  16098. \item[Uniform representation] generates one version of each
  16099. polymorphic function but requires all values have a common ``boxed''
  16100. format, such as the tagged values of type \code{Any} in
  16101. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  16102. similarly to code in a dynamically typed language (like \LangDyn{}),
  16103. in which primitive operators require their arguments to be projected
  16104. from \code{Any} and their results are injected into \code{Any}. (In
  16105. object-oriented languages, the projection is accomplished via
  16106. virtual method dispatch.) The uniform representation approach is
  16107. compatible with separate compilation and with first-class
  16108. polymorphism. However, it produces the least-efficient code because
  16109. it introduces overhead in the entire program, including
  16110. non-polymorphic code. This approach is used in implementations of
  16111. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  16112. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  16113. Java~\citep{Bracha:1998fk}.
  16114. \item[Mixed representation] generates one version of each polymorphic
  16115. function, using a boxed representation for type
  16116. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  16117. and conversions are performed at the boundaries between monomorphic
  16118. and polymorphic (e.g. when a polymorphic function is instantiated
  16119. and called). This approach is compatible with separate compilation
  16120. and first-class polymorphism and maintains the efficiency of
  16121. monomorphic code. The tradeoff is increased overhead at the boundary
  16122. between monomorphic and polymorphic code. This approach is used in
  16123. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  16124. Java 5 with the addition of autoboxing.
  16125. \item[Type passing] uses the unboxed representation in both
  16126. monomorphic and polymorphic code. Each polymorphic function is
  16127. compiled to a single function with extra parameters that describe
  16128. the type arguments. The type information is used by the generated
  16129. code to know how to access the unboxed values at runtime. This
  16130. approach is used in implementation of the Napier88
  16131. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  16132. passing is compatible with separate compilation and first-class
  16133. polymorphism and maintains the efficiency for monomorphic
  16134. code. There is runtime overhead in polymorphic code from dispatching
  16135. on type information.
  16136. \end{description}
  16137. In this chapter we use the mixed representation approach, partly
  16138. because of its favorable attributes, and partly because it is
  16139. straightforward to implement using the tools that we have already
  16140. built to support gradual typing. To compile polymorphic functions, we
  16141. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  16142. \LangCast{}.
  16143. \section{Erase Types}
  16144. \label{sec:erase-types}
  16145. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  16146. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  16147. shows the output of the \code{erase-types} pass on the polymorphic
  16148. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  16149. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  16150. \code{All} types are removed from the type of \code{map-vec}.
  16151. \begin{figure}[tbp]
  16152. \begin{lstlisting}
  16153. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  16154. : (Vector Any Any)
  16155. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16156. (define (add1 [x : Integer]) : Integer (+ x 1))
  16157. (vector-ref ((cast map-vec
  16158. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  16159. ((Integer -> Integer) (Vector Integer Integer)
  16160. -> (Vector Integer Integer)))
  16161. add1 (vector 0 41)) 1)
  16162. \end{lstlisting}
  16163. \caption{The polymorphic \code{map-vec} example after type erasure.}
  16164. \label{fig:map-vec-erase}
  16165. \end{figure}
  16166. This process of type erasure creates a challenge at points of
  16167. instantiation. For example, consider the instantiation of
  16168. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  16169. The type of \code{map-vec} is
  16170. \begin{lstlisting}
  16171. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  16172. \end{lstlisting}
  16173. and it is instantiated to
  16174. \begin{lstlisting}
  16175. ((Integer -> Integer) (Vector Integer Integer)
  16176. -> (Vector Integer Integer))
  16177. \end{lstlisting}
  16178. After erasure, the type of \code{map-vec} is
  16179. \begin{lstlisting}
  16180. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  16181. \end{lstlisting}
  16182. but we need to convert it to the instantiated type. This is easy to
  16183. do in the target language \LangCast{} with a single \code{cast}. In
  16184. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  16185. has been compiled to a \code{cast} from the type of \code{map-vec} to
  16186. the instantiated type. The source and target type of a cast must be
  16187. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  16188. because both the source and target are obtained from the same
  16189. polymorphic type of \code{map-vec}, replacing the type parameters with
  16190. \code{Any} in the former and with the deduced type arguments in the
  16191. later. (Recall that the \code{Any} type is consistent with any type.)
  16192. To implement the \code{erase-types} pass, we recommend defining a
  16193. recursive auxiliary function named \code{erase-type} that applies the
  16194. following two transformations. It replaces type variables with
  16195. \code{Any}
  16196. \begin{lstlisting}
  16197. |$x$|
  16198. |$\Rightarrow$|
  16199. Any
  16200. \end{lstlisting}
  16201. and it removes the polymorphic \code{All} types.
  16202. \begin{lstlisting}
  16203. (All |$xs$| |$T_1$|)
  16204. |$\Rightarrow$|
  16205. |$T'_1$|
  16206. \end{lstlisting}
  16207. Apply the \code{erase-type} function to all of the type annotations in
  16208. the program.
  16209. Regarding the translation of expressions, the case for \code{Inst} is
  16210. the interesting one. We translate it into a \code{Cast}, as shown
  16211. below. The type of the subexpression $e$ is the polymorphic type
  16212. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  16213. $T$, the type $T'$. The target type $T''$ is the result of
  16214. substituting the arguments types $ts$ for the type parameters $xs$ in
  16215. $T$ followed by doing type erasure.
  16216. \begin{lstlisting}
  16217. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  16218. |$\Rightarrow$|
  16219. (Cast |$e'$| |$T'$| |$T''$|)
  16220. \end{lstlisting}
  16221. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  16222. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  16223. Finally, each polymorphic function is translated to a regular
  16224. functions in which type erasure has been applied to all the type
  16225. annotations and the body.
  16226. \begin{lstlisting}
  16227. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  16228. |$\Rightarrow$|
  16229. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  16230. \end{lstlisting}
  16231. \begin{exercise}\normalfont
  16232. Implement a compiler for the polymorphic language \LangPoly{} by
  16233. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  16234. programs that use polymorphic functions. Some of them should make
  16235. use of first-class polymorphism.
  16236. \end{exercise}
  16237. \begin{figure}[p]
  16238. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16239. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  16240. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  16241. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  16242. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  16243. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  16244. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  16245. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  16246. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  16247. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  16248. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  16249. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  16250. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  16251. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  16252. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  16253. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  16254. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16255. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16256. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16257. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16258. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16259. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16260. \path[->,bend right=15] (Rpoly) edge [above] node
  16261. {\ttfamily\footnotesize type\_check} (Rpolyp);
  16262. \path[->,bend right=15] (Rpolyp) edge [above] node
  16263. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  16264. \path[->,bend right=15] (Rgradualp) edge [above] node
  16265. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  16266. \path[->,bend right=15] (Rwhilepp) edge [right] node
  16267. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  16268. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  16269. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  16270. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  16271. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  16272. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  16273. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  16274. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  16275. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  16276. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  16277. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16278. \path[->,bend left=15] (F1-1) edge [below] node
  16279. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16280. \path[->,bend right=15] (F1-2) edge [above] node
  16281. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16282. \path[->,bend right=15] (F1-3) edge [above] node
  16283. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16284. \path[->,bend right=15] (F1-4) edge [above] node
  16285. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16286. \path[->,bend right=15] (F1-5) edge [right] node
  16287. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16288. \path[->,bend left=15] (C3-2) edge [left] node
  16289. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16290. \path[->,bend right=15] (x86-2) edge [left] node
  16291. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16292. \path[->,bend right=15] (x86-2-1) edge [below] node
  16293. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16294. \path[->,bend right=15] (x86-2-2) edge [left] node
  16295. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16296. \path[->,bend left=15] (x86-3) edge [above] node
  16297. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16298. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  16299. \end{tikzpicture}
  16300. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  16301. \label{fig:Rpoly-passes}
  16302. \end{figure}
  16303. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  16304. for the compilation of \LangPoly{}.
  16305. % TODO: challenge problem: specialization of instantiations
  16306. % Further Reading
  16307. \fi
  16308. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16309. \clearpage
  16310. \appendix
  16311. \chapter{Appendix}
  16312. \if\edition\racketEd
  16313. \section{Interpreters}
  16314. \label{appendix:interp}
  16315. \index{subject}{interpreter}
  16316. We provide interpreters for each of the source languages \LangInt{},
  16317. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  16318. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  16319. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  16320. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  16321. and x86 are in the \key{interp.rkt} file.
  16322. \section{Utility Functions}
  16323. \label{appendix:utilities}
  16324. The utility functions described in this section are in the
  16325. \key{utilities.rkt} file of the support code.
  16326. \paragraph{\code{interp-tests}}
  16327. The \key{interp-tests} function runs the compiler passes and the
  16328. interpreters on each of the specified tests to check whether each pass
  16329. is correct. The \key{interp-tests} function has the following
  16330. parameters:
  16331. \begin{description}
  16332. \item[name (a string)] a name to identify the compiler,
  16333. \item[typechecker] a function of exactly one argument that either
  16334. raises an error using the \code{error} function when it encounters a
  16335. type error, or returns \code{\#f} when it encounters a type
  16336. error. If there is no type error, the type checker returns the
  16337. program.
  16338. \item[passes] a list with one entry per pass. An entry is a list with
  16339. four things:
  16340. \begin{enumerate}
  16341. \item a string giving the name of the pass,
  16342. \item the function that implements the pass (a translator from AST
  16343. to AST),
  16344. \item a function that implements the interpreter (a function from
  16345. AST to result value) for the output language,
  16346. \item and a type checker for the output language. Type checkers for
  16347. the $R$ and $C$ languages are provided in the support code. For
  16348. example, the type checkers for \LangVar{} and \LangCVar{} are in
  16349. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  16350. type checker entry is optional. The support code does not provide
  16351. type checkers for the x86 languages.
  16352. \end{enumerate}
  16353. \item[source-interp] an interpreter for the source language. The
  16354. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  16355. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  16356. \item[tests] a list of test numbers that specifies which tests to
  16357. run. (see below)
  16358. \end{description}
  16359. %
  16360. The \key{interp-tests} function assumes that the subdirectory
  16361. \key{tests} has a collection of Racket programs whose names all start
  16362. with the family name, followed by an underscore and then the test
  16363. number, ending with the file extension \key{.rkt}. Also, for each test
  16364. program that calls \code{read} one or more times, there is a file with
  16365. the same name except that the file extension is \key{.in} that
  16366. provides the input for the Racket program. If the test program is
  16367. expected to fail type checking, then there should be an empty file of
  16368. the same name but with extension \key{.tyerr}.
  16369. \paragraph{\code{compiler-tests}}
  16370. runs the compiler passes to generate x86 (a \key{.s} file) and then
  16371. runs the GNU C compiler (gcc) to generate machine code. It runs the
  16372. machine code and checks that the output is $42$. The parameters to the
  16373. \code{compiler-tests} function are similar to those of the
  16374. \code{interp-tests} function, and consist of
  16375. \begin{itemize}
  16376. \item a compiler name (a string),
  16377. \item a type checker,
  16378. \item description of the passes,
  16379. \item name of a test-family, and
  16380. \item a list of test numbers.
  16381. \end{itemize}
  16382. \paragraph{\code{compile-file}}
  16383. takes a description of the compiler passes (see the comment for
  16384. \key{interp-tests}) and returns a function that, given a program file
  16385. name (a string ending in \key{.rkt}), applies all of the passes and
  16386. writes the output to a file whose name is the same as the program file
  16387. name but with \key{.rkt} replaced with \key{.s}.
  16388. \paragraph{\code{read-program}}
  16389. takes a file path and parses that file (it must be a Racket program)
  16390. into an abstract syntax tree.
  16391. \paragraph{\code{parse-program}}
  16392. takes an S-expression representation of an abstract syntax tree and converts it into
  16393. the struct-based representation.
  16394. \paragraph{\code{assert}}
  16395. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  16396. and displays the message \key{msg} if the Boolean \key{bool} is false.
  16397. \paragraph{\code{lookup}}
  16398. % remove discussion of lookup? -Jeremy
  16399. takes a key and an alist, and returns the first value that is
  16400. associated with the given key, if there is one. If not, an error is
  16401. triggered. The alist may contain both immutable pairs (built with
  16402. \key{cons}) and mutable pairs (built with \key{mcons}).
  16403. %The \key{map2} function ...
  16404. \fi %\racketEd
  16405. \section{x86 Instruction Set Quick-Reference}
  16406. \label{sec:x86-quick-reference}
  16407. \index{subject}{x86}
  16408. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  16409. do. We write $A \to B$ to mean that the value of $A$ is written into
  16410. location $B$. Address offsets are given in bytes. The instruction
  16411. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  16412. registers (such as \code{\%rax}), or memory references (such as
  16413. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  16414. reference per instruction. Other operands must be immediates or
  16415. registers.
  16416. \begin{table}[tbp]
  16417. \centering
  16418. \begin{tabular}{l|l}
  16419. \textbf{Instruction} & \textbf{Operation} \\ \hline
  16420. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  16421. \texttt{negq} $A$ & $- A \to A$ \\
  16422. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  16423. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  16424. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  16425. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  16426. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  16427. \texttt{retq} & Pops the return address and jumps to it \\
  16428. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  16429. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  16430. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  16431. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  16432. be an immediate) \\
  16433. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  16434. matches the condition code of the instruction, otherwise go to the
  16435. next instructions. The condition codes are \key{e} for ``equal'',
  16436. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  16437. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  16438. \texttt{jl} $L$ & \\
  16439. \texttt{jle} $L$ & \\
  16440. \texttt{jg} $L$ & \\
  16441. \texttt{jge} $L$ & \\
  16442. \texttt{jmp} $L$ & Jump to label $L$ \\
  16443. \texttt{movq} $A$, $B$ & $A \to B$ \\
  16444. \texttt{movzbq} $A$, $B$ &
  16445. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  16446. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  16447. and the extra bytes of $B$ are set to zero.} \\
  16448. & \\
  16449. & \\
  16450. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  16451. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  16452. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  16453. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  16454. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  16455. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  16456. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  16457. description of the condition codes. $A$ must be a single byte register
  16458. (e.g., \texttt{al} or \texttt{cl}).} \\
  16459. \texttt{setl} $A$ & \\
  16460. \texttt{setle} $A$ & \\
  16461. \texttt{setg} $A$ & \\
  16462. \texttt{setge} $A$ &
  16463. \end{tabular}
  16464. \vspace{5pt}
  16465. \caption{Quick-reference for the x86 instructions used in this book.}
  16466. \label{tab:x86-instr}
  16467. \end{table}
  16468. \if\edition\racketEd
  16469. \cleardoublepage
  16470. \section{Concrete Syntax for Intermediate Languages}
  16471. The concrete syntax of \LangAny{} is defined in
  16472. Figure~\ref{fig:Rany-concrete-syntax}.
  16473. \begin{figure}[tp]
  16474. \centering
  16475. \fbox{
  16476. \begin{minipage}{0.97\textwidth}\small
  16477. \[
  16478. \begin{array}{lcl}
  16479. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  16480. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  16481. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  16482. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16483. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  16484. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  16485. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  16486. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  16487. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  16488. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  16489. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  16490. \MID \LP\key{void?}\;\Exp\RP \\
  16491. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  16492. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  16493. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  16494. \end{array}
  16495. \]
  16496. \end{minipage}
  16497. }
  16498. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  16499. (Figure~\ref{fig:Rlam-syntax}).}
  16500. \label{fig:Rany-concrete-syntax}
  16501. \end{figure}
  16502. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  16503. defined in Figures~\ref{fig:c0-concrete-syntax},
  16504. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  16505. and \ref{fig:c3-concrete-syntax}, respectively.
  16506. \begin{figure}[tbp]
  16507. \fbox{
  16508. \begin{minipage}{0.96\textwidth}
  16509. \small
  16510. \[
  16511. \begin{array}{lcl}
  16512. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  16513. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  16514. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  16515. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  16516. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  16517. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  16518. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  16519. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  16520. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  16521. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  16522. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  16523. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  16524. \end{array}
  16525. \]
  16526. \end{minipage}
  16527. }
  16528. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  16529. \label{fig:c2-concrete-syntax}
  16530. \end{figure}
  16531. \begin{figure}[tp]
  16532. \fbox{
  16533. \begin{minipage}{0.96\textwidth}
  16534. \small
  16535. \[
  16536. \begin{array}{lcl}
  16537. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  16538. \\
  16539. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  16540. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  16541. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  16542. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  16543. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  16544. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  16545. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  16546. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  16547. \MID \LP\key{collect} \,\itm{int}\RP }\\
  16548. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  16549. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  16550. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  16551. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  16552. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  16553. \LangCFunM{} & ::= & \Def\ldots
  16554. \end{array}
  16555. \]
  16556. \end{minipage}
  16557. }
  16558. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  16559. \label{fig:c3-concrete-syntax}
  16560. \end{figure}
  16561. \fi % racketEd
  16562. \backmatter
  16563. \addtocontents{toc}{\vspace{11pt}}
  16564. %% \addtocontents{toc}{\vspace{11pt}}
  16565. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  16566. \nocite{*}\let\bibname\refname
  16567. \addcontentsline{toc}{fmbm}{\refname}
  16568. \printbibliography
  16569. \printindex{authors}{Author Index}
  16570. \printindex{subject}{Subject Index}
  16571. \end{document}
  16572. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  16573. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  16574. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  16575. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  16576. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  16577. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  16578. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  16579. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  16580. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  16581. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  16582. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  16583. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  16584. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  16585. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  16586. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  16587. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  16588. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  16589. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  16590. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  16591. % LocalWords: morekeywords fullflexible