book.tex 587 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715
  1. %\documentclass[]{TimesAPriori_MIT}%%6x9
  2. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  3. %\documentclass[8x10]{TimesAPriori_MIT}%%8x10
  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. \definecolor{lightgray}{gray}{1}
  17. \newcommand{\black}[1]{{\color{black} #1}}
  18. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  19. \newcommand{\gray}[1]{{\color{gray} #1}}
  20. \def\racketEd{0}
  21. \def\pythonEd{1}
  22. \def\edition{1}
  23. % material that is specific to the Racket edition of the book
  24. \newcommand{\racket}[1]{{\if\edition\racketEd\color{olive}{#1}\fi}}
  25. % would like a command for: \if\edition\racketEd\color{olive}
  26. % and : \fi\color{black}
  27. % material that is specific to the Python edition of the book
  28. \newcommand{\python}[1]{{\if\edition\pythonEd\color{purple}{#1}\fi}}
  29. %% For multiple indices:
  30. \usepackage{multind}
  31. \makeindex{subject}
  32. \makeindex{authors}
  33. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  34. \lstset{%
  35. language=Lisp,
  36. basicstyle=\ttfamily\small,
  37. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  38. deletekeywords={read,mapping,vector},
  39. escapechar=|,
  40. columns=flexible,
  41. moredelim=[is][\color{red}]{~}{~},
  42. showstringspaces=false
  43. }
  44. %%% Any shortcut own defined macros place here
  45. %% sample of author macro:
  46. \input{defs}
  47. \newtheorem{exercise}[theorem]{Exercise}
  48. % Adjusted settings
  49. \setlength{\columnsep}{4pt}
  50. %% \begingroup
  51. %% \setlength{\intextsep}{0pt}%
  52. %% \setlength{\columnsep}{0pt}%
  53. %% \begin{wrapfigure}{r}{0.5\textwidth}
  54. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  55. %% \caption{Basic layout}
  56. %% \end{wrapfigure}
  57. %% \lipsum[1]
  58. %% \endgroup
  59. \newbox\oiintbox
  60. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  61. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  62. \def\oiint{\copy\oiintbox}
  63. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  64. %\usepackage{showframe}
  65. \def\ShowFrameLinethickness{0.125pt}
  66. \addbibresource{book.bib}
  67. \begin{document}
  68. \frontmatter
  69. \HalfTitle{Essentials of Compilation}
  70. \halftitlepage
  71. %% \begin{seriespage}
  72. %% \seriestitle{Industrial Economics}
  73. %% \serieseditor{Miriam Smith and Simon Rattle, editors}
  74. %% \title{Engineering and Economics}
  75. %% \author{Samuel Endgrove}
  76. %% \title{Structural Economics: From Beginning to End}
  77. %% \author{Guang Xi}
  78. %% \end{seriespage}
  79. \Title{Essentials of Compilation}
  80. \Booksubtitle{The Incremental, Nano-Pass Approach}
  81. \edition{First Edition}
  82. \BookAuthor{Jeremy G. Siek}
  83. \imprint{The MIT Press\\
  84. Cambridge, Massachusetts\\
  85. London, England}
  86. \begin{copyrightpage}
  87. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  88. or personal downloading under the
  89. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  90. license.
  91. Copyright in this monograph has been licensed exclusively to The MIT
  92. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  93. version to the public in 2022. All inquiries regarding rights should
  94. be addressed to The MIT Press, Rights and Permissions Department.
  95. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  96. %% All rights reserved. No part of this book may be reproduced in any
  97. %% form by any electronic or mechanical means (including photocopying,
  98. %% recording, or information storage and retrieval) without permission in
  99. %% writing from the publisher.
  100. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  101. %% United States of America.
  102. %% Library of Congress Cataloging-in-Publication Data is available.
  103. %% ISBN:
  104. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  105. \end{copyrightpage}
  106. \dedication{This book is dedicated to the programming language wonks
  107. at Indiana University.}
  108. %% \begin{epigraphpage}
  109. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  110. %% \textit{Book Name if any}}
  111. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  112. %% \end{epigraphpage}
  113. \tableofcontents
  114. \listoffigures
  115. \listoftables
  116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  117. \chapter*{Preface}
  118. \addcontentsline{toc}{fmbm}{Preface}
  119. There is a magical moment when a programmer presses the ``run'' button
  120. and the software begins to execute. Somehow a program written in a
  121. high-level language is running on a computer that is only capable of
  122. shuffling bits. Here we reveal the wizardry that makes that moment
  123. possible. Beginning with the groundbreaking work of Backus and
  124. colleagues in the 1950s, computer scientists discovered techniques for
  125. constructing programs, called \emph{compilers}, that automatically
  126. translate high-level programs into machine code.
  127. We take you on a journey by constructing your own compiler for a small
  128. but powerful language. Along the way we explain the essential
  129. concepts, algorithms, and data structures that underlie compilers. We
  130. develop your understanding of how programs are mapped onto computer
  131. hardware, which is helpful when reasoning about properties at the
  132. junction between hardware and software such as execution time,
  133. software errors, and security vulnerabilities. For those interested
  134. in pursuing compiler construction, our goal is to provide a
  135. stepping-stone to advanced topics such as just-in-time compilation,
  136. program analysis, and program optimization. For those interested in
  137. designing and implementing programming languages, we connect
  138. language design choices to their impact on the compiler and the generated
  139. code.
  140. A compiler is typically organized as a sequence of stages that
  141. progressively translates a program to code that runs on hardware. We
  142. take this approach to the extreme by partitioning our compiler into a
  143. large number of \emph{nanopasses}, each of which performs a single
  144. task. This allows us to test the output of each pass in isolation, and
  145. furthermore, allows us to focus our attention making the compiler far
  146. easier to understand.
  147. %% [TODO: easier to understand/debug for those maintaining the compiler,
  148. %% proving correctness]
  149. The most familiar approach to describing compilers is with one pass
  150. per chapter. The problem with that is it obfuscates how language
  151. features motivate design choices in a compiler. We take an
  152. \emph{incremental} approach in which we build a complete compiler in
  153. each chapter, starting with arithmetic and variables and add new
  154. features in subsequent chapters.
  155. Our choice of language features is designed to elicit the fundamental
  156. concepts and algorithms used in compilers.
  157. \begin{itemize}
  158. \item We begin with integer arithmetic and local variables in
  159. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  160. the fundamental tools of compiler construction: \emph{abstract
  161. syntax trees} and \emph{recursive functions}.
  162. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  163. \emph{graph coloring} to assign variables to machine registers.
  164. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  165. an elegant recursive algorithm for mapping expressions to
  166. \emph{control-flow graphs}.
  167. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  168. \emph{garbage collection}.
  169. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  170. but lack lexical scoping, similar to the C programming
  171. language~\citep{Kernighan:1988nx} except that we generate efficient
  172. tail calls. The reader learns about the procedure call stack,
  173. \emph{calling conventions}, and their interaction with register
  174. allocation and garbage collection.
  175. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  176. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  177. \emph{closure conversion}, in which lambdas are translated into a
  178. combination of functions and tuples.
  179. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  180. point the input languages are statically typed. The reader extends
  181. the statically typed language with an \code{Any} type which serves
  182. as a target for compiling the dynamically typed language.
  183. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  184. programming languages with the addition of loops and mutable
  185. variables. These additions elicit the need for \emph{dataflow
  186. analysis} in the register allocator.
  187. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  188. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  189. in which different regions of a program may be static or dynamically
  190. typed. The reader implements runtime support for \emph{proxies} that
  191. allow values to safely move between regions.
  192. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  193. leveraging the \code{Any} type and type casts developed in Chapters
  194. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  195. \end{itemize}
  196. There are many language features that we do not include. Our choices
  197. weigh the incidental complexity of a feature against the fundamental
  198. concepts that it exposes. For example, we include tuples and not
  199. records because they both elicit the study of heap allocation and
  200. garbage collection but records come with more incidental complexity.
  201. Since 2016 this book has served as the textbook for the compiler
  202. course at Indiana University, a 16-week course for upper-level
  203. undergraduates and first-year graduate students.
  204. %
  205. Prior to this course, students learn to program in both imperative and
  206. functional languages, study data structures and algorithms, and take
  207. discrete mathematics.
  208. %
  209. At the beginning of the course, students form groups of 2-4 people.
  210. The groups complete one chapter every two weeks, starting with
  211. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  212. chapters include a challenge problem that we assign to the graduate
  213. students. The last two weeks of the course involve a final project in
  214. which students design and implement a compiler extension of their
  215. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  216. \ref{ch:Rpoly} can be used in support of these projects or they can
  217. replace some of the earlier chapters. For example, a course with an
  218. emphasis on statically-typed imperative languages would skip
  219. Chapter~\ref{ch:Rdyn} in favor of
  220. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  221. the dependencies between chapters.
  222. This book has also been used in compiler courses at California
  223. Polytechnic State University, Portland State University, Rose–Hulman
  224. Institute of Technology, University of Massachusetts Lowell, and the
  225. University of Vermont.
  226. \begin{figure}[tp]
  227. \begin{tikzpicture}[baseline=(current bounding box.center)]
  228. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  229. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  230. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  231. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  232. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  233. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  234. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  235. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  236. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  237. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  238. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  239. \path[->] (C1) edge [above] node {} (C2);
  240. \path[->] (C2) edge [above] node {} (C3);
  241. \path[->] (C3) edge [above] node {} (C4);
  242. \path[->] (C4) edge [above] node {} (C5);
  243. \path[->] (C5) edge [above] node {} (C6);
  244. \path[->] (C6) edge [above] node {} (C7);
  245. \path[->] (C4) edge [above] node {} (C8);
  246. \path[->] (C4) edge [above] node {} (C9);
  247. \path[->] (C8) edge [above] node {} (C10);
  248. \path[->] (C10) edge [above] node {} (C11);
  249. \end{tikzpicture}
  250. \caption{Diagram of chapter dependencies.}
  251. \label{fig:chapter-dependences}
  252. \end{figure}
  253. \racket{
  254. We use the \href{https://racket-lang.org/}{Racket} language both for
  255. the implementation of the compiler and for the input language, so the
  256. reader should be proficient with Racket or Scheme. There are many
  257. excellent resources for learning Scheme and
  258. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  259. }
  260. \python{
  261. This edition of the book uses the \href{https://www.python.org/}{Python}
  262. both for the implementation of the compiler and for the input language, so the
  263. reader should be proficient with Python. There are many
  264. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  265. }
  266. The support code for this book is in the \code{github} repository at
  267. the following URL:
  268. \begin{center}\small
  269. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  270. \end{center}
  271. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  272. is helpful but not necessary for the reader to have taken a computer
  273. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  274. of x86-64 assembly language that are needed.
  275. %
  276. We follow the System V calling
  277. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  278. that we generate works with the runtime system (written in C) when it
  279. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  280. operating systems.
  281. %
  282. On the Windows operating system, \code{gcc} uses the Microsoft x64
  283. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  284. assembly code that we generate does \emph{not} work with the runtime
  285. system on Windows. One workaround is to use a virtual machine with
  286. Linux as the guest operating system.
  287. \section*{Acknowledgments}
  288. The tradition of compiler construction at Indiana University goes back
  289. to research and courses on programming languages by Daniel Friedman in
  290. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  291. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  292. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  293. the compiler course and continued the development of Chez Scheme.
  294. %
  295. The compiler course evolved to incorporate novel pedagogical ideas
  296. while also including elements of efficient real-world compilers. One
  297. of Friedman's ideas was to split the compiler into many small
  298. passes. Another idea, called ``the game'', was to test the code
  299. generated by each pass using interpreters.
  300. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  301. developed infrastructure to support this approach and evolved the
  302. course to use even smaller
  303. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  304. design decisions in this book are inspired by the assignment
  305. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  306. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  307. organization of the course made it difficult for students to
  308. understand the rationale for the compiler design. Ghuloum proposed the
  309. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  310. on.
  311. We thank the many students who served as teaching assistants for the
  312. compiler course at IU and made suggestions for improving the book
  313. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  314. thank Andre Kuhlenschmidt for his work on the garbage collector,
  315. Michael Vollmer for his work on efficient tail calls, and Michael
  316. Vitousek for his help running the first offering of the incremental
  317. compiler course at IU.
  318. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  319. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  320. for teaching courses based on drafts of this book and for their
  321. invaluable feedback.
  322. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  323. course in the early 2000's and especially for finding the bug that
  324. sent our garbage collector on a wild goose chase!
  325. \mbox{}\\
  326. \noindent Jeremy G. Siek \\
  327. Bloomington, Indiana
  328. \mainmatter
  329. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  330. \chapter{Preliminaries}
  331. \label{ch:trees-recur}
  332. In this chapter we review the basic tools that are needed to implement
  333. a compiler. Programs are typically input by a programmer as text,
  334. i.e., a sequence of characters. The program-as-text representation is
  335. called \emph{concrete syntax}. We use concrete syntax to concisely
  336. write down and talk about programs. Inside the compiler, we use
  337. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  338. that efficiently supports the operations that the compiler needs to
  339. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  340. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  341. from concrete syntax to abstract syntax is a process called
  342. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  343. implementation of parsing in this book.
  344. %
  345. \racket{A parser is provided in the support code for translating from
  346. concrete to abstract syntax.}
  347. %
  348. \python{We use Python's \code{ast} module to translate from concrete
  349. to abstract syntax.}
  350. ASTs can be represented in many different ways inside the compiler,
  351. depending on the programming language used to write the compiler.
  352. %
  353. \racket{We use Racket's
  354. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  355. feature to represent ASTs (Section~\ref{sec:ast}).}
  356. %
  357. \python{We use Python classes and objects to represent ASTs, especially the
  358. classes defined in the standard \code{ast} module for the Python
  359. source language.}
  360. %
  361. We use grammars to define the abstract syntax of programming languages
  362. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  363. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  364. recursive functions to construct and deconstruct ASTs
  365. (Section~\ref{sec:recursion}). This chapter provides an brief
  366. introduction to these ideas.
  367. \racket{\index{subject}{struct}}
  368. \python{\index{subject}{class}\index{subject}{object}}
  369. \section{Abstract Syntax Trees}
  370. \label{sec:ast}
  371. Compilers use abstract syntax trees to represent programs because they
  372. often need to ask questions like: for a given part of a program, what
  373. kind of language feature is it? What are its sub-parts? Consider the
  374. program on the left and its AST on the right. This program is an
  375. addition operation and it has two sub-parts, a read operation and a
  376. negation. The negation has another sub-part, the integer constant
  377. \code{8}. By using a tree to represent the program, we can easily
  378. follow the links to go from one part of a program to its sub-parts.
  379. \begin{center}
  380. \begin{minipage}{0.4\textwidth}
  381. \if\edition\racketEd
  382. \begin{lstlisting}
  383. (+ (read) (- 8))
  384. \end{lstlisting}
  385. \fi
  386. \if\edition\pythonEd
  387. \begin{lstlisting}
  388. input_int() + -8
  389. \end{lstlisting}
  390. \fi
  391. \end{minipage}
  392. \begin{minipage}{0.4\textwidth}
  393. \begin{equation}
  394. \begin{tikzpicture}
  395. \node[draw] (plus) at (0 , 0) {\key{+}};
  396. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  397. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  398. \node[draw] (8) at (1 , -3) {\key{8}};
  399. \draw[->] (plus) to (read);
  400. \draw[->] (plus) to (minus);
  401. \draw[->] (minus) to (8);
  402. \end{tikzpicture}
  403. \label{eq:arith-prog}
  404. \end{equation}
  405. \end{minipage}
  406. \end{center}
  407. We use the standard terminology for trees to describe ASTs: each
  408. rectangle above is called a \emph{node}. The arrows connect a node to its
  409. \emph{children} (which are also nodes). The top-most node is the
  410. \emph{root}. Every node except for the root has a \emph{parent} (the
  411. node it is the child of). If a node has no children, it is a
  412. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  413. \index{subject}{node}
  414. \index{subject}{children}
  415. \index{subject}{root}
  416. \index{subject}{parent}
  417. \index{subject}{leaf}
  418. \index{subject}{internal node}
  419. %% Recall that an \emph{symbolic expression} (S-expression) is either
  420. %% \begin{enumerate}
  421. %% \item an atom, or
  422. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  423. %% where $e_1$ and $e_2$ are each an S-expression.
  424. %% \end{enumerate}
  425. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  426. %% null value \code{'()}, etc. We can create an S-expression in Racket
  427. %% simply by writing a backquote (called a quasi-quote in Racket)
  428. %% followed by the textual representation of the S-expression. It is
  429. %% quite common to use S-expressions to represent a list, such as $a, b
  430. %% ,c$ in the following way:
  431. %% \begin{lstlisting}
  432. %% `(a . (b . (c . ())))
  433. %% \end{lstlisting}
  434. %% Each element of the list is in the first slot of a pair, and the
  435. %% second slot is either the rest of the list or the null value, to mark
  436. %% the end of the list. Such lists are so common that Racket provides
  437. %% special notation for them that removes the need for the periods
  438. %% and so many parenthesis:
  439. %% \begin{lstlisting}
  440. %% `(a b c)
  441. %% \end{lstlisting}
  442. %% The following expression creates an S-expression that represents AST
  443. %% \eqref{eq:arith-prog}.
  444. %% \begin{lstlisting}
  445. %% `(+ (read) (- 8))
  446. %% \end{lstlisting}
  447. %% When using S-expressions to represent ASTs, the convention is to
  448. %% represent each AST node as a list and to put the operation symbol at
  449. %% the front of the list. The rest of the list contains the children. So
  450. %% in the above case, the root AST node has operation \code{`+} and its
  451. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  452. %% diagram \eqref{eq:arith-prog}.
  453. %% To build larger S-expressions one often needs to splice together
  454. %% several smaller S-expressions. Racket provides the comma operator to
  455. %% splice an S-expression into a larger one. For example, instead of
  456. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  457. %% we could have first created an S-expression for AST
  458. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  459. %% S-expression.
  460. %% \begin{lstlisting}
  461. %% (define ast1.4 `(- 8))
  462. %% (define ast1_1 `(+ (read) ,ast1.4))
  463. %% \end{lstlisting}
  464. %% In general, the Racket expression that follows the comma (splice)
  465. %% can be any expression that produces an S-expression.
  466. {\if\edition\racketEd\color{olive}
  467. We define a Racket \code{struct} for each kind of node. For this
  468. chapter we require just two kinds of nodes: one for integer constants
  469. and one for primitive operations. The following is the \code{struct}
  470. definition for integer constants.
  471. \begin{lstlisting}
  472. (struct Int (value))
  473. \end{lstlisting}
  474. An integer node includes just one thing: the integer value.
  475. To create an AST node for the integer $8$, we write \INT{8}.
  476. \begin{lstlisting}
  477. (define eight (Int 8))
  478. \end{lstlisting}
  479. We say that the value created by \INT{8} is an
  480. \emph{instance} of the
  481. \code{Int} structure.
  482. The following is the \code{struct} definition for primitive operations.
  483. \begin{lstlisting}
  484. (struct Prim (op args))
  485. \end{lstlisting}
  486. A primitive operation node includes an operator symbol \code{op} and a
  487. list of child \code{args}. For example, to create an AST that negates
  488. the number $8$, we write \code{(Prim '- (list eight))}.
  489. \begin{lstlisting}
  490. (define neg-eight (Prim '- (list eight)))
  491. \end{lstlisting}
  492. Primitive operations may have zero or more children. The \code{read}
  493. operator has zero children:
  494. \begin{lstlisting}
  495. (define rd (Prim 'read '()))
  496. \end{lstlisting}
  497. whereas the addition operator has two children:
  498. \begin{lstlisting}
  499. (define ast1_1 (Prim '+ (list rd neg-eight)))
  500. \end{lstlisting}
  501. We have made a design choice regarding the \code{Prim} structure.
  502. Instead of using one structure for many different operations
  503. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  504. structure for each operation, as follows.
  505. \begin{lstlisting}
  506. (struct Read ())
  507. (struct Add (left right))
  508. (struct Neg (value))
  509. \end{lstlisting}
  510. The reason we choose to use just one structure is that in many parts
  511. of the compiler the code for the different primitive operators is the
  512. same, so we might as well just write that code once, which is enabled
  513. by using a single structure.
  514. \fi}
  515. {\if\edition\pythonEd\color{purple}
  516. We use a Python \code{class} for each kind of node.
  517. The following is the class definition for constants.
  518. \begin{lstlisting}
  519. class Constant:
  520. def __init__(self, value):
  521. self.value = value
  522. \end{lstlisting}
  523. An integer constant node includes just one thing: the integer value.
  524. To create an AST node for the integer $8$, we write \INT{8}.
  525. \begin{lstlisting}
  526. eight = Constant(8)
  527. \end{lstlisting}
  528. We say that the value created by \INT{8} is an
  529. \emph{instance} of the \code{Constant} class.
  530. The following is class definition for unary operators.
  531. \begin{lstlisting}
  532. class UnaryOp:
  533. def __init__(self, op, operand):
  534. self.op = op
  535. self.operand = operand
  536. \end{lstlisting}
  537. The specific operation is specified by the \code{op} parameter. For
  538. example, the class \code{USub} is for unary subtraction. (More unary
  539. operators are introduced in later chapters.) To create an AST that
  540. negates the number $8$, we write \NEG{\code{eight}}.
  541. \begin{lstlisting}
  542. neg_eight = UnaryOp(USub(), eight)
  543. \end{lstlisting}
  544. The call to the \code{input\_int} function is represented by the
  545. \code{Call} and \code{Name} classes.
  546. \begin{lstlisting}
  547. class Call:
  548. def __init__(self, func, args):
  549. self.func = func
  550. self.args = args
  551. class Name:
  552. def __init__(self, id):
  553. self.id = id
  554. \end{lstlisting}
  555. To create an AST node that calls \code{input\_int}, we write
  556. \begin{lstlisting}
  557. read = Call(Name('input_int'), [])
  558. \end{lstlisting}
  559. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  560. the \code{BinOp} class for binary operators.
  561. \begin{lstlisting}
  562. class BinOp:
  563. def __init__(self, left, op, right):
  564. self.op = op
  565. self.left = left
  566. self.right = right
  567. \end{lstlisting}
  568. Similar to \code{UnaryOp}, the specific operation is specified by the
  569. \code{op} parameter, which for now is just an instance of the
  570. \code{Add} class. So to create the AST node that adds negative eight
  571. to some user input, we write the following.
  572. \begin{lstlisting}
  573. ast1_1 = BinOp(read, Add(), neg_eight)
  574. \end{lstlisting}
  575. \fi}
  576. When compiling a program such as \eqref{eq:arith-prog}, we need to
  577. know that the operation associated with the root node is addition and
  578. we need to be able to access its two children. \racket{Racket}\python{Python}
  579. provides pattern matching to support these kinds of queries, as we see in
  580. Section~\ref{sec:pattern-matching}.
  581. In this book, we often write down the concrete syntax of a program
  582. even when we really have in mind the AST because the concrete syntax
  583. is more concise. We recommend that, in your mind, you always think of
  584. programs as abstract syntax trees.
  585. \section{Grammars}
  586. \label{sec:grammar}
  587. \index{subject}{integer}
  588. \index{subject}{literal}
  589. \index{subject}{constant}
  590. A programming language can be thought of as a \emph{set} of programs.
  591. The set is typically infinite (one can always create larger and larger
  592. programs), so one cannot simply describe a language by listing all of
  593. the programs in the language. Instead we write down a set of rules, a
  594. \emph{grammar}, for building programs. Grammars are often used to
  595. define the concrete syntax of a language, but they can also be used to
  596. describe the abstract syntax. We write our rules in a variant of
  597. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  598. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  599. As an example, we describe a small language, named \LangInt{}, that consists of
  600. integers and arithmetic operations.
  601. \index{subject}{grammar}
  602. The first grammar rule for the abstract syntax of \LangInt{} says that an
  603. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  604. \begin{equation}
  605. \Exp ::= \INT{\Int} \label{eq:arith-int}
  606. \end{equation}
  607. %
  608. Each rule has a left-hand-side and a right-hand-side.
  609. If you have an AST node that matches the
  610. right-hand-side, then you can categorize it according to the
  611. left-hand-side.
  612. %
  613. A name such as $\Exp$ that is defined by the grammar rules is a
  614. \emph{non-terminal}. \index{subject}{non-terminal}
  615. %
  616. The name $\Int$ is also a non-terminal, but instead of defining it
  617. with a grammar rule, we define it with the following explanation. An
  618. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  619. $-$ (for negative integers), such that the sequence of decimals
  620. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  621. the representation of integers using 63 bits, which simplifies several
  622. aspects of compilation. \racket{Thus, these integers corresponds to
  623. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  624. \python{In contrast, integers in Python have unlimited precision, but
  625. the techniques need to handle unlimited precision fall outside the
  626. scope of this book.}
  627. The second grammar rule is the \READOP{} operation that receives an
  628. input integer from the user of the program.
  629. \begin{equation}
  630. \Exp ::= \READ{} \label{eq:arith-read}
  631. \end{equation}
  632. The third rule says that, given an $\Exp$ node, the negation of that
  633. node is also an $\Exp$.
  634. \begin{equation}
  635. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  636. \end{equation}
  637. Symbols in typewriter font are \emph{terminal} symbols and must
  638. literally appear in the program for the rule to be applicable.
  639. \index{subject}{terminal}
  640. We can apply these rules to categorize the ASTs that are in the
  641. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  642. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  643. following AST is an $\Exp$.
  644. \begin{center}
  645. \begin{minipage}{0.5\textwidth}
  646. \NEG{\INT{\code{8}}}
  647. \end{minipage}
  648. \begin{minipage}{0.25\textwidth}
  649. \begin{equation}
  650. \begin{tikzpicture}
  651. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  652. \node[draw, circle] (8) at (0, -1.2) {$8$};
  653. \draw[->] (minus) to (8);
  654. \end{tikzpicture}
  655. \label{eq:arith-neg8}
  656. \end{equation}
  657. \end{minipage}
  658. \end{center}
  659. The next grammar rule is for addition expressions:
  660. \begin{equation}
  661. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  662. \end{equation}
  663. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  664. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  665. \eqref{eq:arith-read} and we have already categorized
  666. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  667. to show that
  668. \[
  669. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  670. \]
  671. is an $\Exp$ in the \LangInt{} language.
  672. If you have an AST for which the above rules do not apply, then the
  673. AST is not in \LangInt{}. For example, the program \racket{\code{(-
  674. (read) 8)}} \python{\code{input\_int() - 8}} is not in \LangInt{}
  675. because there are no rules for the \key{-} operator with two
  676. arguments. Whenever we define a language with a grammar, the language
  677. only includes those programs that are justified by the rules.
  678. {\if\edition\pythonEd\color{purple}
  679. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  680. There is a statement for printing the value of an expression
  681. \[
  682. \Stmt{} ::= \PRINT{\Exp}
  683. \]
  684. and a statement that evaluates an expression but ignores the result.
  685. \[
  686. \Stmt{} ::= \EXPR{\Exp}
  687. \]
  688. \fi}
  689. {\if\edition\racketEd\color{olive}
  690. The last grammar rule for \LangInt{} states that there is a
  691. \code{Program} node to mark the top of the whole program:
  692. \[
  693. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  694. \]
  695. The \code{Program} structure is defined as follows
  696. \begin{lstlisting}
  697. (struct Program (info body))
  698. \end{lstlisting}
  699. where \code{body} is an expression. In later chapters, the \code{info}
  700. part will be used to store auxiliary information but for now it is
  701. just the empty list.
  702. \fi}
  703. {\if\edition\pythonEd\color{purple}
  704. The last grammar rule for \LangInt{} states that there is a
  705. \code{Module} node to mark the top of the whole program:
  706. \[
  707. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  708. \]
  709. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  710. this case, a list of statements.
  711. %
  712. The \code{Module} class is defined as follows
  713. \begin{lstlisting}
  714. class Module:
  715. def __init__(self, body):
  716. self.body = body
  717. \end{lstlisting}
  718. where \code{body} is a list of statements.
  719. \fi}
  720. It is common to have many grammar rules with the same left-hand side
  721. but different right-hand sides, such as the rules for $\Exp$ in the
  722. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  723. combine several right-hand-sides into a single rule.
  724. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  725. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  726. defined in Figure~\ref{fig:r0-concrete-syntax}.
  727. \racket{The \code{read-program} function provided in
  728. \code{utilities.rkt} of the support code reads a program in from a
  729. file (the sequence of characters in the concrete syntax of Racket)
  730. and parses it into an abstract syntax tree. See the description of
  731. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  732. details.}
  733. \python{The \code{parse} function in Python's \code{ast} module
  734. converts the concrete syntax (represented as a string) into an
  735. abstract syntax tree.}
  736. \begin{figure}[tp]
  737. \fbox{
  738. \begin{minipage}{0.96\textwidth}
  739. {\if\edition\racketEd\color{olive}
  740. \[
  741. \begin{array}{rcl}
  742. \Exp &::=& \Int \MID \LP\key{read}\RP \MID \LP\key{-}\;\Exp\RP \MID \LP\key{+} \; \Exp\;\Exp\RP\\
  743. \LangInt{} &::=& \Exp
  744. \end{array}
  745. \]
  746. \fi}
  747. {\if\edition\pythonEd\color{purple}
  748. \[
  749. \begin{array}{rcl}
  750. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp\\
  751. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp\\
  752. \LangInt{} &::=& \Stmt^{*}
  753. \end{array}
  754. \]
  755. \fi}
  756. \end{minipage}
  757. }
  758. \caption{The concrete syntax of \LangInt{}.}
  759. \label{fig:r0-concrete-syntax}
  760. \end{figure}
  761. \begin{figure}[tp]
  762. \fbox{
  763. \begin{minipage}{0.96\textwidth}
  764. {\if\edition\racketEd\color{olive}
  765. \[
  766. \begin{array}{rcl}
  767. \Exp &::=& \INT{\Int} \MID \READ{} \MID \NEG{\Exp} \\
  768. &\MID& \ADD{\Exp}{\Exp} \\
  769. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  770. \end{array}
  771. \]
  772. \fi}
  773. {\if\edition\pythonEd\color{purple}
  774. \[
  775. \begin{array}{rcl}
  776. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  777. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  778. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  779. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  780. \end{array}
  781. \]
  782. \fi}
  783. \end{minipage}
  784. }
  785. \caption{The abstract syntax of \LangInt{}.}
  786. \label{fig:r0-syntax}
  787. \end{figure}
  788. \section{Pattern Matching}
  789. \label{sec:pattern-matching}
  790. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  791. the parts of an AST node. \racket{Racket}\python{Python} provides the
  792. \texttt{match} feature to access the parts of a value.
  793. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  794. \begin{center}
  795. \begin{minipage}{0.5\textwidth}
  796. {\if\edition\racketEd\color{olive}
  797. \begin{lstlisting}
  798. (match ast1_1
  799. [(Prim op (list child1 child2))
  800. (print op)])
  801. \end{lstlisting}
  802. \fi}
  803. {\if\edition\pythonEd\color{purple}
  804. \begin{lstlisting}
  805. match ast1_1:
  806. case BinOp(child1, op, child2):
  807. print(op)
  808. \end{lstlisting}
  809. \fi}
  810. \end{minipage}
  811. \end{center}
  812. {\if\edition\racketEd\color{olive}
  813. %
  814. In the above example, the \texttt{match} form checks whether the AST
  815. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  816. three pattern variables \texttt{op}, \texttt{child1}, and
  817. \texttt{child2}, and then prints out the operator. In general, a match
  818. clause consists of a \emph{pattern} and a
  819. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  820. to be either a pattern variable, a structure name followed by a
  821. pattern for each of the structure's arguments, or an S-expression
  822. (symbols, lists, etc.). (See Chapter 12 of The Racket
  823. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  824. and Chapter 9 of The Racket
  825. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  826. for a complete description of \code{match}.)
  827. %
  828. The body of a match clause may contain arbitrary Racket code. The
  829. pattern variables can be used in the scope of the body, such as
  830. \code{op} in \code{(print op)}.
  831. %
  832. \fi}
  833. %
  834. %
  835. {\if\edition\pythonEd\color{purple}
  836. %
  837. In the above example, the \texttt{match} form checks whether the AST
  838. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  839. three pattern variables \texttt{child1}, \texttt{op}, and
  840. \texttt{child2}, and then prints out the operator. In general, each
  841. \code{case} consists of a \emph{pattern} and a
  842. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  843. to be either a pattern variable, a class name followed by a pattern
  844. for each of its constructor's arguments, or other literals such as
  845. strings, lists, etc.
  846. %
  847. The body of each \code{case} may contain arbitrary Python code. The
  848. pattern variables can be used in the body, such as \code{op} in
  849. \code{print(op)}.
  850. %
  851. \fi}
  852. A \code{match} form may contain several clauses, as in the following
  853. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  854. the AST. The \code{match} proceeds through the clauses in order,
  855. checking whether the pattern can match the input AST. The body of the
  856. first clause that matches is executed. The output of \code{leaf} for
  857. several ASTs is shown on the right.
  858. \begin{center}
  859. \begin{minipage}{0.6\textwidth}
  860. {\if\edition\racketEd\color{olive}
  861. \begin{lstlisting}
  862. (define (leaf arith)
  863. (match arith
  864. [(Int n) #t]
  865. [(Prim 'read '()) #t]
  866. [(Prim '- (list e1)) #f]
  867. [(Prim '+ (list e1 e2)) #f]))
  868. (leaf (Prim 'read '()))
  869. (leaf (Prim '- (list (Int 8))))
  870. (leaf (Int 8))
  871. \end{lstlisting}
  872. \fi}
  873. {\if\edition\pythonEd\color{purple}
  874. \begin{lstlisting}
  875. def leaf(arith):
  876. match arith:
  877. case Constant(n):
  878. return True
  879. case Call(Name('input_int'), []):
  880. return True
  881. case UnaryOp(USub(), e1):
  882. return False
  883. case BinOp(e1, Add(), e2):
  884. return False
  885. case _:
  886. return False
  887. print(leaf(Call(Name('input_int'), [])))
  888. print(leaf(UnaryOp(USub(), eight)))
  889. print(leaf(Constant(8)))
  890. \end{lstlisting}
  891. \fi}
  892. \end{minipage}
  893. \vrule
  894. \begin{minipage}{0.25\textwidth}
  895. {\if\edition\racketEd\color{olive}
  896. \begin{lstlisting}
  897. #t
  898. #f
  899. #t
  900. \end{lstlisting}
  901. \fi}
  902. {\if\edition\pythonEd\color{purple}
  903. \begin{lstlisting}
  904. True
  905. False
  906. True
  907. \end{lstlisting}
  908. \fi}
  909. \end{minipage}
  910. \end{center}
  911. When writing a \code{match}, we refer to the grammar definition to
  912. identify which non-terminal we are expecting to match against, then we
  913. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  914. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  915. corresponding right-hand side of a grammar rule. For the \code{match}
  916. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  917. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  918. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  919. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  920. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  921. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  922. patterns, replace non-terminals such as $\Exp$ with pattern variables
  923. of your choice (e.g. \code{e1} and \code{e2}).
  924. \section{Recursive Functions}
  925. \label{sec:recursion}
  926. \index{subject}{recursive function}
  927. Programs are inherently recursive. For example, an \LangInt{}
  928. expression is often made of smaller expressions. Thus, the natural way
  929. to process an entire program is with a recursive function. As a first
  930. example of such a recursive function, we define the function
  931. \code{exp} in Figure~\ref{fig:exp-predicate}, which takes an
  932. arbitrary value and determines whether or not it is an \LangInt{}
  933. expression.
  934. %
  935. We say that a function is defined by \emph{structural recursion} when
  936. it is defined using a sequence of match \racket{clauses}\python{cases}
  937. that correspond to a grammar, and the body of each \racket{clause}\python{case}
  938. makes a recursive call on each
  939. child node.\footnote{This principle of structuring code according to
  940. the data definition is advocated in the book \emph{How to Design
  941. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  942. \python{We define a second function, named \code{stmt}, that recognizes
  943. whether a value is a \LangInt{} statement.}
  944. \python{Finally, }
  945. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{Rint}, which
  946. determines whether an AST is a program in \LangInt{}. In general we can
  947. expect to write one recursive function to handle each non-terminal in
  948. a grammar.\index{subject}{structural recursion}
  949. \begin{figure}[tp]
  950. {\if\edition\racketEd\color{olive}
  951. \begin{minipage}{0.7\textwidth}
  952. \begin{lstlisting}
  953. (define (exp ast)
  954. (match ast
  955. [(Int n) #t]
  956. [(Prim 'read '()) #t]
  957. [(Prim '- (list e)) (exp e)]
  958. [(Prim '+ (list e1 e2))
  959. (and (exp e1) (exp e2))]
  960. [else #f]))
  961. (define (Rint ast)
  962. (match ast
  963. [(Program '() e) (exp e)]
  964. [else #f]))
  965. (Rint (Program '() ast1_1)
  966. (Rint (Program '()
  967. (Prim '- (list (Prim 'read '())
  968. (Prim '+ (list (Num 8)))))))
  969. \end{lstlisting}
  970. \end{minipage}
  971. \vrule
  972. \begin{minipage}{0.25\textwidth}
  973. \begin{lstlisting}
  974. #t
  975. #f
  976. \end{lstlisting}
  977. \end{minipage}
  978. \fi}
  979. {\if\edition\pythonEd\color{purple}
  980. \begin{minipage}{0.7\textwidth}
  981. \begin{lstlisting}
  982. def exp(e):
  983. match e:
  984. case Constant(n):
  985. return True
  986. case Call(Name('input_int'), []):
  987. return True
  988. case UnaryOp(USub(), e1):
  989. return exp(e1)
  990. case BinOp(e1, Add(), e2):
  991. return exp(e1) and exp(e2)
  992. case _:
  993. return False
  994. def stmt(s):
  995. match s:
  996. case Call(Name('print'), [e]):
  997. return exp(e)
  998. case Expr(e):
  999. return exp(e)
  1000. case _:
  1001. return False
  1002. def Rint(p):
  1003. match p:
  1004. case Module(body):
  1005. return all([stmt(s) for s in body])
  1006. case _:
  1007. return False
  1008. print(Rint(Module([Expr(ast1_1)])))
  1009. print(Rint(Module([Expr(BinOp(read, Sub(),
  1010. UnaryOp(Add(), Constant(8))))])))
  1011. \end{lstlisting}
  1012. \end{minipage}
  1013. \vrule
  1014. \begin{minipage}{0.25\textwidth}
  1015. \begin{lstlisting}
  1016. True
  1017. False
  1018. \end{lstlisting}
  1019. \end{minipage}
  1020. \fi}
  1021. \caption{Example of recursive functions for \LangInt{}. These functions
  1022. recognize whether an AST is in \LangInt{}.}
  1023. \label{fig:exp-predicate}
  1024. \end{figure}
  1025. %% You may be tempted to merge the two functions into one, like this:
  1026. %% \begin{center}
  1027. %% \begin{minipage}{0.5\textwidth}
  1028. %% \begin{lstlisting}
  1029. %% (define (Rint ast)
  1030. %% (match ast
  1031. %% [(Int n) #t]
  1032. %% [(Prim 'read '()) #t]
  1033. %% [(Prim '- (list e)) (Rint e)]
  1034. %% [(Prim '+ (list e1 e2)) (and (Rint e1) (Rint e2))]
  1035. %% [(Program '() e) (Rint e)]
  1036. %% [else #f]))
  1037. %% \end{lstlisting}
  1038. %% \end{minipage}
  1039. %% \end{center}
  1040. %% %
  1041. %% Sometimes such a trick will save a few lines of code, especially when
  1042. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1043. %% \emph{not} recommended because it can get you into trouble.
  1044. %% %
  1045. %% For example, the above function is subtly wrong:
  1046. %% \lstinline{(Rint (Program '() (Program '() (Int 3))))}
  1047. %% returns true when it should return false.
  1048. \section{Interpreters}
  1049. \label{sec:interp_Rint}
  1050. \index{subject}{interpreter}
  1051. The behavior of a program is defined by the specification of the
  1052. programming language.
  1053. %
  1054. \racket{For example, the Scheme language is defined in the report by
  1055. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1056. reference manual~\citep{plt-tr}.}
  1057. %
  1058. \python{For example, the Python language is defined in the Python
  1059. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1060. %
  1061. In this book we use interpreters
  1062. to specify each language that we consider. An interpreter that is
  1063. designated as the definition of a language is called a
  1064. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1065. \index{subject}{definitional interpreter} We warm up by creating a
  1066. definitional interpreter for the \LangInt{} language, which serves as
  1067. a second example of structural recursion. The \texttt{interp\_Rint}
  1068. function is defined in Figure~\ref{fig:interp_Rint}. The body of the
  1069. function is a match on the input program followed by a call to the
  1070. \lstinline{interp_exp} helper function, which in turn has one match
  1071. clause per grammar rule for \LangInt{} expressions.
  1072. \begin{figure}[tp]
  1073. {\if\edition\racketEd\color{olive}
  1074. \begin{lstlisting}
  1075. (define (interp_exp e)
  1076. (match e
  1077. [(Int n) n]
  1078. [(Prim 'read '())
  1079. (define r (read))
  1080. (cond [(fixnum? r) r]
  1081. [else (error 'interp_exp "read expected an integer" r)])]
  1082. [(Prim '- (list e))
  1083. (define v (interp_exp e))
  1084. (fx- 0 v)]
  1085. [(Prim '+ (list e1 e2))
  1086. (define v1 (interp_exp e1))
  1087. (define v2 (interp_exp e2))
  1088. (fx+ v1 v2)]))
  1089. (define (interp_Rint p)
  1090. (match p
  1091. [(Program '() e) (interp_exp e)]))
  1092. \end{lstlisting}
  1093. \fi}
  1094. {\if\edition\pythonEd\color{purple}
  1095. \begin{lstlisting}
  1096. def interp_exp(e):
  1097. match e:
  1098. case BinOp(left, Add(), right):
  1099. l = interp_exp(left)
  1100. r = interp_exp(right)
  1101. return l + r
  1102. case UnaryOp(USub(), v):
  1103. return - interp_exp(v)
  1104. case Constant(value):
  1105. return value
  1106. case Call(Name('input_int'), []):
  1107. return int(input())
  1108. def interp_stmt(s):
  1109. match s:
  1110. case Expr(Call(Name('print'), [arg])):
  1111. print(interp_exp(arg))
  1112. case Expr(value):
  1113. interp_exp(value)
  1114. def interp_Pint(p):
  1115. match p:
  1116. case Module(body):
  1117. for s in body:
  1118. interp_stmt(s)
  1119. \end{lstlisting}
  1120. \fi}
  1121. \caption{Interpreter for the \LangInt{} language.}
  1122. \label{fig:interp_Rint}
  1123. \end{figure}
  1124. Let us consider the result of interpreting a few \LangInt{} programs. The
  1125. following program adds two integers.
  1126. {\if\edition\racketEd\color{olive}
  1127. \begin{lstlisting}
  1128. (+ 10 32)
  1129. \end{lstlisting}
  1130. \fi}
  1131. {\if\edition\pythonEd\color{purple}
  1132. \begin{lstlisting}
  1133. print(10 + 32)
  1134. \end{lstlisting}
  1135. \fi}
  1136. The result is \key{42}, the answer to life, the universe, and
  1137. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1138. Galaxy} by Douglas Adams.}.
  1139. %
  1140. We wrote the above program in concrete syntax whereas the parsed
  1141. abstract syntax is:
  1142. {\if\edition\racketEd\color{olive}
  1143. \begin{lstlisting}
  1144. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1145. \end{lstlisting}
  1146. \fi}
  1147. {\if\edition\pythonEd\color{purple}
  1148. \begin{lstlisting}
  1149. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1150. \end{lstlisting}
  1151. \fi}
  1152. The next example demonstrates that expressions may be nested within
  1153. each other, in this case nesting several additions and negations.
  1154. {\if\edition\racketEd\color{olive}
  1155. \begin{lstlisting}
  1156. (+ 10 (- (+ 12 20)))
  1157. \end{lstlisting}
  1158. \fi}
  1159. {\if\edition\pythonEd\color{purple}
  1160. \begin{lstlisting}
  1161. print(10 + -(12 + 20))
  1162. \end{lstlisting}
  1163. \fi}
  1164. What is the result of the above program?
  1165. {\if\edition\racketEd\color{olive}
  1166. As mentioned previously, the \LangInt{} language does not support
  1167. arbitrarily-large integers, but only $63$-bit integers, so we
  1168. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1169. in Racket.
  1170. Suppose
  1171. \[
  1172. n = 999999999999999999
  1173. \]
  1174. which indeed fits in $63$-bits. What happens when we run the
  1175. following program in our interpreter?
  1176. \begin{lstlisting}
  1177. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1178. \end{lstlisting}
  1179. It produces an error:
  1180. \begin{lstlisting}
  1181. fx+: result is not a fixnum
  1182. \end{lstlisting}
  1183. We establish the convention that if running the definitional
  1184. interpreter on a program produces an error then the meaning of that
  1185. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1186. error is a \code{trapped-error}. A compiler for the language is under
  1187. no obligations regarding programs with unspecified behavior; it does
  1188. not have to produce an executable, and if it does, that executable can
  1189. do anything. On the other hand, if the error is a
  1190. \code{trapped-error}, then the compiler must produce an executable and
  1191. it is required to report that an error occurred. To signal an error,
  1192. exit with a return code of \code{255}. The interpreters in chapters
  1193. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1194. \code{trapped-error}.
  1195. \fi}
  1196. % TODO: how to deal with too-large integers in the Python interpreter?
  1197. %% This convention applies to the languages defined in this
  1198. %% book, as a way to simplify the student's task of implementing them,
  1199. %% but this convention is not applicable to all programming languages.
  1200. %%
  1201. Moving on to the last feature of the \LangInt{} language, the
  1202. \READOP{} operation prompts the user of the program for an integer.
  1203. Recall that program \eqref{eq:arith-prog} requests an integer input
  1204. and then subtracts \code{8}. So if we run
  1205. {\if\edition\racketEd\color{olive}
  1206. \begin{lstlisting}
  1207. (interp_Rint (Program '() ast1_1))
  1208. \end{lstlisting}
  1209. \fi}
  1210. {\if\edition\pythonEd\color{purple}
  1211. \begin{lstlisting}
  1212. interp_Pint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1213. \end{lstlisting}
  1214. \fi}
  1215. \noindent and if the input is \code{50}, the result is \code{42}.
  1216. We include the \READOP{} operation in \LangInt{} so a clever student
  1217. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1218. during compilation to obtain the output and then generates the trivial
  1219. code to produce the output.\footnote{Yes, a clever student did this in the
  1220. first instance of this course!}
  1221. The job of a compiler is to translate a program in one language into a
  1222. program in another language so that the output program behaves the
  1223. same way as the input program does. This idea is depicted in the
  1224. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1225. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1226. Given a compiler that translates from language $\mathcal{L}_1$ to
  1227. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1228. compiler must translate it into some program $P_2$ such that
  1229. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1230. same input $i$ yields the same output $o$.
  1231. \begin{equation} \label{eq:compile-correct}
  1232. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1233. \node (p1) at (0, 0) {$P_1$};
  1234. \node (p2) at (3, 0) {$P_2$};
  1235. \node (o) at (3, -2.5) {$o$};
  1236. \path[->] (p1) edge [above] node {compile} (p2);
  1237. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1238. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1239. \end{tikzpicture}
  1240. \end{equation}
  1241. In the next section we see our first example of a compiler.
  1242. \section{Example Compiler: a Partial Evaluator}
  1243. \label{sec:partial-evaluation}
  1244. In this section we consider a compiler that translates \LangInt{} programs
  1245. into \LangInt{} programs that may be more efficient, that is, this compiler
  1246. is an optimizer. This optimizer eagerly computes the parts of the
  1247. program that do not depend on any inputs, a process known as
  1248. \emph{partial evaluation}~\citep{Jones:1993uq}.
  1249. \index{subject}{partial evaluation}
  1250. For example, given the following program
  1251. {\if\edition\racketEd\color{olive}
  1252. \begin{lstlisting}
  1253. (+ (read) (- (+ 5 3)))
  1254. \end{lstlisting}
  1255. \fi}
  1256. {\if\edition\pythonEd\color{purple}
  1257. \begin{lstlisting}
  1258. print input_int() + -(5 + 3)
  1259. \end{lstlisting}
  1260. \fi}
  1261. \noindent our compiler translates it into the program
  1262. {\if\edition\racketEd\color{olive}
  1263. \begin{lstlisting}
  1264. (+ (read) -8)
  1265. \end{lstlisting}
  1266. \fi}
  1267. {\if\edition\pythonEd\color{purple}
  1268. \begin{lstlisting}
  1269. print input_int() + -8
  1270. \end{lstlisting}
  1271. \fi}
  1272. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1273. evaluator for the \LangInt{} language. The output of the partial evaluator
  1274. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  1275. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1276. whereas the code for partially evaluating the negation and addition
  1277. operations is factored into two separate helper functions:
  1278. \code{pe\_neg} and \code{pe\_add}. The input to these helper
  1279. functions is the output of partially evaluating the children.
  1280. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1281. arguments are integers and if they are, perform the appropriate
  1282. arithmetic. Otherwise, they create an AST node for the arithmetic
  1283. operation.
  1284. \begin{figure}[tp]
  1285. {\if\edition\racketEd\color{olive}
  1286. \begin{lstlisting}
  1287. (define (pe_neg r)
  1288. (match r
  1289. [(Int n) (Int (fx- 0 n))]
  1290. [else (Prim '- (list r))]))
  1291. (define (pe_add r1 r2)
  1292. (match* (r1 r2)
  1293. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1294. [(_ _) (Prim '+ (list r1 r2))]))
  1295. (define (pe_exp e)
  1296. (match e
  1297. [(Int n) (Int n)]
  1298. [(Prim 'read '()) (Prim 'read '())]
  1299. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1300. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1301. (define (pe_Rint p)
  1302. (match p
  1303. [(Program '() e) (Program '() (pe_exp e))]))
  1304. \end{lstlisting}
  1305. \fi}
  1306. {\if\edition\pythonEd\color{purple}
  1307. \begin{lstlisting}
  1308. def pe_neg(r):
  1309. match r:
  1310. case Constant(n):
  1311. return Constant(-n)
  1312. case _:
  1313. return UnaryOp(USub(), r)
  1314. def pe_add(r1, r2):
  1315. match (r1, r2):
  1316. case (Constant(n1), Constant(n2)):
  1317. return Constant(n1 + n2)
  1318. case _:
  1319. return BinOp(r1, Add(), r2)
  1320. def pe_exp(e):
  1321. match e:
  1322. case BinOp(left, Add(), right):
  1323. return pe_add(pe_exp(left), pe_exp(right))
  1324. case UnaryOp(USub(), v):
  1325. return pe_neg(pe_exp(v))
  1326. case Constant(value):
  1327. return e
  1328. case Call(Name('input_int'), []):
  1329. return e
  1330. def pe_stmt(s):
  1331. match s:
  1332. case Expr(Call(Name('print'), [arg])):
  1333. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1334. case Expr(value):
  1335. return Expr(pe_exp(value))
  1336. def pe_Pint(p):
  1337. match p:
  1338. case Module(body):
  1339. new_body = [pe_stmt(s) for s in body]
  1340. return Module(new_body)
  1341. \end{lstlisting}
  1342. \fi}
  1343. \caption{A partial evaluator for \LangInt{}.}
  1344. \label{fig:pe-arith}
  1345. \end{figure}
  1346. To gain some confidence that the partial evaluator is correct, we can
  1347. test whether it produces programs that get the same result as the
  1348. input programs. That is, we can test whether it satisfies Diagram
  1349. \ref{eq:compile-correct}.
  1350. %
  1351. {\if\edition\racketEd\color{olive}
  1352. The following code runs the partial evaluator on several examples and
  1353. tests the output program. The \texttt{parse-program} and
  1354. \texttt{assert} functions are defined in
  1355. Appendix~\ref{appendix:utilities}.\\
  1356. \begin{minipage}{1.0\textwidth}
  1357. \begin{lstlisting}
  1358. (define (test_pe p)
  1359. (assert "testing pe_Rint"
  1360. (equal? (interp_Rint p) (interp_Rint (pe_Rint p)))))
  1361. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1362. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1363. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1364. \end{lstlisting}
  1365. \end{minipage}
  1366. \fi}
  1367. % TODO: python version of testing the PE
  1368. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1369. \chapter{Integers and Variables}
  1370. \label{ch:Rvar}
  1371. This chapter is about compiling a subset of \racket{Racket}\python{Python}
  1372. to x86-64 assembly
  1373. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1374. integer arithmetic and local variable binding. We often refer to
  1375. x86-64 simply as x86. The chapter begins with a description of the
  1376. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1377. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1378. is large so we discuss only the instructions needed for compiling
  1379. \LangVar{}. We introduce more x86 instructions in later chapters.
  1380. After introducing \LangVar{} and x86, we reflect on their differences
  1381. and come up with a plan to break down the translation from \LangVar{}
  1382. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1383. rest of the sections in this chapter give detailed hints regarding
  1384. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1385. We hope to give enough hints that the well-prepared reader, together
  1386. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1387. a couple weeks. To give the reader a feeling for the scale of this
  1388. first compiler, the instructor solution for the \LangVar{} compiler is
  1389. approximately \racket{500}\python{300} lines of code.
  1390. \section{The \LangVar{} Language}
  1391. \label{sec:s0}
  1392. \index{subject}{variable}
  1393. The \LangVar{} language extends the \LangInt{} language with
  1394. variables. The concrete syntax of the \LangVar{} language is defined
  1395. by the grammar in Figure~\ref{fig:Rvar-concrete-syntax} and the
  1396. abstract syntax is defined in Figure~\ref{fig:Rvar-syntax}. The
  1397. non-terminal \Var{} may be any Racket identifier. As in \LangInt{},
  1398. \key{read} is a nullary operator, \key{-} is a unary operator, and
  1399. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1400. syntax of \LangVar{} includes the \racket{\key{Program}
  1401. struct}\python{\key{Module} instance} to mark the top of the
  1402. program.
  1403. %% The $\itm{info}$
  1404. %% field of the \key{Program} structure contains an \emph{association
  1405. %% list} (a list of key-value pairs) that is used to communicate
  1406. %% auxiliary data from one compiler pass the next.
  1407. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1408. exhibit several compilation techniques.
  1409. \begin{figure}[tp]
  1410. \centering
  1411. \fbox{
  1412. \begin{minipage}{0.96\textwidth}
  1413. {\if\edition\racketEd\color{olive}
  1414. \[
  1415. \begin{array}{rcl}
  1416. \Exp &::=& \Int{} \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}\\
  1417. &\MID& \Var{} \MID \CLET{\Var}{\Exp}{\Exp} \\
  1418. \LangVarM{} &::=& \Exp
  1419. \end{array}
  1420. \]
  1421. \fi}
  1422. {\if\edition\pythonEd\color{purple}
  1423. \[
  1424. \begin{array}{rcl}
  1425. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Var{} \\
  1426. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp\\
  1427. \LangVarM{} &::=& \Stmt^{*}
  1428. \end{array}
  1429. \]
  1430. \fi}
  1431. \end{minipage}
  1432. }
  1433. \caption{The concrete syntax of \LangVar{}.}
  1434. \label{fig:Rvar-concrete-syntax}
  1435. \end{figure}
  1436. \begin{figure}[tp]
  1437. \centering
  1438. \fbox{
  1439. \begin{minipage}{0.96\textwidth}
  1440. {\if\edition\racketEd\color{olive}
  1441. \[
  1442. \begin{array}{rcl}
  1443. \Exp &::=& \INT{\Int} \MID \READ{} \\
  1444. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  1445. &\MID& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  1446. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1447. \end{array}
  1448. \]
  1449. \fi}
  1450. {\if\edition\pythonEd\color{purple}
  1451. \[
  1452. \begin{array}{rcl}
  1453. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  1454. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \VAR{\Var{}} \\
  1455. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  1456. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  1457. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1458. \end{array}
  1459. \]
  1460. \fi}
  1461. \end{minipage}
  1462. }
  1463. \caption{The abstract syntax of \LangVar{}.}
  1464. \label{fig:Rvar-syntax}
  1465. \end{figure}
  1466. {\if\edition\racketEd\color{olive}
  1467. Let us dive further into the syntax and semantics of the \LangVar{}
  1468. language. The \key{let} feature defines a variable for use within its
  1469. body and initializes the variable with the value of an expression.
  1470. The abstract syntax for \key{let} is defined in
  1471. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for \key{let} is
  1472. \begin{lstlisting}
  1473. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1474. \end{lstlisting}
  1475. For example, the following program initializes \code{x} to $32$ and then
  1476. evaluates the body \code{(+ 10 x)}, producing $42$.
  1477. \begin{lstlisting}
  1478. (let ([x (+ 12 20)]) (+ 10 x))
  1479. \end{lstlisting}
  1480. \fi}
  1481. %
  1482. {\if\edition\pythonEd\color{purple}
  1483. The \LangVar{} language adds variables and the assignment statement
  1484. to \LangInt{}. The assignment statement defines a variable for use by
  1485. later statements and initializes the variable with the value of an expression.
  1486. The abstract syntax for assignment is defined in
  1487. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for assignment is
  1488. \begin{lstlisting}
  1489. |$\itm{var}$| = |$\itm{exp}$|
  1490. \end{lstlisting}
  1491. For example, the following program initializes \code{x} to $32$ and then
  1492. prints the result of \code{10 + x}, producing $42$.
  1493. \begin{lstlisting}
  1494. x = 12 + 20
  1495. print(10 + x)
  1496. \end{lstlisting}
  1497. \fi}
  1498. {\if\edition\racketEd\color{olive}
  1499. When there are multiple \key{let}'s for the same variable, the closest
  1500. enclosing \key{let} is used. That is, variable definitions overshadow
  1501. prior definitions. Consider the following program with two \key{let}'s
  1502. that define variables named \code{x}. Can you figure out the result?
  1503. \begin{lstlisting}
  1504. (let ([x 32]) (+ (let ([x 10]) x) x))
  1505. \end{lstlisting}
  1506. For the purposes of depicting which variable uses correspond to which
  1507. definitions, the following shows the \code{x}'s annotated with
  1508. subscripts to distinguish them. Double check that your answer for the
  1509. above is the same as your answer for this annotated version of the
  1510. program.
  1511. \begin{lstlisting}
  1512. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1513. \end{lstlisting}
  1514. The initializing expression is always evaluated before the body of the
  1515. \key{let}, so in the following, the \key{read} for \code{x} is
  1516. performed before the \key{read} for \code{y}. Given the input
  1517. $52$ then $10$, the following produces $42$ (not $-42$).
  1518. \begin{lstlisting}
  1519. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1520. \end{lstlisting}
  1521. \fi}
  1522. \subsection{Extensible Interpreters via Method Overriding}
  1523. \label{sec:extensible-interp}
  1524. To prepare for discussing the interpreter for \LangVar{}, we
  1525. explain why we to implement the interpreter using
  1526. object-oriented programming, that is, as a collection of methods
  1527. inside of a class. Throughout this book we define many interpreters,
  1528. one for each of the languages that we study. Because each language
  1529. builds on the prior one, there is a lot of commonality between these
  1530. interpreters. We want to write down the common parts just once
  1531. instead of many times. A naive approach would be to have, for example,
  1532. the interpreter for \LangIf{} handle all of the new features in that
  1533. language and then have a default case that dispatches to the
  1534. interpreter for \LangVar{}. The following code sketches this idea.
  1535. \begin{center}
  1536. {\if\edition\racketEd\color{olive}
  1537. \begin{minipage}{0.45\textwidth}
  1538. \begin{lstlisting}
  1539. (define (interp_Rvar_exp e)
  1540. (match e
  1541. [(Prim '- (list e1))
  1542. (fx- 0 (interp_Rvar_exp e1))]
  1543. ...))
  1544. \end{lstlisting}
  1545. \end{minipage}
  1546. \begin{minipage}{0.45\textwidth}
  1547. \begin{lstlisting}
  1548. (define (interp_Rif_exp e)
  1549. (match e
  1550. [(If cnd thn els)
  1551. (match (interp_Rif_exp cnd)
  1552. [#t (interp_Rif_exp thn)]
  1553. [#f (interp_Rif_exp els)])]
  1554. ...
  1555. [else (interp_Rvar_exp e)]))
  1556. \end{lstlisting}
  1557. \end{minipage}
  1558. \fi}
  1559. {\if\edition\pythonEd\color{purple}
  1560. \begin{minipage}{0.45\textwidth}
  1561. \begin{lstlisting}
  1562. def interp_Rvar_exp(e):
  1563. match e:
  1564. case UnaryOp(USub(), e1):
  1565. return - interp_Rvar_exp(e1)
  1566. ...
  1567. \end{lstlisting}
  1568. \end{minipage}
  1569. \begin{minipage}{0.45\textwidth}
  1570. \begin{lstlisting}
  1571. def interp_Rif_exp(e):
  1572. match e:
  1573. case IfExp(cnd, thn, els):
  1574. match interp_Rif_exp(cnd):
  1575. case True:
  1576. return interp_Rif_exp(thn)
  1577. case False:
  1578. return interp_Rif_exp(els)
  1579. ...
  1580. case _:
  1581. return interp_Rvar_exp(e)
  1582. \end{lstlisting}
  1583. \end{minipage}
  1584. \fi}
  1585. \end{center}
  1586. The problem with this approach is that it does not handle situations
  1587. in which an \LangIf{} feature, such as a conditional expression, is
  1588. nested inside an \LangVar{} feature, like the \code{-} operator, as in
  1589. the following program.
  1590. {\if\edition\racketEd\color{olive}
  1591. \begin{lstlisting}
  1592. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1593. \end{lstlisting}
  1594. \fi}
  1595. {\if\edition\pythonEd\color{purple}
  1596. \begin{lstlisting}
  1597. print(-(42 if True else 0))
  1598. \end{lstlisting}
  1599. \fi}
  1600. If we invoke \code{interp\_Rif\_exp} on this program, it dispatches to
  1601. \code{interp\_Rvar\_exp} to handle the \code{-} operator, but then it
  1602. recurisvely calls \code{interp\_Rvar\_exp} again on the argument of \code{-},
  1603. which is an \code{If}. But there is no case for \code{If} in
  1604. \code{interp\_Rvar\_exp}, so we get an error!
  1605. To make our interpreters extensible we need something called
  1606. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1607. recursive knot is delayed to when the functions are
  1608. composed. Object-oriented languages provide open recursion with the
  1609. late-binding of overridden methods\index{subject}{method overriding}. The
  1610. following code sketches this idea for interpreting \LangVar{} and
  1611. \LangIf{} using
  1612. \racket{the
  1613. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1614. \index{subject}{class} feature of Racket}
  1615. \python{a Python \code{class} definition}. We define one class for each
  1616. language and define a method for interpreting expressions inside each
  1617. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1618. and the method \code{interp\_exp} in \LangIf{} overrides the
  1619. \code{interp\_exp} in \LangVar{}. Note that the default case of
  1620. \code{interp\_exp} in \LangIf{} uses \code{super} to invoke
  1621. \code{interp\_exp}, and because \LangIf{} inherits from \LangVar{},
  1622. that dispatches to the \code{interp\_exp} in \LangVar{}.
  1623. \begin{center}
  1624. {\if\edition\racketEd\color{olive}
  1625. \begin{minipage}{0.45\textwidth}
  1626. \begin{lstlisting}
  1627. (define interp_Rvar_class
  1628. (class object%
  1629. (define/public (interp_exp e)
  1630. (match e
  1631. [(Prim '- (list e))
  1632. (fx- 0 (interp_exp e))]
  1633. ...))
  1634. ...))
  1635. \end{lstlisting}
  1636. \end{minipage}
  1637. \begin{minipage}{0.45\textwidth}
  1638. \begin{lstlisting}
  1639. (define interp_Rif_class
  1640. (class interp_Rvar_class
  1641. (define/override (interp_exp e)
  1642. (match e
  1643. [(If cnd thn els)
  1644. (match (interp_exp cnd)
  1645. [#t (interp_exp thn)]
  1646. [#f (interp_exp els)])]
  1647. ...
  1648. [else (super interp_exp e)]))
  1649. ...
  1650. ))
  1651. \end{lstlisting}
  1652. \end{minipage}
  1653. \fi}
  1654. {\if\edition\pythonEd\color{purple}
  1655. \begin{minipage}{0.45\textwidth}
  1656. \begin{lstlisting}
  1657. class InterpRvar:
  1658. def interp_exp(e):
  1659. match e:
  1660. case UnaryOp(USub(), e1):
  1661. return -self.interp_exp(e1)
  1662. ...
  1663. ...
  1664. \end{lstlisting}
  1665. \end{minipage}
  1666. \begin{minipage}{0.45\textwidth}
  1667. \begin{lstlisting}
  1668. def InterpRif(InterpRVar):
  1669. def interp_exp(e):
  1670. match e:
  1671. case IfExp(cnd, thn, els):
  1672. match self.interp_exp(cnd):
  1673. case True:
  1674. return self.interp_exp(thn)
  1675. case False:
  1676. return self.interp_exp(els)
  1677. ...
  1678. case _:
  1679. return super().interp_exp(e)
  1680. ...
  1681. \end{lstlisting}
  1682. \end{minipage}
  1683. \fi}
  1684. \end{center}
  1685. Getting back to the troublesome example, repeated here:
  1686. {\if\edition\racketEd\color{olive}
  1687. \begin{lstlisting}
  1688. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1689. \end{lstlisting}
  1690. \fi}
  1691. {\if\edition\pythonEd\color{purple}
  1692. \begin{lstlisting}
  1693. -(42 if True else 0)
  1694. \end{lstlisting}
  1695. \fi}
  1696. \noindent We can invoke the \code{interp\_exp} method for \LangIf{} on this
  1697. expression, call it \code{e0}, by creating an object of the \LangIf{} class
  1698. and calling the \code{interp\_exp} method.
  1699. {\if\edition\racketEd\color{olive}
  1700. \begin{lstlisting}
  1701. (send (new interp_Rif_class) interp_exp e0)
  1702. \end{lstlisting}
  1703. \fi}
  1704. {\if\edition\pythonEd\color{purple}
  1705. \begin{lstlisting}
  1706. InterpRif().interp_exp(e0)
  1707. \end{lstlisting}
  1708. \fi}
  1709. \noindent The default case of \code{interp\_exp} in \LangIf{} handles it by
  1710. dispatching to the \code{interp\_exp} method in \LangVar{}, which
  1711. handles the \code{-} operator. But then for the recursive method call,
  1712. it dispatches back to \code{interp\_exp} in \LangIf{}, where the
  1713. \code{If} is handled correctly. Thus, method overriding gives us the
  1714. open recursion that we need to implement our interpreters in an
  1715. extensible way.
  1716. \subsection{Definitional Interpreter for \LangVar{}}
  1717. {\if\edition\racketEd\color{olive}
  1718. \begin{figure}[tp]
  1719. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1720. \small
  1721. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1722. An \emph{association list} (alist) is a list of key-value pairs.
  1723. For example, we can map people to their ages with an alist.
  1724. \index{subject}{alist}\index{subject}{association list}
  1725. \begin{lstlisting}[basicstyle=\ttfamily]
  1726. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1727. \end{lstlisting}
  1728. The \emph{dictionary} interface is for mapping keys to values.
  1729. Every alist implements this interface. \index{subject}{dictionary} The package
  1730. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1731. provides many functions for working with dictionaries. Here
  1732. are a few of them:
  1733. \begin{description}
  1734. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1735. returns the value associated with the given $\itm{key}$.
  1736. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1737. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1738. but otherwise is the same as $\itm{dict}$.
  1739. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1740. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1741. of keys and values in $\itm{dict}$. For example, the following
  1742. creates a new alist in which the ages are incremented.
  1743. \end{description}
  1744. \vspace{-10pt}
  1745. \begin{lstlisting}[basicstyle=\ttfamily]
  1746. (for/list ([(k v) (in-dict ages)])
  1747. (cons k (add1 v)))
  1748. \end{lstlisting}
  1749. \end{tcolorbox}
  1750. %\end{wrapfigure}
  1751. \caption{Association lists implement the dictionary interface.}
  1752. \label{fig:alist}
  1753. \end{figure}
  1754. \fi}
  1755. Having justified the use of classes and methods to implement
  1756. interpreters, we turn to the definitional interpreter for \LangVar{}
  1757. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1758. \LangInt{} but adds two new \key{match} cases for variables and
  1759. \racket{\key{let}}\python{assignment}. For
  1760. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1761. value bound to a variable to all the uses of the variable. To
  1762. accomplish this, we maintain a mapping from variables to
  1763. values. Throughout the compiler we often need to map variables to
  1764. information about them. We refer to these mappings as
  1765. \emph{environments}\index{subject}{environment}.\footnote{Another
  1766. common term for environment in the compiler literature is \emph{symbol
  1767. table}\index{subject}{symbol table}.}
  1768. %
  1769. We use \racket{an association list
  1770. (alist)}\python{\href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}} to represent the
  1771. environment. \racket{Figure~\ref{fig:alist} gives a brief introduction
  1772. to alists and the \code{racket/dict} package.} The
  1773. \code{interp\_exp} function takes the current environment, \code{env},
  1774. as an extra parameter. When the interpreter encounters a variable, it
  1775. looks up the corresponding value in the dictionary.
  1776. %
  1777. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1778. initializing expression, extends the environment with the result
  1779. value bound to the variable, using \code{dict-set}, then evaluates
  1780. the body of the \key{Let}.}
  1781. %
  1782. \python{When the interpreter encounters an assignment, it evaluates
  1783. the initializing expression and then associates the resulting value
  1784. with the variable in the environment.}
  1785. \begin{figure}[tp]
  1786. {\if\edition\racketEd\color{olive}
  1787. \begin{lstlisting}
  1788. (define interp_Rvar_class
  1789. (class object%
  1790. (super-new)
  1791. (define/public ((interp_exp env) e)
  1792. (match e
  1793. [(Int n) n]
  1794. [(Prim 'read '())
  1795. (define r (read))
  1796. (cond [(fixnum? r) r]
  1797. [else (error 'interp_exp "expected an integer" r)])]
  1798. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1799. [(Prim '+ (list e1 e2))
  1800. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1801. [(Var x) (dict-ref env x)]
  1802. [(Let x e body)
  1803. (define new-env (dict-set env x ((interp_exp env) e)))
  1804. ((interp_exp new-env) body)]))
  1805. (define/public (interp_program p)
  1806. (match p
  1807. [(Program '() e) ((interp_exp '()) e)]))
  1808. ))
  1809. (define (interp_Rvar p)
  1810. (send (new interp_Rvar_class) interp_program p))
  1811. \end{lstlisting}
  1812. \fi}
  1813. {\if\edition\pythonEd\color{purple}
  1814. \begin{lstlisting}
  1815. class InterpPvar:
  1816. def interp_exp(self, e, env):
  1817. match e:
  1818. case BinOp(left, Add(), right):
  1819. l = self.interp_exp(left, env)
  1820. r = self.interp_exp(right, env)
  1821. return l + r
  1822. case UnaryOp(USub(), v):
  1823. return - self.interp_exp(v, env)
  1824. case Name(id):
  1825. return env[id]
  1826. case Constant(value):
  1827. return value
  1828. case Call(Name('input_int'), []):
  1829. return int(input())
  1830. def interp_stmts(self, ss, env):
  1831. if len(ss) == 0:
  1832. return
  1833. match ss[0]:
  1834. case Assign([lhs], value):
  1835. env[lhs.id] = self.interp_exp(value, env)
  1836. return self.interp_stmts(ss[1:], env)
  1837. case Expr(Call(Name('print'), [arg])):
  1838. print(self.interp_exp(arg, env), end='')
  1839. return self.interp_stmts(ss[1:], env)
  1840. case Expr(value):
  1841. self.interp_exp(value, env)
  1842. return self.interp_stmts(ss[1:], env)
  1843. def interp_P(self, p):
  1844. match p:
  1845. case Module(body):
  1846. self.interp_stmts(body, {})
  1847. \end{lstlisting}
  1848. \fi}
  1849. \caption{Interpreter for the \LangVar{} language.}
  1850. \label{fig:interp-Rvar}
  1851. \end{figure}
  1852. The goal for this chapter is to implement a compiler that translates
  1853. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1854. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1855. computer as the $P_1$ program interpreted by \code{interp\_Rvar}. That
  1856. is, they output the same integer $n$. We depict this correctness
  1857. criteria in the following diagram.
  1858. \[
  1859. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1860. \node (p1) at (0, 0) {$P_1$};
  1861. \node (p2) at (4, 0) {$P_2$};
  1862. \node (o) at (4, -2) {$n$};
  1863. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1864. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Rvar}} (o);
  1865. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  1866. \end{tikzpicture}
  1867. \]
  1868. In the next section we introduce the \LangXInt{} subset of x86 that
  1869. suffices for compiling \LangVar{}.
  1870. \section{The \LangXInt{} Assembly Language}
  1871. \label{sec:x86}
  1872. \index{subject}{x86}
  1873. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1874. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1875. assembler.
  1876. %
  1877. A program begins with a \code{main} label followed by a sequence of
  1878. instructions. The \key{globl} directive says that the \key{main}
  1879. procedure is externally visible, which is necessary so that the
  1880. operating system can call it. In the grammar, ellipses such as
  1881. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1882. \ldots$ is a sequence of instructions.\index{subject}{instruction}
  1883. %
  1884. An x86 program is stored in the computer's memory. For our purposes,
  1885. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1886. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1887. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1888. the address of the next instruction to be executed. For most
  1889. instructions, the program counter is incremented after the instruction
  1890. is executed, so it points to the next instruction in memory. Most x86
  1891. instructions take two operands, where each operand is either an
  1892. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1893. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1894. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  1895. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  1896. && \key{r8} \MID \key{r9} \MID \key{r10}
  1897. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  1898. \MID \key{r14} \MID \key{r15}}
  1899. \begin{figure}[tp]
  1900. \fbox{
  1901. \begin{minipage}{0.96\textwidth}
  1902. \[
  1903. \begin{array}{lcl}
  1904. \Reg &::=& \allregisters{} \\
  1905. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  1906. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  1907. \key{subq} \; \Arg\key{,} \Arg \MID
  1908. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  1909. && \key{callq} \; \mathit{label} \MID
  1910. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  1911. && \itm{label}\key{:}\; \Instr \\
  1912. \LangXIntM{} &::= & \key{.globl main}\\
  1913. & & \key{main:} \; \Instr\ldots
  1914. \end{array}
  1915. \]
  1916. \end{minipage}
  1917. }
  1918. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1919. \label{fig:x86-int-concrete}
  1920. \end{figure}
  1921. A register is a special kind of variable. Each one holds a 64-bit
  1922. value; there are 16 general-purpose registers in the computer and
  1923. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1924. is written with a \key{\%} followed by the register name, such as
  1925. \key{\%rax}.
  1926. An immediate value is written using the notation \key{\$}$n$ where $n$
  1927. is an integer.
  1928. %
  1929. %
  1930. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1931. which obtains the address stored in register $r$ and then adds $n$
  1932. bytes to the address. The resulting address is used to load or store
  1933. to memory depending on whether it occurs as a source or destination
  1934. argument of an instruction.
  1935. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1936. source $s$ and destination $d$, applies the arithmetic operation, then
  1937. writes the result back to the destination $d$.
  1938. %
  1939. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1940. stores the result in $d$.
  1941. %
  1942. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1943. specified by the label and $\key{retq}$ returns from a procedure to
  1944. its caller.
  1945. %
  1946. We discuss procedure calls in more detail later in this chapter and in
  1947. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1948. updates the program counter to the address of the instruction after
  1949. the specified label.
  1950. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1951. all of the x86 instructions used in this book.
  1952. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  1953. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  1954. \lstinline{movq $10, %rax}
  1955. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1956. adds $32$ to the $10$ in \key{rax} and
  1957. puts the result, $42$, back into \key{rax}.
  1958. %
  1959. The last instruction, \key{retq}, finishes the \key{main} function by
  1960. returning the integer in \key{rax} to the operating system. The
  1961. operating system interprets this integer as the program's exit
  1962. code. By convention, an exit code of 0 indicates that a program
  1963. completed successfully, and all other exit codes indicate various
  1964. errors. Nevertheless, in this book we return the result of the program
  1965. as the exit code.
  1966. \begin{figure}[tbp]
  1967. \begin{lstlisting}
  1968. .globl main
  1969. main:
  1970. movq $10, %rax
  1971. addq $32, %rax
  1972. retq
  1973. \end{lstlisting}
  1974. \caption{An x86 program that computes
  1975. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  1976. \label{fig:p0-x86}
  1977. \end{figure}
  1978. The x86 assembly language varies in a couple of ways depending on what
  1979. operating system it is assembled in. The code examples shown here are
  1980. correct on Linux and most Unix-like platforms, but when assembled on
  1981. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1982. as in \key{\_main}.
  1983. We exhibit the use of memory for storing intermediate results in the
  1984. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  1985. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  1986. uses a region of memory called the \emph{procedure call stack} (or
  1987. \emph{stack} for
  1988. short). \index{subject}{stack}\index{subject}{procedure call stack}
  1989. The stack consists of a separate \emph{frame}\index{subject}{frame}
  1990. for each procedure call. The memory layout for an individual frame is
  1991. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1992. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  1993. item at the top of the stack. The stack grows downward in memory, so
  1994. we increase the size of the stack by subtracting from the stack
  1995. pointer. In the context of a procedure call, the \emph{return
  1996. address}\index{subject}{return address} is the instruction after the
  1997. call instruction on the caller side. The function call instruction,
  1998. \code{callq}, pushes the return address onto the stack prior to
  1999. jumping to the procedure. The register \key{rbp} is the \emph{base
  2000. pointer}\index{subject}{base pointer} and is used to access variables
  2001. that are stored in the frame of the current procedure call. The base
  2002. pointer of the caller is pushed onto the stack after the return
  2003. address and then the base pointer is set to the location of the old
  2004. base pointer. In Figure~\ref{fig:frame} we number the variables from
  2005. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  2006. variable $2$ at $-16\key{(\%rbp)}$, etc.
  2007. \begin{figure}[tbp]
  2008. \begin{lstlisting}
  2009. start:
  2010. movq $10, -8(%rbp)
  2011. negq -8(%rbp)
  2012. movq -8(%rbp), %rax
  2013. addq $52, %rax
  2014. jmp conclusion
  2015. .globl main
  2016. main:
  2017. pushq %rbp
  2018. movq %rsp, %rbp
  2019. subq $16, %rsp
  2020. jmp start
  2021. conclusion:
  2022. addq $16, %rsp
  2023. popq %rbp
  2024. retq
  2025. \end{lstlisting}
  2026. \caption{An x86 program that computes
  2027. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2028. \label{fig:p1-x86}
  2029. \end{figure}
  2030. \begin{figure}[tbp]
  2031. \centering
  2032. \begin{tabular}{|r|l|} \hline
  2033. Position & Contents \\ \hline
  2034. 8(\key{\%rbp}) & return address \\
  2035. 0(\key{\%rbp}) & old \key{rbp} \\
  2036. -8(\key{\%rbp}) & variable $1$ \\
  2037. -16(\key{\%rbp}) & variable $2$ \\
  2038. \ldots & \ldots \\
  2039. 0(\key{\%rsp}) & variable $n$\\ \hline
  2040. \end{tabular}
  2041. \caption{Memory layout of a frame.}
  2042. \label{fig:frame}
  2043. \end{figure}
  2044. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2045. control is transferred from the operating system to the \code{main}
  2046. function. The operating system issues a \code{callq main} instruction
  2047. which pushes its return address on the stack and then jumps to
  2048. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2049. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2050. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2051. alignment (because the \code{callq} pushed the return address). The
  2052. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2053. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2054. pointer for the caller onto the stack and subtracts $8$ from the stack
  2055. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  2056. base pointer so that it points the location of the old base
  2057. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2058. pointer down to make enough room for storing variables. This program
  2059. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2060. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2061. functions. The last instruction of the prelude is \code{jmp start},
  2062. which transfers control to the instructions that were generated from
  2063. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.
  2064. The first instruction under the \code{start} label is
  2065. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2066. %
  2067. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2068. %
  2069. The next instruction moves the $-10$ from variable $1$ into the
  2070. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2071. the value in \code{rax}, updating its contents to $42$.
  2072. The three instructions under the label \code{conclusion} are the
  2073. typical \emph{conclusion}\index{subject}{conclusion} of a procedure. The first
  2074. two instructions restore the \code{rsp} and \code{rbp} registers to
  2075. the state they were in at the beginning of the procedure. The
  2076. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  2077. point at the old base pointer. Then \key{popq \%rbp} returns the old
  2078. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  2079. instruction, \key{retq}, jumps back to the procedure that called this
  2080. one and adds $8$ to the stack pointer.
  2081. The compiler needs a convenient representation for manipulating x86
  2082. programs, so we define an abstract syntax for x86 in
  2083. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2084. \LangXInt{}.
  2085. %
  2086. {\if\edition\racketEd\color{olive}
  2087. The main difference compared to the concrete syntax of \LangXInt{}
  2088. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2089. front of every instruction. Instead instructions are grouped into
  2090. \emph{blocks}\index{subject}{block}\index{subject}{basic block} with a
  2091. label associated with every block, which is why the \key{X86Program}
  2092. struct includes an alist mapping labels to blocks. The reason for this
  2093. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  2094. introduce conditional branching. The \code{Block} structure includes
  2095. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2096. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  2097. $\itm{info}$ field should contain an empty list.
  2098. \fi}
  2099. %
  2100. {\if\edition\pythonEd\color{purple}
  2101. %
  2102. The main difference compared to the concrete syntax of \LangXInt{}
  2103. (Figure~\ref{fig:x86-int-concrete}) is that we do not yet include a
  2104. way to label instructions but instead recommend inserting the
  2105. \key{main}, \key{start}, and \key{conclusion} labels when printing the
  2106. final x86 program.
  2107. %
  2108. \fi}
  2109. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2110. node includes an integer for representing the arity of the function,
  2111. i.e., the number of arguments, which is helpful to know during
  2112. register allocation (Chapter~\ref{ch:register-allocation-Rvar}).
  2113. \begin{figure}[tp]
  2114. \fbox{
  2115. \begin{minipage}{0.98\textwidth}
  2116. \small
  2117. {\if\edition\racketEd\color{olive}
  2118. \[
  2119. \begin{array}{lcl}
  2120. \Reg &::=& \allregisters{} \\
  2121. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2122. \MID \DEREF{\Reg}{\Int} \\
  2123. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2124. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2125. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2126. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2127. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2128. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2129. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2130. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2131. \end{array}
  2132. \]
  2133. \fi}
  2134. {\if\edition\pythonEd\color{purple}
  2135. \[
  2136. \begin{array}{lcl}
  2137. \Reg &::=& \allregisters{} \\
  2138. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2139. \MID \DEREF{\Reg}{\Int} \\
  2140. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2141. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2142. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2143. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2144. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2145. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2146. \LangXIntM{} &::= & \XPROGRAM{\Instr^{*}}{}
  2147. \end{array}
  2148. \]
  2149. \fi}
  2150. \end{minipage}
  2151. }
  2152. \caption{The abstract syntax of \LangXInt{} assembly.}
  2153. \label{fig:x86-int-ast}
  2154. \end{figure}
  2155. \section{Planning the trip to x86 via the \LangCVar{} language}
  2156. \label{sec:plan-s0-x86}
  2157. To compile one language to another it helps to focus on the
  2158. differences between the two languages because the compiler will need
  2159. to bridge those differences. What are the differences between \LangVar{}
  2160. and x86 assembly? Here are some of the most important ones:
  2161. \begin{enumerate}
  2162. \item[(a)] x86 arithmetic instructions typically have two arguments
  2163. and update the second argument in place. In contrast, \LangVar{}
  2164. arithmetic operations take two arguments and produce a new value.
  2165. An x86 instruction may have at most one memory-accessing argument.
  2166. Furthermore, some instructions place special restrictions on their
  2167. arguments.
  2168. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  2169. expression, whereas x86 instructions restrict their arguments to be
  2170. integer constants, registers, and memory locations.
  2171. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  2172. sequence of instructions and jumps to labeled positions, whereas in
  2173. \LangVar{} the order of evaluation is a left-to-right depth-first
  2174. traversal of the abstract syntax tree.
  2175. \item[(d)] A program in \LangVar{} can have any number of variables
  2176. whereas x86 has 16 registers and the procedure calls stack.
  2177. {\if\edition\racketEd\color{olive}
  2178. \item[(e)] Variables in \LangVar{} can shadow other variables with the
  2179. same name. In x86, registers have unique names and memory locations
  2180. have unique addresses.
  2181. \fi}
  2182. \end{enumerate}
  2183. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  2184. the problem into several steps, dealing with the above differences one
  2185. at a time. Each of these steps is called a \emph{pass} of the
  2186. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2187. %
  2188. This terminology comes from the way each step passes over the AST of
  2189. the program.
  2190. %
  2191. We begin by sketching how we might implement each pass, and give them
  2192. names. We then figure out an ordering of the passes and the
  2193. input/output language for each pass. The very first pass has
  2194. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2195. its output language. In between we can choose whichever language is
  2196. most convenient for expressing the output of each pass, whether that
  2197. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2198. our own design. Finally, to implement each pass we write one
  2199. recursive function per non-terminal in the grammar of the input
  2200. language of the pass. \index{subject}{intermediate language}
  2201. \begin{description}
  2202. \item[\key{select\_instructions}] handles the difference between
  2203. \LangVar{} operations and x86 instructions. This pass converts each
  2204. \LangVar{} operation to a short sequence of instructions that
  2205. accomplishes the same task.
  2206. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2207. of a primitive operation or function call is a variable or integer,
  2208. that is, an \emph{atomic} expression. We refer to non-atomic
  2209. expressions as \emph{complex}. This pass introduces temporary
  2210. variables to hold the results of complex
  2211. subexpressions.\index{subject}{atomic
  2212. expression}\index{subject}{complex expression}%
  2213. \footnote{The subexpressions of an operation are often called
  2214. operators and operands which explains the presence of
  2215. \code{opera*} in the name of this pass.}
  2216. {\if\edition\racketEd\color{olive}
  2217. \item[\key{explicate\_control}] makes the execution order of the
  2218. program explicit. It convert the abstract syntax tree representation
  2219. into a control-flow graph in which each node contains a sequence of
  2220. statements and the edges between nodes say which nodes contain jumps
  2221. to other nodes.
  2222. \fi}
  2223. \item[\key{assign\_homes}] replaces the variables in \LangVar{} with
  2224. registers or stack locations in x86.
  2225. {\if\edition\racketEd\color{olive}
  2226. \item[\key{uniquify}] deals with the shadowing of variables by
  2227. renaming every variable to a unique name.
  2228. \fi}
  2229. \end{description}
  2230. The next question is: in what order should we apply these passes? This
  2231. question can be challenging because it is difficult to know ahead of
  2232. time which orderings will be better (easier to implement, produce more
  2233. efficient code, etc.) so oftentimes trial-and-error is
  2234. involved. Nevertheless, we can try to plan ahead and make educated
  2235. choices regarding the ordering.
  2236. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2237. \key{uniquify}? The \key{uniquify} pass should come first because
  2238. \key{explicate\_control} changes all the \key{let}-bound variables to
  2239. become local variables whose scope is the entire program, which would
  2240. confuse variables with the same name.}
  2241. %
  2242. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2243. because the later removes the \key{let} form, but it is convenient to
  2244. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2245. %
  2246. \racket{The ordering of \key{uniquify} with respect to
  2247. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2248. \key{uniquify} to come first.}
  2249. The \key{select\_instructions} and \key{assign\_homes}. passes are
  2250. intertwined. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers
  2251. are used for passing arguments to functions and it is preferable to
  2252. assign parameters to their corresponding registers. On the other hand,
  2253. by selecting instructions first we may run into a dead end in
  2254. \key{assign\_homes}. Recall that only one argument of an x86
  2255. instruction may be a memory access but \key{assign\_homes} might fail
  2256. to assign even one of them to a register.
  2257. %
  2258. A sophisticated approach is to iteratively repeat the two passes until
  2259. a solution is found. However, to reduce implementation complexity we
  2260. recommend a simpler approach in which \key{select\_instructions} comes
  2261. first, followed by the \key{assign\_homes}, then a third pass named
  2262. \key{patch\_instructions} that uses a reserved register to fix
  2263. outstanding problems.
  2264. \begin{figure}[tbp]
  2265. {\if\edition\racketEd\color{olive}
  2266. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2267. \node (Rvar) at (0,2) {\large \LangVar{}};
  2268. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2269. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  2270. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2271. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2272. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2273. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2274. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2275. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2276. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  2277. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-3);
  2278. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2279. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2280. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2281. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2282. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print\_x86} (x86-5);
  2283. \end{tikzpicture}
  2284. \fi}
  2285. {\if\edition\pythonEd\color{purple}
  2286. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2287. \node (Rvar) at (0,2) {\large \LangVar{}};
  2288. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2289. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2290. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2291. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2292. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2293. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-2);
  2294. \path[->,bend right=15] (Rvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2295. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2296. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2297. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86} (x86-4);
  2298. \end{tikzpicture}
  2299. \fi}
  2300. \caption{Diagram of the passes for compiling \LangVar{}. }
  2301. \label{fig:Rvar-passes}
  2302. \end{figure}
  2303. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  2304. passes and identifies the input and output language of each pass. The
  2305. last pass, \key{print\_x86}, converts from the abstract syntax of
  2306. \LangXInt{} to the concrete syntax.
  2307. %
  2308. \racket{In the following two sections we discuss the \LangCVar{}
  2309. intermediate language and the \LangXVar{} dialect of x86.}
  2310. %
  2311. \python{In the following section we discuss the \LangXVar{} dialect of
  2312. x86.}
  2313. %
  2314. The remainder of this chapter gives hints regarding the implementation
  2315. of each of the compiler passes in Figure~\ref{fig:Rvar-passes}.
  2316. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2317. %% are programs that are still in the \LangVar{} language, though the
  2318. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2319. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  2320. %% %
  2321. %% The output of \key{explicate-control} is in an intermediate language
  2322. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2323. %% syntax, which we introduce in the next section. The
  2324. %% \key{select-instruction} pass translates from \LangCVar{} to
  2325. %% \LangXVar{}. The \key{assign-homes} and
  2326. %% \key{patch-instructions}
  2327. %% passes input and output variants of x86 assembly.
  2328. {\if\edition\racketEd\color{olive}
  2329. \subsection{The \LangCVar{} Intermediate Language}
  2330. The output of \key{explicate-control} is similar to the $C$
  2331. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2332. categories for expressions and statements, so we name it \LangCVar{}. The
  2333. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2334. (The concrete syntax for \LangCVar{} is in the Appendix,
  2335. Figure~\ref{fig:c0-concrete-syntax}.)
  2336. %
  2337. The \LangCVar{} language supports the same operators as \LangVar{} but
  2338. the arguments of operators are restricted to atomic
  2339. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2340. assignment statements which can be executed in sequence using the
  2341. \key{Seq} form. A sequence of statements always ends with
  2342. \key{Return}, a guarantee that is baked into the grammar rules for
  2343. \itm{tail}. The naming of this non-terminal comes from the term
  2344. \emph{tail position}\index{subject}{tail position}, which refers to an
  2345. expression that is the last one to execute within a function.
  2346. A \LangCVar{} program consists of a control-flow graph represented as
  2347. an alist mapping labels to tails. This is more general than necessary
  2348. for the present chapter, as we do not yet introduce \key{goto} for
  2349. jumping to labels, but it saves us from having to change the syntax in
  2350. Chapter~\ref{ch:Rif}. For now there will be just one label,
  2351. \key{start}, and the whole program is its tail.
  2352. %
  2353. The $\itm{info}$ field of the \key{CProgram} form, after the
  2354. \key{explicate-control} pass, contains a mapping from the symbol
  2355. \key{locals} to a list of variables, that is, a list of all the
  2356. variables used in the program. At the start of the program, these
  2357. variables are uninitialized; they become initialized on their first
  2358. assignment.
  2359. \begin{figure}[tbp]
  2360. \fbox{
  2361. \begin{minipage}{0.96\textwidth}
  2362. \[
  2363. \begin{array}{lcl}
  2364. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2365. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2366. &\MID& \ADD{\Atm}{\Atm}\\
  2367. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2368. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2369. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2370. \end{array}
  2371. \]
  2372. \end{minipage}
  2373. }
  2374. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2375. \label{fig:c0-syntax}
  2376. \end{figure}
  2377. The definitional interpreter for \LangCVar{} is in the support code,
  2378. in the file \code{interp-Cvar.rkt}.
  2379. \fi}
  2380. \section{The \LangXVar{} dialect}
  2381. The \LangXVar{} language is the output of the pass
  2382. \key{select\_instructions}. It extends \LangXInt{} with an unbounded
  2383. number of program-scope variables and removes the restrictions
  2384. regarding instruction arguments.
  2385. {\if\edition\racketEd\color{olive}
  2386. \section{Uniquify Variables}
  2387. \label{sec:uniquify-Rvar}
  2388. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2389. programs in which every \key{let} binds a unique variable name. For
  2390. example, the \code{uniquify} pass should translate the program on the
  2391. left into the program on the right.
  2392. \begin{transformation}
  2393. \begin{lstlisting}
  2394. (let ([x 32])
  2395. (+ (let ([x 10]) x) x))
  2396. \end{lstlisting}
  2397. \compilesto
  2398. \begin{lstlisting}
  2399. (let ([x.1 32])
  2400. (+ (let ([x.2 10]) x.2) x.1))
  2401. \end{lstlisting}
  2402. \end{transformation}
  2403. The following is another example translation, this time of a program
  2404. with a \key{let} nested inside the initializing expression of another
  2405. \key{let}.
  2406. \begin{transformation}
  2407. \begin{lstlisting}
  2408. (let ([x (let ([x 4])
  2409. (+ x 1))])
  2410. (+ x 2))
  2411. \end{lstlisting}
  2412. \compilesto
  2413. \begin{lstlisting}
  2414. (let ([x.2 (let ([x.1 4])
  2415. (+ x.1 1))])
  2416. (+ x.2 2))
  2417. \end{lstlisting}
  2418. \end{transformation}
  2419. We recommend implementing \code{uniquify} by creating a structurally
  2420. recursive function named \code{uniquify-exp} that mostly just copies
  2421. an expression. However, when encountering a \key{let}, it should
  2422. generate a unique name for the variable and associate the old name
  2423. with the new name in an alist.\footnote{The Racket function
  2424. \code{gensym} is handy for generating unique variable names.} The
  2425. \code{uniquify-exp} function needs to access this alist when it gets
  2426. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2427. for the alist.
  2428. The skeleton of the \code{uniquify-exp} function is shown in
  2429. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  2430. convenient to partially apply it to an alist and then apply it to
  2431. different expressions, as in the last case for primitive operations in
  2432. Figure~\ref{fig:uniquify-Rvar}. The
  2433. %
  2434. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2435. %
  2436. form of Racket is useful for transforming each element of a list to
  2437. produce a new list.\index{subject}{for/list}
  2438. \begin{figure}[tbp]
  2439. \begin{lstlisting}
  2440. (define (uniquify-exp env)
  2441. (lambda (e)
  2442. (match e
  2443. [(Var x) ___]
  2444. [(Int n) (Int n)]
  2445. [(Let x e body) ___]
  2446. [(Prim op es)
  2447. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2448. (define (uniquify p)
  2449. (match p
  2450. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2451. \end{lstlisting}
  2452. \caption{Skeleton for the \key{uniquify} pass.}
  2453. \label{fig:uniquify-Rvar}
  2454. \end{figure}
  2455. \begin{exercise}
  2456. \normalfont % I don't like the italics for exercises. -Jeremy
  2457. Complete the \code{uniquify} pass by filling in the blanks in
  2458. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  2459. variables and for the \key{let} form in the file \code{compiler.rkt}
  2460. in the support code.
  2461. \end{exercise}
  2462. \begin{exercise}
  2463. \normalfont % I don't like the italics for exercises. -Jeremy
  2464. \label{ex:Rvar}
  2465. Create five \LangVar{} programs that exercise the most interesting
  2466. parts of the \key{uniquify} pass, that is, the programs should include
  2467. \key{let} forms, variables, and variables that shadow each other.
  2468. The five programs should be placed in the subdirectory named
  2469. \key{tests} and the file names should start with \code{var\_test\_}
  2470. followed by a unique integer and end with the file extension
  2471. \key{.rkt}.
  2472. %
  2473. The \key{run-tests.rkt} script in the support code checks whether the
  2474. output programs produce the same result as the input programs. The
  2475. script uses the \key{interp-tests} function
  2476. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2477. your \key{uniquify} pass on the example programs. The \code{passes}
  2478. parameter of \key{interp-tests} is a list that should have one entry
  2479. for each pass in your compiler. For now, define \code{passes} to
  2480. contain just one entry for \code{uniquify} as shown below.
  2481. \begin{lstlisting}
  2482. (define passes
  2483. (list (list "uniquify" uniquify interp_Rvar type-check-Rvar)))
  2484. \end{lstlisting}
  2485. Run the \key{run-tests.rkt} script in the support code to check
  2486. whether the output programs produce the same result as the input
  2487. programs.
  2488. \end{exercise}
  2489. \fi}
  2490. \section{Remove Complex Operands}
  2491. \label{sec:remove-complex-opera-Rvar}
  2492. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2493. into a restricted form in which the arguments of operations are atomic
  2494. expressions. Put another way, this pass removes complex
  2495. operands\index{subject}{complex operand}, such as the expression
  2496. \racket{\code{(- 10)}}\python{\code{-10}}
  2497. in the program below. This is accomplished by introducing a new
  2498. temporary variable, assigning the complex operand to the new
  2499. variable, and then using the new variable in place of the complex
  2500. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2501. right.
  2502. {\if\edition\racketEd\color{olive}
  2503. \begin{transformation}
  2504. % var_test_19.rkt
  2505. \begin{lstlisting}
  2506. (let ([x (+ 42 (- 10))])
  2507. (+ x 10))
  2508. \end{lstlisting}
  2509. \compilesto
  2510. \begin{lstlisting}
  2511. (let ([x (let ([tmp.1 (- 10)])
  2512. (+ 42 tmp.1))])
  2513. (+ x 10))
  2514. \end{lstlisting}
  2515. \end{transformation}
  2516. \fi}
  2517. {\if\edition\pythonEd\color{purple}
  2518. \begin{transformation}
  2519. \begin{lstlisting}
  2520. x = 42 + -10
  2521. print(x + 10)
  2522. \end{lstlisting}
  2523. \compilesto
  2524. \begin{lstlisting}
  2525. tmp_0 = -10
  2526. x = 42 + tmp_0
  2527. tmp_1 = x + 10
  2528. print(tmp_1)
  2529. \end{lstlisting}
  2530. \end{transformation}
  2531. \fi}
  2532. \begin{figure}[tp]
  2533. \centering
  2534. \fbox{
  2535. \begin{minipage}{0.96\textwidth}
  2536. {\if\edition\racketEd\color{olive}
  2537. \[
  2538. \begin{array}{rcl}
  2539. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2540. \Exp &::=& \Atm \MID \READ{} \\
  2541. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2542. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2543. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2544. \end{array}
  2545. \]
  2546. \fi}
  2547. {\if\edition\pythonEd\color{purple}
  2548. \[
  2549. \begin{array}{rcl}
  2550. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2551. \Exp{} &::=& \Atm \MID \READ{} \\
  2552. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  2553. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2554. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2555. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2556. \end{array}
  2557. \]
  2558. \fi}
  2559. \end{minipage}
  2560. }
  2561. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2562. atomic expressions, like administrative normal form (ANF).}
  2563. \label{fig:Rvar-anf-syntax}
  2564. \end{figure}
  2565. Figure~\ref{fig:Rvar-anf-syntax} presents the grammar for the output of
  2566. this pass, the language \LangVarANF{}. The only difference is that
  2567. operator arguments are restricted to be atomic expressions that are
  2568. defined by the \Atm{} non-terminal. In particular, integer constants
  2569. and variables are atomic. In the literature, restricting arguments to
  2570. be atomic expressions is one of the ideas in \emph{administrative
  2571. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2572. \index{subject}{administrative normal form} \index{subject}{ANF}
  2573. {\if\edition\racketEd\color{olive}
  2574. We recommend implementing this pass with two mutually recursive
  2575. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2576. \code{rco\_atom} to subexpressions that need to become atomic and to
  2577. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2578. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2579. returns an expression. The \code{rco\_atom} function returns two
  2580. things: an atomic expression and an alist mapping temporary variables to
  2581. complex subexpressions. You can return multiple things from a function
  2582. using Racket's \key{values} form and you can receive multiple things
  2583. from a function call using the \key{define-values} form.
  2584. Also, the
  2585. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2586. form is useful for applying a function to each element of a list, in
  2587. the case where the function returns multiple values.
  2588. \index{subject}{for/lists}
  2589. \fi}
  2590. %
  2591. {\if\edition\pythonEd\color{purple}
  2592. %
  2593. We recommend implementing this pass with an auxiliary method named
  2594. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2595. Boolean that specifies whether the expression needs to become atomic
  2596. or not. The \code{rco\_exp} method should return a pair consisting of
  2597. the new expression and a list of pairs, associating new temporary
  2598. variables with their initializing expressions.
  2599. %
  2600. \fi}
  2601. {\if\edition\racketEd\color{olive}
  2602. Returning to the example program with the expression \code{(+ 42 (-
  2603. 10))}, the subexpression \code{(- 10)} should be processed using the
  2604. \code{rco\_atom} function because it is an argument of the \code{+} and
  2605. therefore needs to become atomic. The output of \code{rco\_atom}
  2606. applied to \code{(- 10)} is as follows.
  2607. \begin{transformation}
  2608. \begin{lstlisting}
  2609. (- 10)
  2610. \end{lstlisting}
  2611. \compilesto
  2612. \begin{lstlisting}
  2613. tmp.1
  2614. ((tmp.1 . (- 10)))
  2615. \end{lstlisting}
  2616. \end{transformation}
  2617. \fi}
  2618. %
  2619. {\if\edition\pythonEd\color{purple}
  2620. %
  2621. Returning to the example program with the expression \code{42 + -10},
  2622. the subexpression \code{-10} should be processed using the
  2623. \code{rco\_exp} function with \code{True} as the second argument
  2624. because \code{-10} is an argument of the \code{+} operator and
  2625. therefore needs to become atomic. The output of \code{rco\_exp}
  2626. applied to \code{-10} is as follows.
  2627. \begin{transformation}
  2628. \begin{lstlisting}
  2629. -10
  2630. \end{lstlisting}
  2631. \compilesto
  2632. \begin{lstlisting}
  2633. tmp_1
  2634. [(tmp_1, -10)]
  2635. \end{lstlisting}
  2636. \end{transformation}
  2637. %
  2638. \fi}
  2639. Take special care of programs such as the following that \racket{bind
  2640. a variable to an atomic expression}\python{assign an atomic
  2641. expression to a variable}. You should leave such \racket{variable
  2642. bindings}\python{assignments} unchanged, as shown in the program on
  2643. the right\\
  2644. %
  2645. {\if\edition\racketEd\color{olive}
  2646. \begin{transformation}
  2647. % var_test_20.rkt
  2648. \begin{lstlisting}
  2649. (let ([a 42])
  2650. (let ([b a])
  2651. b))
  2652. \end{lstlisting}
  2653. \compilesto
  2654. \begin{lstlisting}
  2655. (let ([a 42])
  2656. (let ([b a])
  2657. b))
  2658. \end{lstlisting}
  2659. \end{transformation}
  2660. \fi}
  2661. {\if\edition\pythonEd\color{purple}
  2662. \begin{transformation}
  2663. \begin{lstlisting}
  2664. a = 42
  2665. b = a
  2666. print(b)
  2667. \end{lstlisting}
  2668. \compilesto
  2669. \begin{lstlisting}
  2670. a = 42
  2671. b = a
  2672. print(b)
  2673. \end{lstlisting}
  2674. \end{transformation}
  2675. \fi}
  2676. A careless implementation might produce the following output with
  2677. unnecessary temporary variables.
  2678. \begin{center}
  2679. \begin{minipage}{0.4\textwidth}
  2680. {\if\edition\racketEd\color{olive}
  2681. \begin{lstlisting}
  2682. (let ([tmp.1 42])
  2683. (let ([a tmp.1])
  2684. (let ([tmp.2 a])
  2685. (let ([b tmp.2])
  2686. b))))
  2687. \end{lstlisting}
  2688. \fi}
  2689. {\if\edition\pythonEd\color{purple}
  2690. \begin{lstlisting}
  2691. tmp_1 = 42
  2692. a = tmp_1
  2693. tmp_2 = a
  2694. b = tmp_2
  2695. print(b)
  2696. \end{lstlisting}
  2697. \fi}
  2698. \end{minipage}
  2699. \end{center}
  2700. \begin{exercise}
  2701. \normalfont
  2702. {\if\edition\racketEd\color{olive}
  2703. Implement the \code{remove-complex-opera*} function in
  2704. \code{compiler.rkt}.
  2705. %
  2706. Create three new \LangVar{} programs that exercise the interesting
  2707. code in the \code{remove-complex-opera*} pass. Follow the guidelines
  2708. regarding file names described in Exercise~\ref{ex:Rvar}.
  2709. %
  2710. In the \code{run-tests.rkt} script, add the following entry to the
  2711. list of \code{passes} and then run the script to test your compiler.
  2712. \begin{lstlisting}
  2713. (list "remove-complex" remove-complex-opera* interp_Rvar type-check-Rvar)
  2714. \end{lstlisting}
  2715. While debugging your compiler, it is often useful to see the
  2716. intermediate programs that are output from each pass. To print the
  2717. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2718. \code{interp-tests} in \code{run-tests.rkt}.
  2719. \fi}
  2720. %
  2721. {\if\edition\pythonEd\color{purple}
  2722. Implement the \code{remove\_complex\_operands} function in
  2723. \code{compiler.py}, creating auxiliary functions for each
  2724. non-terminal in the grammar, i.e., \code{rco\_exp}
  2725. and \code{rco\_stmt}.
  2726. \fi}
  2727. \end{exercise}
  2728. {\if\edition\pythonEd\color{purple}
  2729. \begin{exercise}
  2730. \normalfont % I don't like the italics for exercises. -Jeremy
  2731. \label{ex:Rvar}
  2732. Create five \LangVar{} programs that exercise the most interesting
  2733. parts of the Remove Complex Operands pass. The five programs should
  2734. be placed in the subdirectory named \key{tests} and the file names
  2735. should start with \code{var\_test\_} followed by a unique integer and
  2736. end with the file extension \key{.py}.
  2737. % TODO: come up with passes infrastructure for Python -Jeremy
  2738. %% The \key{run-tests.rkt} script in the support code checks whether the
  2739. %% output programs produce the same result as the input programs. The
  2740. %% script uses the \key{interp-tests} function
  2741. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2742. %% your \key{uniquify} pass on the example programs. The \code{passes}
  2743. %% parameter of \key{interp-tests} is a list that should have one entry
  2744. %% for each pass in your compiler. For now, define \code{passes} to
  2745. %% contain just one entry for \code{uniquify} as shown below.
  2746. %% \begin{lstlisting}
  2747. %% (define passes
  2748. %% (list (list "uniquify" uniquify interp_Rvar type-check-Rvar)))
  2749. %% \end{lstlisting}
  2750. Run the \key{run-tests.py} script in the support code to check
  2751. whether the output programs produce the same result as the input
  2752. programs.
  2753. \end{exercise}
  2754. \fi}
  2755. {\if\edition\racketEd\color{olive}
  2756. \section{Explicate Control}
  2757. \label{sec:explicate-control-Rvar}
  2758. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2759. programs that make the order of execution explicit in their
  2760. syntax. For now this amounts to flattening \key{let} constructs into a
  2761. sequence of assignment statements. For example, consider the following
  2762. \LangVar{} program.\\
  2763. % var_test_11.rkt
  2764. \begin{minipage}{0.96\textwidth}
  2765. \begin{lstlisting}
  2766. (let ([y (let ([x 20])
  2767. (+ x (let ([x 22]) x)))])
  2768. y)
  2769. \end{lstlisting}
  2770. \end{minipage}\\
  2771. %
  2772. The output of the previous pass and of \code{explicate-control} is
  2773. shown below. Recall that the right-hand-side of a \key{let} executes
  2774. before its body, so the order of evaluation for this program is to
  2775. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2776. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2777. output of \code{explicate-control} makes this ordering explicit.
  2778. \begin{transformation}
  2779. \begin{lstlisting}
  2780. (let ([y (let ([x.1 20])
  2781. (let ([x.2 22])
  2782. (+ x.1 x.2)))])
  2783. y)
  2784. \end{lstlisting}
  2785. \compilesto
  2786. \begin{lstlisting}[language=C]
  2787. start:
  2788. x.1 = 20;
  2789. x.2 = 22;
  2790. y = (+ x.1 x.2);
  2791. return y;
  2792. \end{lstlisting}
  2793. \end{transformation}
  2794. \begin{figure}[tbp]
  2795. \begin{lstlisting}
  2796. (define (explicate-tail e)
  2797. (match e
  2798. [(Var x) ___]
  2799. [(Int n) (Return (Int n))]
  2800. [(Let x rhs body) ___]
  2801. [(Prim op es) ___]
  2802. [else (error "explicate-tail unhandled case" e)]))
  2803. (define (explicate-assign e x cont)
  2804. (match e
  2805. [(Var x) ___]
  2806. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2807. [(Let y rhs body) ___]
  2808. [(Prim op es) ___]
  2809. [else (error "explicate-assign unhandled case" e)]))
  2810. (define (explicate-control p)
  2811. (match p
  2812. [(Program info body) ___]))
  2813. \end{lstlisting}
  2814. \caption{Skeleton for the \key{explicate-control} pass.}
  2815. \label{fig:explicate-control-Rvar}
  2816. \end{figure}
  2817. The organization of this pass depends on the notion of tail position
  2818. that we have alluded to earlier.
  2819. \begin{definition}
  2820. The following rules define when an expression is in \textbf{\emph{tail
  2821. position}}\index{subject}{tail position} for the language \LangVar{}.
  2822. \begin{enumerate}
  2823. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2824. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2825. \end{enumerate}
  2826. \end{definition}
  2827. We recommend implementing \code{explicate-control} using two mutually
  2828. recursive functions, \code{explicate-tail} and
  2829. \code{explicate-assign}, as suggested in the skeleton code in
  2830. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2831. function should be applied to expressions in tail position whereas the
  2832. \code{explicate-assign} should be applied to expressions that occur on
  2833. the right-hand-side of a \key{let}.
  2834. %
  2835. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2836. input and produces a \Tail{} in \LangCVar{} (see
  2837. Figure~\ref{fig:c0-syntax}).
  2838. %
  2839. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2840. the variable that it is to be assigned to, and a \Tail{} in
  2841. \LangCVar{} for the code that comes after the assignment. The
  2842. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2843. The \code{explicate-assign} function is in accumulator-passing style:
  2844. the \code{cont} parameter is used for accumulating the output. This
  2845. accumulator-passing style plays an important role in how we generate
  2846. high-quality code for conditional expressions in Chapter~\ref{ch:Rif}.
  2847. \begin{exercise}\normalfont
  2848. %
  2849. Implement the \code{explicate-control} function in
  2850. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2851. exercise the code in \code{explicate-control}.
  2852. %
  2853. In the \code{run-tests.rkt} script, add the following entry to the
  2854. list of \code{passes} and then run the script to test your compiler.
  2855. \begin{lstlisting}
  2856. (list "explicate control" explicate-control interp_Cvar type-check-Cvar)
  2857. \end{lstlisting}
  2858. \end{exercise}
  2859. \fi}
  2860. \section{Select Instructions}
  2861. \label{sec:select-Rvar}
  2862. \index{subject}{instruction selection}
  2863. In the \code{select\_instructions} pass we begin the work of
  2864. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  2865. language of this pass is a variant of x86 that still uses variables,
  2866. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  2867. non-terminal of the \LangXInt{} abstract syntax
  2868. (Figure~\ref{fig:x86-int-ast}).
  2869. \racket{We recommend implementing the
  2870. \code{select\_instructions} with three auxiliary functions, one for
  2871. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  2872. $\Tail$.}
  2873. \python{We recommend implementing an auxiliary function
  2874. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  2875. \racket{
  2876. The cases for $\Atm$ are straightforward; variables stay
  2877. the same and integer constants change to immediates:
  2878. $\INT{n}$ changes to $\IMM{n}$.}
  2879. We consider the cases for the $\Stmt$ non-terminal, starting with
  2880. arithmetic operations. For example, consider the addition
  2881. operation. We can use the \key{addq} instruction, but it performs an
  2882. in-place update. So we could move $\itm{arg}_1$ into the left-hand
  2883. side \itm{var} and then add $\itm{arg}_2$ to \itm{var}.
  2884. \begin{transformation}
  2885. {\if\edition\racketEd\color{olive}
  2886. \begin{lstlisting}
  2887. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2888. \end{lstlisting}
  2889. \fi}
  2890. {\if\edition\pythonEd\color{purple}
  2891. \begin{lstlisting}
  2892. |$\itm{var}$| = |$\itm{arg}_1$| + |$\itm{arg}_2$|
  2893. \end{lstlisting}
  2894. \fi}
  2895. \compilesto
  2896. \begin{lstlisting}
  2897. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2898. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2899. \end{lstlisting}
  2900. \end{transformation}
  2901. There are also cases that require special care to avoid generating
  2902. needlessly complicated code. For example, if one of the arguments of
  2903. the addition is the same variable as the left-hand side of the
  2904. assignment, then there is no need for the extra move instruction. The
  2905. assignment statement can be translated into a single \key{addq}
  2906. instruction as follows.
  2907. \begin{transformation}
  2908. {\if\edition\racketEd\color{olive}
  2909. \begin{lstlisting}
  2910. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2911. \end{lstlisting}
  2912. \fi}
  2913. {\if\edition\pythonEd\color{purple}
  2914. \begin{lstlisting}
  2915. |$\itm{var}$| = |$\itm{arg}_1$| + |$\itm{var}$|
  2916. \end{lstlisting}
  2917. \fi}
  2918. \compilesto
  2919. \begin{lstlisting}
  2920. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2921. \end{lstlisting}
  2922. \end{transformation}
  2923. The \key{read} operation does not have a direct counterpart in x86
  2924. assembly, so we provide this functionality with the function
  2925. \code{read\_int} in the file \code{runtime.c}, written in
  2926. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2927. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  2928. system}, or simply the \emph{runtime} for short. When compiling your
  2929. generated x86 assembly code, you need to compile \code{runtime.c} to
  2930. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2931. \code{-c}) and link it into the executable. For our purposes of code
  2932. generation, all you need to do is translate an assignment of
  2933. \key{read} into a call to the \code{read\_int} function followed by a
  2934. move from \code{rax} to the left-hand-side variable. (Recall that the
  2935. return value of a function goes into \code{rax}.)
  2936. \begin{transformation}
  2937. {\if\edition\racketEd\color{olive}
  2938. \begin{lstlisting}
  2939. |$\itm{var}$| = (read);
  2940. \end{lstlisting}
  2941. \fi}
  2942. {\if\edition\pythonEd\color{purple}
  2943. \begin{lstlisting}
  2944. |$\itm{var}$| = input_int();
  2945. \end{lstlisting}
  2946. \fi}
  2947. \compilesto
  2948. \begin{lstlisting}
  2949. callq read_int
  2950. movq %rax, |$\itm{var}$|
  2951. \end{lstlisting}
  2952. \end{transformation}
  2953. {\if\edition\racketEd\color{olive}
  2954. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2955. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2956. assignment to the \key{rax} register followed by a jump to the
  2957. conclusion of the program (so the conclusion needs to be labeled).
  2958. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2959. recursively and then append the resulting instructions.
  2960. \fi}
  2961. \begin{exercise}
  2962. \normalfont
  2963. {\if\edition\racketEd\color{olive}
  2964. Implement the \key{select-instructions} pass in
  2965. \code{compiler.rkt}. Create three new example programs that are
  2966. designed to exercise all of the interesting cases in this pass.
  2967. %
  2968. In the \code{run-tests.rkt} script, add the following entry to the
  2969. list of \code{passes} and then run the script to test your compiler.
  2970. \begin{lstlisting}
  2971. (list "instruction selection" select-instructions interp_pseudo-x86-0)
  2972. \end{lstlisting}
  2973. \fi}
  2974. {\if\edition\pythonEd\color{purple}
  2975. Implement the \key{select\_instructions} pass in
  2976. \code{compiler.py}. Create three new example programs that are
  2977. designed to exercise all of the interesting cases in this pass.
  2978. Run the \code{run-tests.py} script to to check
  2979. whether the output programs produce the same result as the input
  2980. programs.
  2981. \fi}
  2982. \end{exercise}
  2983. \section{Assign Homes}
  2984. \label{sec:assign-Rvar}
  2985. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  2986. \LangXVar{} programs that no longer use program variables.
  2987. Thus, the \key{assign-homes} pass is responsible for placing all of
  2988. the program variables in registers or on the stack. For runtime
  2989. efficiency, it is better to place variables in registers, but as there
  2990. are only 16 registers, some programs must necessarily resort to
  2991. placing some variables on the stack. In this chapter we focus on the
  2992. mechanics of placing variables on the stack. We study an algorithm for
  2993. placing variables in registers in
  2994. Chapter~\ref{ch:register-allocation-Rvar}.
  2995. Consider again the following \LangVar{} program from
  2996. Section~\ref{sec:remove-complex-opera-Rvar}.
  2997. % var_test_20.rkt
  2998. {\if\edition\racketEd\color{olive}
  2999. \begin{lstlisting}
  3000. (let ([a 42])
  3001. (let ([b a])
  3002. b))
  3003. \end{lstlisting}
  3004. \fi}
  3005. {\if\edition\pythonEd\color{purple}
  3006. \begin{lstlisting}
  3007. a = 42
  3008. b = a
  3009. print(b)
  3010. \end{lstlisting}
  3011. \fi}
  3012. The output of \code{select\_instructions} is shown on the left and the
  3013. output of \code{assign\_homes} on the right. In this example, we
  3014. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  3015. variable \code{b} to location \code{-16(\%rbp)}.
  3016. \begin{transformation}
  3017. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3018. start:
  3019. movq $42, a
  3020. movq a, b
  3021. movq b, %rax
  3022. jmp conclusion
  3023. \end{lstlisting}
  3024. \compilesto
  3025. %stack-space: 16
  3026. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3027. start:
  3028. movq $42, -8(%rbp)
  3029. movq -8(%rbp), -16(%rbp)
  3030. movq -16(%rbp), %rax
  3031. jmp conclusion
  3032. \end{lstlisting}
  3033. \end{transformation}
  3034. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3035. \code{X86Program} node is an alist mapping all the variables in the
  3036. program to their types (for now just \code{Integer}). The
  3037. \code{assign\_homes} pass should replace all uses of those variables
  3038. with stack locations. As an aside, the \code{locals-types} entry is
  3039. computed by \code{type-check-Cvar} in the support code, which installs
  3040. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  3041. be propagated to the \code{X86Program} node.}
  3042. %
  3043. \python{The \code{assign\_homes} pass should replace all uses of
  3044. variables with stack locations.}
  3045. In the process of assigning variables to stack locations, it is
  3046. convenient for you to compute and store the size of the frame (in
  3047. bytes) in%
  3048. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3049. %
  3050. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3051. which is needed later to generate the conclusion of the \code{main}
  3052. procedure. The x86-64 standard requires the frame size to be a
  3053. multiple of 16 bytes.\index{subject}{frame}
  3054. % TODO: store the number of variables instead? -Jeremy
  3055. \begin{exercise}\normalfont
  3056. Implement the \key{assign\_homes} pass in
  3057. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3058. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  3059. \Block{}. We recommend that the auxiliary functions take an extra
  3060. parameter that maps variable names to homes (stack locations for now).
  3061. %
  3062. {\if\edition\racketEd\color{olive}
  3063. In the \code{run-tests.rkt} script, add the following entry to the
  3064. list of \code{passes} and then run the script to test your compiler.
  3065. \begin{lstlisting}
  3066. (list "assign homes" assign-homes interp_x86-0)
  3067. \end{lstlisting}
  3068. \fi}
  3069. {\if\edition\pythonEd\color{purple}
  3070. Run the \code{run-tests.py} script to to check
  3071. whether the output programs produce the same result as the input
  3072. programs.
  3073. \fi}
  3074. \end{exercise}
  3075. \section{Patch Instructions}
  3076. \label{sec:patch-s0}
  3077. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3078. \LangXInt{} by making sure that each instruction adheres to the
  3079. restriction that at most one argument of an instruction may be a
  3080. memory reference.
  3081. We return to the following example.\\
  3082. \begin{minipage}{0.5\textwidth}
  3083. % var_test_20.rkt
  3084. {\if\edition\racketEd\color{olive}
  3085. \begin{lstlisting}
  3086. (let ([a 42])
  3087. (let ([b a])
  3088. b))
  3089. \end{lstlisting}
  3090. \fi}
  3091. {\if\edition\pythonEd\color{purple}
  3092. \begin{lstlisting}
  3093. a = 42
  3094. b = a
  3095. print(b)
  3096. \end{lstlisting}
  3097. \fi}
  3098. \end{minipage}\\
  3099. The \key{assign\_homes} pass produces the following translation. \\
  3100. \begin{minipage}{0.5\textwidth}
  3101. {\if\edition\racketEd\color{olive}
  3102. \begin{lstlisting}
  3103. movq $42, -8(%rbp)
  3104. movq -8(%rbp), -16(%rbp)
  3105. movq -16(%rbp), %rax
  3106. \end{lstlisting}
  3107. \fi}
  3108. {\if\edition\pythonEd\color{purple}
  3109. \begin{lstlisting}
  3110. movq 42, -8(%rbp)
  3111. movq -8(%rbp), -16(%rbp)
  3112. movq -16(%rbp), %rdi
  3113. callq print_int
  3114. \end{lstlisting}
  3115. \fi}
  3116. \end{minipage}\\
  3117. The second \key{movq} instruction is problematic because both
  3118. arguments are stack locations. We suggest fixing this problem by
  3119. moving from the source location to the register \key{rax} and then
  3120. from \key{rax} to the destination location, as follows.
  3121. \begin{lstlisting}
  3122. movq -8(%rbp), %rax
  3123. movq %rax, -16(%rbp)
  3124. \end{lstlisting}
  3125. \begin{exercise}
  3126. \normalfont Implement the \key{patch\_instructions} pass in
  3127. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3128. Create three new example programs that are
  3129. designed to exercise all of the interesting cases in this pass.
  3130. %
  3131. {\if\edition\racketEd\color{olive}
  3132. In the \code{run-tests.rkt} script, add the following entry to the
  3133. list of \code{passes} and then run the script to test your compiler.
  3134. \begin{lstlisting}
  3135. (list "patch instructions" patch-instructions interp_x86-0)
  3136. \end{lstlisting}
  3137. \fi}
  3138. {\if\edition\pythonEd\color{purple}
  3139. Run the \code{run-tests.py} script to to check
  3140. whether the output programs produce the same result as the input
  3141. programs.
  3142. \fi}
  3143. \end{exercise}
  3144. \section{Print x86}
  3145. \label{sec:print-x86}
  3146. The last step of the compiler from \LangVar{} to x86 is to convert the
  3147. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  3148. string representation (defined in
  3149. Figure~\ref{fig:x86-int-concrete}). \racket{The Racket \key{format} and
  3150. \key{string-append} functions are useful in this regard.} The main work
  3151. that this step needs to perform is to create the \key{main} function
  3152. and the standard instructions for its prelude and conclusion, as shown
  3153. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  3154. know the amount of space needed for the stack frame, which you can
  3155. obtain from the \racket{\code{stack-space} entry in the $\itm{info}$ field}
  3156. \python{\code{stack\_space} field}
  3157. of the \key{X86Program} node.
  3158. When running on Mac OS X, your compiler should prefix an underscore to
  3159. labels like \key{main}. \racket{The Racket call \code{(system-type 'os)} is
  3160. useful for determining which operating system the compiler is running
  3161. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3162. \python{The Python \code{platform} library includes a \code{system()} function
  3163. that returns \code{'Linux'}, \code{'Windows'}, or \code{'Darwin'} (for Mac).}
  3164. \begin{exercise}\normalfont
  3165. %
  3166. Implement the \key{print\_x86} pass in \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3167. %
  3168. {\if\edition\racketEd\color{olive}
  3169. In the \code{run-tests.rkt} script, add the following entry to the
  3170. list of \code{passes} and then run the script to test your compiler.
  3171. \begin{lstlisting}
  3172. (list "print x86" print-x86 #f)
  3173. \end{lstlisting}
  3174. %
  3175. Uncomment the call to the \key{compiler-tests} function
  3176. (Appendix~\ref{appendix:utilities}), which tests your complete
  3177. compiler by executing the generated x86 code. Compile the provided
  3178. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  3179. script to test your compiler.
  3180. \fi}
  3181. {\if\edition\pythonEd\color{purple}
  3182. Run the \code{run-tests.py} script to to check
  3183. whether the output programs produce the same result as the input
  3184. programs.
  3185. \fi}
  3186. \end{exercise}
  3187. \section{Challenge: Partial Evaluator for \LangVar{}}
  3188. \label{sec:pe-Rvar}
  3189. \index{subject}{partial evaluation}
  3190. This section describes optional challenge exercises that involve
  3191. adapting and improving the partial evaluator for \LangInt{} that was
  3192. introduced in Section~\ref{sec:partial-evaluation}.
  3193. \begin{exercise}\label{ex:pe-Rvar}
  3194. \normalfont
  3195. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3196. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3197. instead of \LangInt{} programs. Recall that \LangVar{} adds
  3198. \racket{\key{let} binding}\python{assignment}
  3199. and variables to the \LangInt{} language, so you will need to add cases for
  3200. them in the \code{pe\_exp} \racket{function}\python{and \code{pe\_stmt functions}}. Once complete, add the partial
  3201. evaluation pass to the front of your compiler and make sure that your
  3202. compiler still passes all of the tests.
  3203. \end{exercise}
  3204. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  3205. \begin{exercise}
  3206. \normalfont
  3207. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3208. \code{pe\_add} auxiliary functions with functions that know more about
  3209. arithmetic. For example, your partial evaluator should translate
  3210. {\if\edition\racketEd\color{olive}
  3211. \[
  3212. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3213. \code{(+ 2 (read))}
  3214. \]
  3215. \fi}
  3216. {\if\edition\pythonEd\color{purple}
  3217. \[
  3218. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3219. \code{2 + input\_int()}
  3220. \]
  3221. \fi}
  3222. To accomplish this, the \code{pe\_exp} function should produce output
  3223. in the form of the $\itm{residual}$ non-terminal of the following
  3224. grammar. The idea is that when processing an addition expression, we
  3225. can always produce either 1) an integer constant, 2) an addition
  3226. expression with an integer constant on the left-hand side but not the
  3227. right-hand side, or 3) or an addition expression in which neither
  3228. subexpression is a constant.
  3229. {\if\edition\racketEd\color{olive}
  3230. \[
  3231. \begin{array}{lcl}
  3232. \itm{inert} &::=& \Var
  3233. \MID \LP\key{read}\RP
  3234. \MID \LP\key{-} ~\Var\RP
  3235. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3236. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3237. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3238. \itm{residual} &::=& \Int
  3239. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3240. \MID \itm{inert}
  3241. \end{array}
  3242. \]
  3243. \fi}
  3244. {\if\edition\pythonEd\color{purple}
  3245. \[
  3246. \begin{array}{lcl}
  3247. \itm{inert} &::=& \Var
  3248. \MID \key{input\_int}\LP\RP
  3249. \MID \key{-} \Var
  3250. \MID \key{-} \key{input\_int}\LP\RP
  3251. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3252. \itm{residual} &::=& \Int
  3253. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3254. \MID \itm{inert}
  3255. \end{array}
  3256. \]
  3257. \fi}
  3258. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3259. inputs are $\itm{residual}$ expressions and they should return
  3260. $\itm{residual}$ expressions. Once the improvements are complete,
  3261. make sure that your compiler still passes all of the tests. After
  3262. all, fast code is useless if it produces incorrect results!
  3263. \end{exercise}
  3264. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3265. \chapter{Register Allocation}
  3266. \label{ch:register-allocation-Rvar}
  3267. \index{subject}{register allocation}
  3268. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  3269. stack. In this Chapter we learn how to improve the performance of the
  3270. generated code by placing some variables into registers. The CPU can
  3271. access a register in a single cycle, whereas accessing the stack can
  3272. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3273. serves as a running example. The source program is on the left and the
  3274. output of instruction selection is on the right. The program is almost
  3275. in the x86 assembly language but it still uses variables.
  3276. \begin{figure}
  3277. \begin{minipage}{0.45\textwidth}
  3278. Example \LangVar{} program:
  3279. % var_test_28.rkt
  3280. {\if\edition\racketEd\color{olive}
  3281. \begin{lstlisting}
  3282. (let ([v 1])
  3283. (let ([w 42])
  3284. (let ([x (+ v 7)])
  3285. (let ([y x])
  3286. (let ([z (+ x w)])
  3287. (+ z (- y)))))))
  3288. \end{lstlisting}
  3289. \fi}
  3290. {\if\edition\pythonEd\color{purple}
  3291. \begin{lstlisting}
  3292. v = 1
  3293. w = 42
  3294. x = v + 7
  3295. y = x
  3296. z = x + w
  3297. print(z + (- y))
  3298. \end{lstlisting}
  3299. \fi}
  3300. \end{minipage}
  3301. \begin{minipage}{0.45\textwidth}
  3302. After instruction selection:
  3303. {\if\edition\racketEd\color{olive}
  3304. \begin{lstlisting}
  3305. locals-types:
  3306. x : Integer, y : Integer,
  3307. z : Integer, t : Integer,
  3308. v : Integer, w : Integer
  3309. start:
  3310. movq $1, v
  3311. movq $42, w
  3312. movq v, x
  3313. addq $7, x
  3314. movq x, y
  3315. movq x, z
  3316. addq w, z
  3317. movq y, t
  3318. negq t
  3319. movq z, %rax
  3320. addq t, %rax
  3321. jmp conclusion
  3322. \end{lstlisting}
  3323. \fi}
  3324. {\if\edition\pythonEd\color{purple}
  3325. \begin{lstlisting}
  3326. movq $1, v
  3327. movq $42, w
  3328. movq v, x
  3329. addq $7, x
  3330. movq x, y
  3331. movq x, z
  3332. addq w, z
  3333. movq y, tmp_0
  3334. negq tmp_0
  3335. movq z, tmp_1
  3336. addq tmp_0, tmp_1
  3337. movq tmp_1, %rdi
  3338. callq print_int
  3339. \end{lstlisting}
  3340. \fi}
  3341. \end{minipage}
  3342. \caption{A running example for register allocation.}
  3343. \label{fig:reg-eg}
  3344. \end{figure}
  3345. The goal of register allocation is to fit as many variables into
  3346. registers as possible. Some programs have more variables than
  3347. registers so we cannot always map each variable to a different
  3348. register. Fortunately, it is common for different variables to be
  3349. needed during different periods of time during program execution, and
  3350. in such cases several variables can be mapped to the same register.
  3351. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3352. After the variable \code{x} is moved to \code{z} it is no longer
  3353. needed. Variable \code{z}, on the other hand, is used only after this
  3354. point, so \code{x} and \code{z} could share the same register. The
  3355. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  3356. where a variable is needed. Once we have that information, we compute
  3357. which variables are needed at the same time, i.e., which ones
  3358. \emph{interfere} with each other, and represent this relation as an
  3359. undirected graph whose vertices are variables and edges indicate when
  3360. two variables interfere (Section~\ref{sec:build-interference}). We
  3361. then model register allocation as a graph coloring problem
  3362. (Section~\ref{sec:graph-coloring}).
  3363. If we run out of registers despite these efforts, we place the
  3364. remaining variables on the stack, similar to what we did in
  3365. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  3366. for assigning a variable to a stack location. The decision to spill a
  3367. variable is handled as part of the graph coloring process
  3368. (Section~\ref{sec:graph-coloring}).
  3369. We make the simplifying assumption that each variable is assigned to
  3370. one location (a register or stack address). A more sophisticated
  3371. approach is to assign a variable to one or more locations in different
  3372. regions of the program. For example, if a variable is used many times
  3373. in short sequence and then only used again after many other
  3374. instructions, it could be more efficient to assign the variable to a
  3375. register during the initial sequence and then move it to the stack for
  3376. the rest of its lifetime. We refer the interested reader to
  3377. \citet{Cooper:2011aa} for more information about that approach.
  3378. % discuss prioritizing variables based on how much they are used.
  3379. \section{Registers and Calling Conventions}
  3380. \label{sec:calling-conventions}
  3381. \index{subject}{calling conventions}
  3382. As we perform register allocation, we need to be aware of the
  3383. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3384. functions calls are performed in x86.
  3385. %
  3386. Even though \LangVar{} does not include programmer-defined functions,
  3387. our generated code includes a \code{main} function that is called by
  3388. the operating system and our generated code contains calls to the
  3389. \code{read\_int} function.
  3390. Function calls require coordination between two pieces of code that
  3391. may be written by different programmers or generated by different
  3392. compilers. Here we follow the System V calling conventions that are
  3393. used by the GNU C compiler on Linux and
  3394. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3395. %
  3396. The calling conventions include rules about how functions share the
  3397. use of registers. In particular, the caller is responsible for freeing
  3398. up some registers prior to the function call for use by the callee.
  3399. These are called the \emph{caller-saved registers}
  3400. \index{subject}{caller-saved registers}
  3401. and they are
  3402. \begin{lstlisting}
  3403. rax rcx rdx rsi rdi r8 r9 r10 r11
  3404. \end{lstlisting}
  3405. On the other hand, the callee is responsible for preserving the values
  3406. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3407. which are
  3408. \begin{lstlisting}
  3409. rsp rbp rbx r12 r13 r14 r15
  3410. \end{lstlisting}
  3411. We can think about this caller/callee convention from two points of
  3412. view, the caller view and the callee view:
  3413. \begin{itemize}
  3414. \item The caller should assume that all the caller-saved registers get
  3415. overwritten with arbitrary values by the callee. On the other hand,
  3416. the caller can safely assume that all the callee-saved registers
  3417. contain the same values after the call that they did before the
  3418. call.
  3419. \item The callee can freely use any of the caller-saved registers.
  3420. However, if the callee wants to use a callee-saved register, the
  3421. callee must arrange to put the original value back in the register
  3422. prior to returning to the caller. This can be accomplished by saving
  3423. the value to the stack in the prelude of the function and restoring
  3424. the value in the conclusion of the function.
  3425. \end{itemize}
  3426. In x86, registers are also used for passing arguments to a function
  3427. and for the return value. In particular, the first six arguments to a
  3428. function are passed in the following six registers, in this order.
  3429. \begin{lstlisting}
  3430. rdi rsi rdx rcx r8 r9
  3431. \end{lstlisting}
  3432. If there are more than six arguments, then the convention is to use
  3433. space on the frame of the caller for the rest of the
  3434. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3435. need more than six arguments. For now, the only function we care about
  3436. is \code{read\_int} and it takes zero arguments.
  3437. %
  3438. The register \code{rax} is used for the return value of a function.
  3439. The next question is how these calling conventions impact register
  3440. allocation. Consider the \LangVar{} program in
  3441. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3442. example from the caller point of view and then from the callee point
  3443. of view.
  3444. The program makes two calls to the \code{read} function. Also, the
  3445. variable \code{x} is in use during the second call to \code{read}, so
  3446. we need to make sure that the value in \code{x} does not get
  3447. accidentally wiped out by the call to \code{read}. One obvious
  3448. approach is to save all the values in caller-saved registers to the
  3449. stack prior to each function call, and restore them after each
  3450. call. That way, if the register allocator chooses to assign \code{x}
  3451. to a caller-saved register, its value will be preserved across the
  3452. call to \code{read}. However, saving and restoring to the stack is
  3453. relatively slow. If \code{x} is not used many times, it may be better
  3454. to assign \code{x} to a stack location in the first place. Or better
  3455. yet, if we can arrange for \code{x} to be placed in a callee-saved
  3456. register, then it won't need to be saved and restored during function
  3457. calls.
  3458. The approach that we recommend for variables that are in use during a
  3459. function call is to either assign them to callee-saved registers or to
  3460. spill them to the stack. On the other hand, for variables that are not
  3461. in use during a function call, we try the following alternatives in
  3462. order 1) look for an available caller-saved register (to leave room
  3463. for other variables in the callee-saved register), 2) look for a
  3464. callee-saved register, and 3) spill the variable to the stack.
  3465. It is straightforward to implement this approach in a graph coloring
  3466. register allocator. First, we know which variables are in use during
  3467. every function call because we compute that information for every
  3468. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  3469. build the interference graph (Section~\ref{sec:build-interference}),
  3470. we can place an edge between each of these variables and the
  3471. caller-saved registers in the interference graph. This will prevent
  3472. the graph coloring algorithm from assigning those variables to
  3473. caller-saved registers.
  3474. Returning to the example in
  3475. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3476. generated x86 code on the right-hand side, focusing on the
  3477. \code{start} block. Notice that variable \code{x} is assigned to
  3478. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  3479. place during the second call to \code{read\_int}. Next, notice that
  3480. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  3481. because there are no function calls in the remainder of the block.
  3482. Next we analyze the example from the callee point of view, focusing on
  3483. the prelude and conclusion of the \code{main} function. As usual the
  3484. prelude begins with saving the \code{rbp} register to the stack and
  3485. setting the \code{rbp} to the current stack pointer. We now know why
  3486. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3487. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3488. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3489. (\code{x}). The other callee-saved registers are not saved in the
  3490. prelude because they are not used. The prelude subtracts 8 bytes from
  3491. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3492. conclusion, we see that \code{rbx} is restored from the stack with a
  3493. \code{popq} instruction.
  3494. \index{subject}{prelude}\index{subject}{conclusion}
  3495. \begin{figure}[tp]
  3496. \begin{minipage}{0.45\textwidth}
  3497. Example \LangVar{} program:
  3498. %var_test_14.rkt
  3499. {\if\edition\racketEd\color{olive}
  3500. \begin{lstlisting}
  3501. (let ([x (read)])
  3502. (let ([y (read)])
  3503. (+ (+ x y) 42)))
  3504. \end{lstlisting}
  3505. \fi}
  3506. {\if\edition\pythonEd\color{purple}
  3507. \begin{lstlisting}
  3508. x = input_int()
  3509. y = input_int()
  3510. print((x + y) + 42)
  3511. \end{lstlisting}
  3512. \fi}
  3513. \end{minipage}
  3514. \begin{minipage}{0.45\textwidth}
  3515. Generated x86 assembly:
  3516. {\if\edition\racketEd\color{olive}
  3517. \begin{lstlisting}
  3518. start:
  3519. callq read_int
  3520. movq %rax, %rbx
  3521. callq read_int
  3522. movq %rax, %rcx
  3523. addq %rcx, %rbx
  3524. movq %rbx, %rax
  3525. addq $42, %rax
  3526. jmp _conclusion
  3527. .globl main
  3528. main:
  3529. pushq %rbp
  3530. movq %rsp, %rbp
  3531. pushq %rbx
  3532. subq $8, %rsp
  3533. jmp start
  3534. conclusion:
  3535. addq $8, %rsp
  3536. popq %rbx
  3537. popq %rbp
  3538. retq
  3539. \end{lstlisting}
  3540. \fi}
  3541. {\if\edition\pythonEd\color{purple}
  3542. \begin{lstlisting}
  3543. .globl main
  3544. main:
  3545. pushq %rbp
  3546. movq %rsp, %rbp
  3547. pushq %rbx
  3548. subq $8, %rsp
  3549. callq read_int
  3550. movq %rax, %rbx
  3551. callq read_int
  3552. movq %rax, %rcx
  3553. movq %rbx, %rdx
  3554. addq %rcx, %rdx
  3555. movq %rdx, %rcx
  3556. addq $42, %rcx
  3557. movq %rcx, %rdi
  3558. callq print_int
  3559. addq $8, %rsp
  3560. popq %rbx
  3561. popq %rbp
  3562. retq
  3563. \end{lstlisting}
  3564. \fi}
  3565. \end{minipage}
  3566. \caption{An example with function calls.}
  3567. \label{fig:example-calling-conventions}
  3568. \end{figure}
  3569. %\clearpage
  3570. \section{Liveness Analysis}
  3571. \label{sec:liveness-analysis-Rvar}
  3572. \index{subject}{liveness analysis}
  3573. The \code{uncover\_live} \racket{pass}\python{function}
  3574. performs \emph{liveness analysis}, that
  3575. is, it discovers which variables are in-use in different regions of a
  3576. program.
  3577. %
  3578. A variable or register is \emph{live} at a program point if its
  3579. current value is used at some later point in the program. We
  3580. refer to variables and registers collectively as \emph{locations}.
  3581. %
  3582. Consider the following code fragment in which there are two writes to
  3583. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3584. \begin{center}
  3585. \begin{minipage}{0.96\textwidth}
  3586. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3587. movq $5, a
  3588. movq $30, b
  3589. movq a, c
  3590. movq $10, b
  3591. addq b, c
  3592. \end{lstlisting}
  3593. \end{minipage}
  3594. \end{center}
  3595. The answer is no because \code{a} is live from line 1 to 3 and
  3596. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3597. line 2 is never used because it is overwritten (line 4) before the
  3598. next read (line 5).
  3599. The live locations can be computed by traversing the instruction
  3600. sequence back to front (i.e., backwards in execution order). Let
  3601. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3602. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3603. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3604. locations before instruction $I_k$.
  3605. \racket{We recommend representing these
  3606. sets with the Racket \code{set} data structure described in
  3607. Figure~\ref{fig:set}.}
  3608. \python{We recommend representing these sets with the Python
  3609. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3610. data structure.}
  3611. {\if\edition\racketEd\color{olive}
  3612. \begin{figure}[tp]
  3613. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3614. \small
  3615. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3616. A \emph{set} is an unordered collection of elements without duplicates.
  3617. Here are some of the operations defined on sets.
  3618. \index{subject}{set}
  3619. \begin{description}
  3620. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3621. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3622. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3623. difference of the two sets.
  3624. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3625. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3626. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3627. \end{description}
  3628. \end{tcolorbox}
  3629. %\end{wrapfigure}
  3630. \caption{The \code{set} data structure.}
  3631. \label{fig:set}
  3632. \end{figure}
  3633. \fi}
  3634. The live locations after an instruction are always the same as the
  3635. live locations before the next instruction.
  3636. \index{subject}{live-after} \index{subject}{live-before}
  3637. \begin{equation} \label{eq:live-after-before-next}
  3638. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3639. \end{equation}
  3640. To start things off, there are no live locations after the last
  3641. instruction, so
  3642. \begin{equation}\label{eq:live-last-empty}
  3643. L_{\mathsf{after}}(n) = \emptyset
  3644. \end{equation}
  3645. We then apply the following rule repeatedly, traversing the
  3646. instruction sequence back to front.
  3647. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3648. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3649. \end{equation}
  3650. where $W(k)$ are the locations written to by instruction $I_k$ and
  3651. $R(k)$ are the locations read by instruction $I_k$.
  3652. {\if\edition\racketEd\color{olive}
  3653. There is a special case for \code{jmp} instructions. The locations
  3654. that are live before a \code{jmp} should be the locations in
  3655. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3656. maintaining an alist named \code{label->live} that maps each label to
  3657. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3658. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3659. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3660. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3661. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3662. \fi}
  3663. Let us walk through the above example, applying these formulas
  3664. starting with the instruction on line 5. We collect the answers in
  3665. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3666. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3667. instruction (formula~\ref{eq:live-last-empty}). The
  3668. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3669. because it reads from variables \code{b} and \code{c}
  3670. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3671. \[
  3672. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3673. \]
  3674. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3675. the live-before set from line 5 to be the live-after set for this
  3676. instruction (formula~\ref{eq:live-after-before-next}).
  3677. \[
  3678. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3679. \]
  3680. This move instruction writes to \code{b} and does not read from any
  3681. variables, so we have the following live-before set
  3682. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3683. \[
  3684. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3685. \]
  3686. The live-before for instruction \code{movq a, c}
  3687. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3688. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3689. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3690. variable that is not live and does not read from a variable.
  3691. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3692. because it writes to variable \code{a}.
  3693. \begin{figure}[tbp]
  3694. \begin{minipage}{0.45\textwidth}
  3695. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3696. movq $5, a
  3697. movq $30, b
  3698. movq a, c
  3699. movq $10, b
  3700. addq b, c
  3701. \end{lstlisting}
  3702. \end{minipage}
  3703. \vrule\hspace{10pt}
  3704. \begin{minipage}{0.45\textwidth}
  3705. \begin{align*}
  3706. L_{\mathsf{before}}(1)= \emptyset,
  3707. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3708. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3709. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3710. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3711. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3712. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3713. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3714. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3715. L_{\mathsf{after}}(5)= \emptyset
  3716. \end{align*}
  3717. \end{minipage}
  3718. \caption{Example output of liveness analysis on a short example.}
  3719. \label{fig:liveness-example-0}
  3720. \end{figure}
  3721. \begin{exercise}\normalfont
  3722. Perform liveness analysis on the running example in
  3723. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3724. sets for each instruction. Compare your answers to the solution
  3725. shown in Figure~\ref{fig:live-eg}.
  3726. \end{exercise}
  3727. \begin{figure}[tp]
  3728. \hspace{20pt}
  3729. \begin{minipage}{0.45\textwidth}
  3730. {\if\edition\racketEd\color{olive}
  3731. \begin{lstlisting}
  3732. |$\{\ttm{rsp}\}$|
  3733. movq $1, v
  3734. |$\{\ttm{v},\ttm{rsp}\}$|
  3735. movq $42, w
  3736. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3737. movq v, x
  3738. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3739. addq $7, x
  3740. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3741. movq x, y
  3742. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3743. movq x, z
  3744. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3745. addq w, z
  3746. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3747. movq y, t
  3748. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3749. negq t
  3750. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3751. movq z, %rax
  3752. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3753. addq t, %rax
  3754. |$\{\ttm{rax},\ttm{rsp}\}$|
  3755. jmp conclusion
  3756. \end{lstlisting}
  3757. \fi}
  3758. {\if\edition\pythonEd\color{purple}
  3759. \begin{lstlisting}
  3760. movq $1, v
  3761. |$\{\ttm{v}\}$|
  3762. movq $42, w
  3763. |$\{\ttm{w}, \ttm{v}\}$|
  3764. movq v, x
  3765. |$\{\ttm{w}, \ttm{x}\}$|
  3766. addq $7, x
  3767. |$\{\ttm{w}, \ttm{x}\}$|
  3768. movq x, y
  3769. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  3770. movq x, z
  3771. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  3772. addq w, z
  3773. |$\{\ttm{y}, \ttm{z}\}$|
  3774. movq y, tmp_0
  3775. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3776. negq tmp_0
  3777. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3778. movq z, tmp_1
  3779. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  3780. addq tmp_0, tmp_1
  3781. |$\{\ttm{tmp\_1}\}$|
  3782. movq tmp_1, %rdi
  3783. |$\{\ttm{rdi}\}$|
  3784. callq print_int
  3785. |$\{\}$|
  3786. \end{lstlisting}
  3787. \fi}
  3788. \end{minipage}
  3789. \caption{The running example annotated with live-after sets.}
  3790. \label{fig:live-eg}
  3791. \end{figure}
  3792. \begin{exercise}\normalfont
  3793. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  3794. %
  3795. \racket{Store the sequence of live-after sets in the $\itm{info}$
  3796. field of the \code{Block} structure.}
  3797. %
  3798. \python{Return a dictionary that maps each instruction to its
  3799. live-after set.}
  3800. %
  3801. \racket{We recommend creating an auxiliary function that takes a list
  3802. of instructions and an initial live-after set (typically empty) and
  3803. returns the list of live-after sets.}
  3804. %
  3805. We recommend creating auxiliary functions to 1) compute the set
  3806. of locations that appear in an \Arg{}, 2) compute the locations read
  3807. by an instruction (the $R$ function), and 3) the locations written by
  3808. an instruction (the $W$ function). The \code{callq} instruction should
  3809. include all of the caller-saved registers in its write-set $W$ because
  3810. the calling convention says that those registers may be written to
  3811. during the function call. Likewise, the \code{callq} instruction
  3812. should include the appropriate argument-passing registers in its
  3813. read-set $R$, depending on the arity of the function being
  3814. called. (This is why the abstract syntax for \code{callq} includes the
  3815. arity.)
  3816. \end{exercise}
  3817. %\clearpage
  3818. \section{Build the Interference Graph}
  3819. \label{sec:build-interference}
  3820. {\if\edition\racketEd\color{olive}
  3821. \begin{figure}[tp]
  3822. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  3823. \small
  3824. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  3825. A \emph{graph} is a collection of vertices and edges where each
  3826. edge connects two vertices. A graph is \emph{directed} if each
  3827. edge points from a source to a target. Otherwise the graph is
  3828. \emph{undirected}.
  3829. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  3830. \begin{description}
  3831. %% We currently don't use directed graphs. We instead use
  3832. %% directed multi-graphs. -Jeremy
  3833. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  3834. directed graph from a list of edges. Each edge is a list
  3835. containing the source and target vertex.
  3836. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  3837. undirected graph from a list of edges. Each edge is represented by
  3838. a list containing two vertices.
  3839. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  3840. inserts a vertex into the graph.
  3841. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  3842. inserts an edge between the two vertices.
  3843. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  3844. returns a sequence of vertices adjacent to the vertex.
  3845. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  3846. returns a sequence of all vertices in the graph.
  3847. \end{description}
  3848. \end{tcolorbox}
  3849. %\end{wrapfigure}
  3850. \caption{The Racket \code{graph} package.}
  3851. \label{fig:graph}
  3852. \end{figure}
  3853. \fi}
  3854. Based on the liveness analysis, we know where each location is live.
  3855. However, during register allocation, we need to answer questions of
  3856. the specific form: are locations $u$ and $v$ live at the same time?
  3857. (And therefore cannot be assigned to the same register.) To make this
  3858. question more efficient to answer, we create an explicit data
  3859. structure, an \emph{interference graph}\index{subject}{interference
  3860. graph}. An interference graph is an undirected graph that has an
  3861. edge between two locations if they are live at the same time, that is,
  3862. if they interfere with each other.
  3863. %
  3864. \racket{We recommend using the Racket \code{graph} package
  3865. (Figure~\ref{fig:graph}) to represent the interference graph.}
  3866. %
  3867. \python{We provide implementations of directed and undirected graph
  3868. data structures in the file \code{graph.py} of the support code.}
  3869. A straightforward way to compute the interference graph is to look at
  3870. the set of live locations between each instruction and the next and
  3871. add an edge to the graph for every pair of variables in the same set.
  3872. This approach is less than ideal for two reasons. First, it can be
  3873. expensive because it takes $O(n^2)$ time to consider at every pair in
  3874. a set of $n$ live locations. Second, in the special case where two
  3875. locations hold the same value (because one was assigned to the other),
  3876. they can be live at the same time without interfering with each other.
  3877. A better way to compute the interference graph is to focus on
  3878. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3879. must not overwrite something in a live location. So for each
  3880. instruction, we create an edge between the locations being written to
  3881. and the live locations. (Except that one should not create self
  3882. edges.) Note that for the \key{callq} instruction, we consider all of
  3883. the caller-saved registers as being written to, so an edge is added
  3884. between every live variable and every caller-saved register. For
  3885. \key{movq}, we deal with the above-mentioned special case by not
  3886. adding an edge between a live variable $v$ and the destination if $v$
  3887. matches the source. So we have the following two rules.
  3888. \begin{enumerate}
  3889. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3890. $d$, then add the edge $(d,v)$ for every $v \in
  3891. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3892. \item For any other instruction $I_k$, for every $d \in W(k)$
  3893. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3894. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3895. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3896. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3897. %% \item If instruction $I_k$ is of the form \key{callq}
  3898. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3899. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3900. \end{enumerate}
  3901. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3902. the above rules to each instruction. We highlight a few of the
  3903. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  3904. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  3905. so \code{v} interferes with \code{rsp}.}
  3906. %
  3907. \python{The first instruction is \lstinline{movq $1, v} and the
  3908. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  3909. no interference because $\ttm{v}$ is the destination of the move.}
  3910. %
  3911. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  3912. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  3913. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  3914. %
  3915. \python{The fourth instruction is \lstinline{addq $7, x} and the
  3916. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  3917. $\ttm{x}$ interferes with \ttm{w}.}
  3918. %
  3919. \racket{The next instruction is \lstinline{movq x, y} and the
  3920. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  3921. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  3922. \ttm{x} because \ttm{x} is the source of the move and therefore
  3923. \ttm{x} and \ttm{y} hold the same value.}
  3924. %
  3925. \python{The next instruction is \lstinline{movq x, y} and the
  3926. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  3927. applies, so \ttm{y} interferes with \ttm{w} but not
  3928. \ttm{x} because \ttm{x} is the source of the move and therefore
  3929. \ttm{x} and \ttm{y} hold the same value.}
  3930. %
  3931. Figure~\ref{fig:interference-results} lists the interference results
  3932. for all of the instructions and the resulting interference graph is
  3933. shown in Figure~\ref{fig:interfere}.
  3934. \begin{figure}[tbp]
  3935. \begin{quote}
  3936. {\if\edition\racketEd\color{olive}
  3937. \begin{tabular}{ll}
  3938. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  3939. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  3940. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3941. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3942. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  3943. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  3944. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  3945. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3946. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3947. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3948. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3949. \lstinline!jmp conclusion!& no interference.
  3950. \end{tabular}
  3951. \fi}
  3952. {\if\edition\pythonEd\color{purple}
  3953. \begin{tabular}{ll}
  3954. \lstinline!movq $1, v!& no interference\\
  3955. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  3956. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  3957. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  3958. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  3959. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  3960. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  3961. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  3962. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  3963. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  3964. \lstinline!addq tmp_0, tmp_1! & no interference\\
  3965. \lstinline!movq tmp_1, %rdi! & no interference \\
  3966. \lstinline!callq print_int!& no interference.
  3967. \end{tabular}
  3968. \fi}
  3969. \end{quote}
  3970. \caption{Interference results for the running example.}
  3971. \label{fig:interference-results}
  3972. \end{figure}
  3973. \begin{figure}[tbp]
  3974. \large
  3975. {\if\edition\racketEd\color{olive}
  3976. \[
  3977. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3978. \node (rax) at (0,0) {$\ttm{rax}$};
  3979. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3980. \node (t1) at (0,2) {$\ttm{t}$};
  3981. \node (z) at (3,2) {$\ttm{z}$};
  3982. \node (x) at (6,2) {$\ttm{x}$};
  3983. \node (y) at (3,0) {$\ttm{y}$};
  3984. \node (w) at (6,0) {$\ttm{w}$};
  3985. \node (v) at (9,0) {$\ttm{v}$};
  3986. \draw (t1) to (rax);
  3987. \draw (t1) to (z);
  3988. \draw (z) to (y);
  3989. \draw (z) to (w);
  3990. \draw (x) to (w);
  3991. \draw (y) to (w);
  3992. \draw (v) to (w);
  3993. \draw (v) to (rsp);
  3994. \draw (w) to (rsp);
  3995. \draw (x) to (rsp);
  3996. \draw (y) to (rsp);
  3997. \path[-.,bend left=15] (z) edge node {} (rsp);
  3998. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3999. \draw (rax) to (rsp);
  4000. \end{tikzpicture}
  4001. \]
  4002. \fi}
  4003. {\if\edition\pythonEd\color{purple}
  4004. \[
  4005. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4006. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4007. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4008. \node (z) at (3,2) {$\ttm{z}$};
  4009. \node (x) at (6,2) {$\ttm{x}$};
  4010. \node (y) at (3,0) {$\ttm{y}$};
  4011. \node (w) at (6,0) {$\ttm{w}$};
  4012. \node (v) at (9,0) {$\ttm{v}$};
  4013. \draw (t0) to (t1);
  4014. \draw (t0) to (z);
  4015. \draw (z) to (y);
  4016. \draw (z) to (w);
  4017. \draw (x) to (w);
  4018. \draw (y) to (w);
  4019. \draw (v) to (w);
  4020. \end{tikzpicture}
  4021. \]
  4022. \fi}
  4023. \caption{The interference graph of the example program.}
  4024. \label{fig:interfere}
  4025. \end{figure}
  4026. %% Our next concern is to choose a data structure for representing the
  4027. %% interference graph. There are many choices for how to represent a
  4028. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4029. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4030. %% data structure is to study the algorithm that uses the data structure,
  4031. %% determine what operations need to be performed, and then choose the
  4032. %% data structure that provide the most efficient implementations of
  4033. %% those operations. Often times the choice of data structure can have an
  4034. %% effect on the time complexity of the algorithm, as it does here. If
  4035. %% you skim the next section, you will see that the register allocation
  4036. %% algorithm needs to ask the graph for all of its vertices and, given a
  4037. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4038. %% correct choice of graph representation is that of an adjacency
  4039. %% list. There are helper functions in \code{utilities.rkt} for
  4040. %% representing graphs using the adjacency list representation:
  4041. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4042. %% (Appendix~\ref{appendix:utilities}).
  4043. %% %
  4044. %% \margincomment{\footnotesize To do: change to use the
  4045. %% Racket graph library. \\ --Jeremy}
  4046. %% %
  4047. %% In particular, those functions use a hash table to map each vertex to
  4048. %% the set of adjacent vertices, and the sets are represented using
  4049. %% Racket's \key{set}, which is also a hash table.
  4050. \begin{exercise}\normalfont
  4051. \racket{Implement the compiler pass named \code{build\_interference} according
  4052. to the algorithm suggested above. We recommend using the Racket
  4053. \code{graph} package to create and inspect the interference graph.
  4054. The output graph of this pass should be stored in the $\itm{info}$ field of
  4055. the program, under the key \code{conflicts}.}
  4056. %
  4057. \python{Implement a function named \code{build\_interference}
  4058. according to the algorithm suggested above that
  4059. returns the interference graph.}
  4060. \end{exercise}
  4061. \section{Graph Coloring via Sudoku}
  4062. \label{sec:graph-coloring}
  4063. \index{subject}{graph coloring}
  4064. \index{subject}{Sudoku}
  4065. \index{subject}{color}
  4066. We come to the main event, mapping variables to registers and stack
  4067. locations. Variables that interfere with each other must be mapped to
  4068. different locations. In terms of the interference graph, this means
  4069. that adjacent vertices must be mapped to different locations. If we
  4070. think of locations as colors, the register allocation problem becomes
  4071. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4072. The reader may be more familiar with the graph coloring problem than he
  4073. or she realizes; the popular game of Sudoku is an instance of the
  4074. graph coloring problem. The following describes how to build a graph
  4075. out of an initial Sudoku board.
  4076. \begin{itemize}
  4077. \item There is one vertex in the graph for each Sudoku square.
  4078. \item There is an edge between two vertices if the corresponding squares
  4079. are in the same row, in the same column, or if the squares are in
  4080. the same $3\times 3$ region.
  4081. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4082. \item Based on the initial assignment of numbers to squares in the
  4083. Sudoku board, assign the corresponding colors to the corresponding
  4084. vertices in the graph.
  4085. \end{itemize}
  4086. If you can color the remaining vertices in the graph with the nine
  4087. colors, then you have also solved the corresponding game of Sudoku.
  4088. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4089. the corresponding graph with colored vertices. We map the Sudoku
  4090. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4091. sampling of the vertices (the colored ones) because showing edges for
  4092. all of the vertices would make the graph unreadable.
  4093. \begin{figure}[tbp]
  4094. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4095. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4096. \caption{A Sudoku game board and the corresponding colored graph.}
  4097. \label{fig:sudoku-graph}
  4098. \end{figure}
  4099. Some techniques for playing Sudoku correspond to heuristics used in
  4100. graph coloring algorithms. For example, one of the basic techniques
  4101. for Sudoku is called Pencil Marks. The idea is to use a process of
  4102. elimination to determine what numbers are no longer available for a
  4103. square and write down those numbers in the square (writing very
  4104. small). For example, if the number $1$ is assigned to a square, then
  4105. write the pencil mark $1$ in all the squares in the same row, column,
  4106. and region to indicate that $1$ is no longer an option for those other
  4107. squares.
  4108. %
  4109. The Pencil Marks technique corresponds to the notion of
  4110. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4111. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4112. are no longer available. In graph terminology, we have the following
  4113. definition:
  4114. \begin{equation*}
  4115. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4116. \text{ and } \mathrm{color}(v) = c \}
  4117. \end{equation*}
  4118. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4119. edge with $u$.
  4120. Using the Pencil Marks technique leads to a simple strategy for
  4121. filling in numbers: if there is a square with only one possible number
  4122. left, then choose that number! But what if there are no squares with
  4123. only one possibility left? One brute-force approach is to try them
  4124. all: choose the first one and if that ultimately leads to a solution,
  4125. great. If not, backtrack and choose the next possibility. One good
  4126. thing about Pencil Marks is that it reduces the degree of branching in
  4127. the search tree. Nevertheless, backtracking can be terribly time
  4128. consuming. One way to reduce the amount of backtracking is to use the
  4129. most-constrained-first heuristic (aka. minimum remaining
  4130. values)~\citep{Russell2003}. That is, when choosing a square, always
  4131. choose one with the fewest possibilities left (the vertex with the
  4132. highest saturation). The idea is that choosing highly constrained
  4133. squares earlier rather than later is better because later on there may
  4134. not be any possibilities left in the highly saturated squares.
  4135. However, register allocation is easier than Sudoku because the
  4136. register allocator can map variables to stack locations when the
  4137. registers run out. Thus, it makes sense to replace backtracking with
  4138. greedy search: make the best choice at the time and keep going. We
  4139. still wish to minimize the number of colors needed, so we use the
  4140. most-constrained-first heuristic in the greedy search.
  4141. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4142. algorithm for register allocation based on saturation and the
  4143. most-constrained-first heuristic. It is roughly equivalent to the
  4144. DSATUR
  4145. algorithm~\citep{Brelaz:1979eu}.
  4146. %,Gebremedhin:1999fk,Omari:2006uq
  4147. Just as in Sudoku, the algorithm represents colors with integers. The
  4148. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4149. for register allocation. The integers $k$ and larger correspond to
  4150. stack locations. The registers that are not used for register
  4151. allocation, such as \code{rax}, are assigned to negative integers. In
  4152. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4153. %% One might wonder why we include registers at all in the liveness
  4154. %% analysis and interference graph. For example, we never allocate a
  4155. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4156. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  4157. %% to use register for passing arguments to functions, it will be
  4158. %% necessary for those registers to appear in the interference graph
  4159. %% because those registers will also be assigned to variables, and we
  4160. %% don't want those two uses to encroach on each other. Regarding
  4161. %% registers such as \code{rax} and \code{rsp} that are not used for
  4162. %% variables, we could omit them from the interference graph but that
  4163. %% would require adding special cases to our algorithm, which would
  4164. %% complicate the logic for little gain.
  4165. \begin{figure}[btp]
  4166. \centering
  4167. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4168. Algorithm: DSATUR
  4169. Input: a graph |$G$|
  4170. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4171. |$W \gets \mathrm{vertices}(G)$|
  4172. while |$W \neq \emptyset$| do
  4173. pick a vertex |$u$| from |$W$| with the highest saturation,
  4174. breaking ties randomly
  4175. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4176. |$\mathrm{color}[u] \gets c$|
  4177. |$W \gets W - \{u\}$|
  4178. \end{lstlisting}
  4179. \caption{The saturation-based greedy graph coloring algorithm.}
  4180. \label{fig:satur-algo}
  4181. \end{figure}
  4182. {\if\edition\racketEd\color{olive}
  4183. With the DSATUR algorithm in hand, let us return to the running
  4184. example and consider how to color the interference graph in
  4185. Figure~\ref{fig:interfere}.
  4186. %
  4187. We start by assigning the register nodes to their own color. For
  4188. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4189. assigned $-2$. The variables are not yet colored, so they are
  4190. annotated with a dash. We then update the saturation for vertices that
  4191. are adjacent to a register, obtaining the following annotated
  4192. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4193. it interferes with both \code{rax} and \code{rsp}.
  4194. \[
  4195. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4196. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4197. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4198. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4199. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4200. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4201. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4202. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4203. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4204. \draw (t1) to (rax);
  4205. \draw (t1) to (z);
  4206. \draw (z) to (y);
  4207. \draw (z) to (w);
  4208. \draw (x) to (w);
  4209. \draw (y) to (w);
  4210. \draw (v) to (w);
  4211. \draw (v) to (rsp);
  4212. \draw (w) to (rsp);
  4213. \draw (x) to (rsp);
  4214. \draw (y) to (rsp);
  4215. \path[-.,bend left=15] (z) edge node {} (rsp);
  4216. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4217. \draw (rax) to (rsp);
  4218. \end{tikzpicture}
  4219. \]
  4220. The algorithm says to select a maximally saturated vertex. So we pick
  4221. $\ttm{t}$ and color it with the first available integer, which is
  4222. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4223. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4224. \[
  4225. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4226. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4227. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4228. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4229. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4230. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4231. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4232. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4233. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4234. \draw (t1) to (rax);
  4235. \draw (t1) to (z);
  4236. \draw (z) to (y);
  4237. \draw (z) to (w);
  4238. \draw (x) to (w);
  4239. \draw (y) to (w);
  4240. \draw (v) to (w);
  4241. \draw (v) to (rsp);
  4242. \draw (w) to (rsp);
  4243. \draw (x) to (rsp);
  4244. \draw (y) to (rsp);
  4245. \path[-.,bend left=15] (z) edge node {} (rsp);
  4246. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4247. \draw (rax) to (rsp);
  4248. \end{tikzpicture}
  4249. \]
  4250. We repeat the process, selecting a maximally saturated vertex,
  4251. choosing is \code{z}, and color it with the first available number, which
  4252. is $1$. We add $1$ to the saturation for the neighboring vertices
  4253. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4254. \[
  4255. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4256. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4257. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4258. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4259. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4260. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4261. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4262. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4263. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4264. \draw (t1) to (rax);
  4265. \draw (t1) to (z);
  4266. \draw (z) to (y);
  4267. \draw (z) to (w);
  4268. \draw (x) to (w);
  4269. \draw (y) to (w);
  4270. \draw (v) to (w);
  4271. \draw (v) to (rsp);
  4272. \draw (w) to (rsp);
  4273. \draw (x) to (rsp);
  4274. \draw (y) to (rsp);
  4275. \path[-.,bend left=15] (z) edge node {} (rsp);
  4276. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4277. \draw (rax) to (rsp);
  4278. \end{tikzpicture}
  4279. \]
  4280. The most saturated vertices are now \code{w} and \code{y}. We color
  4281. \code{w} with the first available color, which is $0$.
  4282. \[
  4283. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4284. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4285. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4286. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4287. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4288. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4289. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4290. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4291. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4292. \draw (t1) to (rax);
  4293. \draw (t1) to (z);
  4294. \draw (z) to (y);
  4295. \draw (z) to (w);
  4296. \draw (x) to (w);
  4297. \draw (y) to (w);
  4298. \draw (v) to (w);
  4299. \draw (v) to (rsp);
  4300. \draw (w) to (rsp);
  4301. \draw (x) to (rsp);
  4302. \draw (y) to (rsp);
  4303. \path[-.,bend left=15] (z) edge node {} (rsp);
  4304. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4305. \draw (rax) to (rsp);
  4306. \end{tikzpicture}
  4307. \]
  4308. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4309. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4310. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4311. and \code{z}, whose colors are $0$ and $1$ respectively.
  4312. \[
  4313. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4314. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4315. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4316. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4317. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4318. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4319. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4320. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4321. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4322. \draw (t1) to (rax);
  4323. \draw (t1) to (z);
  4324. \draw (z) to (y);
  4325. \draw (z) to (w);
  4326. \draw (x) to (w);
  4327. \draw (y) to (w);
  4328. \draw (v) to (w);
  4329. \draw (v) to (rsp);
  4330. \draw (w) to (rsp);
  4331. \draw (x) to (rsp);
  4332. \draw (y) to (rsp);
  4333. \path[-.,bend left=15] (z) edge node {} (rsp);
  4334. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4335. \draw (rax) to (rsp);
  4336. \end{tikzpicture}
  4337. \]
  4338. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4339. \[
  4340. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4341. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4342. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4343. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4344. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4345. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4346. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4347. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4348. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4349. \draw (t1) to (rax);
  4350. \draw (t1) to (z);
  4351. \draw (z) to (y);
  4352. \draw (z) to (w);
  4353. \draw (x) to (w);
  4354. \draw (y) to (w);
  4355. \draw (v) to (w);
  4356. \draw (v) to (rsp);
  4357. \draw (w) to (rsp);
  4358. \draw (x) to (rsp);
  4359. \draw (y) to (rsp);
  4360. \path[-.,bend left=15] (z) edge node {} (rsp);
  4361. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4362. \draw (rax) to (rsp);
  4363. \end{tikzpicture}
  4364. \]
  4365. In the last step of the algorithm, we color \code{x} with $1$.
  4366. \[
  4367. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4368. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4369. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4370. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4371. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4372. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4373. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4374. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4375. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4376. \draw (t1) to (rax);
  4377. \draw (t1) to (z);
  4378. \draw (z) to (y);
  4379. \draw (z) to (w);
  4380. \draw (x) to (w);
  4381. \draw (y) to (w);
  4382. \draw (v) to (w);
  4383. \draw (v) to (rsp);
  4384. \draw (w) to (rsp);
  4385. \draw (x) to (rsp);
  4386. \draw (y) to (rsp);
  4387. \path[-.,bend left=15] (z) edge node {} (rsp);
  4388. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4389. \draw (rax) to (rsp);
  4390. \end{tikzpicture}
  4391. \]
  4392. So we obtain the following coloring:
  4393. \[
  4394. \{
  4395. \ttm{rax} \mapsto -1,
  4396. \ttm{rsp} \mapsto -2,
  4397. \ttm{t} \mapsto 0,
  4398. \ttm{z} \mapsto 1,
  4399. \ttm{x} \mapsto 1,
  4400. \ttm{y} \mapsto 2,
  4401. \ttm{w} \mapsto 0,
  4402. \ttm{v} \mapsto 1
  4403. \}
  4404. \]
  4405. \fi}
  4406. %
  4407. {\if\edition\pythonEd\color{purple}
  4408. %
  4409. With the DSATUR algorithm in hand, let us return to the running
  4410. example and consider how to color the interference graph in
  4411. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4412. to indicate that it has not yet been assigned a color. The saturation
  4413. sets are also shown for each node; all of them start as the empty set.
  4414. (We do not include the register nodes in the graph below because there
  4415. were no interference edges involving registers in this program, but in
  4416. general there can be.)
  4417. %
  4418. \[
  4419. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4420. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4421. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4422. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4423. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4424. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4425. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4426. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4427. \draw (t0) to (t1);
  4428. \draw (t0) to (z);
  4429. \draw (z) to (y);
  4430. \draw (z) to (w);
  4431. \draw (x) to (w);
  4432. \draw (y) to (w);
  4433. \draw (v) to (w);
  4434. \end{tikzpicture}
  4435. \]
  4436. The algorithm says to select a maximally saturated vertex. So we pick
  4437. $\ttm{tmp\_0}$ and color it with the first available integer, which is
  4438. $0$. We mark $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$
  4439. because they interfere with $\ttm{tmp\_0}$.
  4440. \[
  4441. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4442. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4443. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4444. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4445. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4446. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4447. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4448. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4449. \draw (t0) to (t1);
  4450. \draw (t0) to (z);
  4451. \draw (z) to (y);
  4452. \draw (z) to (w);
  4453. \draw (x) to (w);
  4454. \draw (y) to (w);
  4455. \draw (v) to (w);
  4456. \end{tikzpicture}
  4457. \]
  4458. We repeat the process, selecting a maximally saturated vertex,
  4459. choosing \code{z}, and color it with the first available number, which
  4460. is $1$. We add $1$ to the saturation for the neighboring vertices
  4461. \code{tmp\_0}, \code{y}, and \code{w}.
  4462. \[
  4463. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4464. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4465. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4466. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4467. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4468. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4469. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4470. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4471. \draw (t0) to (t1);
  4472. \draw (t0) to (z);
  4473. \draw (z) to (y);
  4474. \draw (z) to (w);
  4475. \draw (x) to (w);
  4476. \draw (y) to (w);
  4477. \draw (v) to (w);
  4478. \end{tikzpicture}
  4479. \]
  4480. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4481. \code{y}. We color \code{w} with the first available color, which
  4482. is $0$.
  4483. \[
  4484. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4485. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4486. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4487. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4488. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4489. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4490. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4491. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4492. \draw (t0) to (t1);
  4493. \draw (t0) to (z);
  4494. \draw (z) to (y);
  4495. \draw (z) to (w);
  4496. \draw (x) to (w);
  4497. \draw (y) to (w);
  4498. \draw (v) to (w);
  4499. \end{tikzpicture}
  4500. \]
  4501. Now \code{y} is the most saturated, so we color it with $2$.
  4502. \[
  4503. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4504. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4505. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4506. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4507. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4508. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4509. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4510. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4511. \draw (t0) to (t1);
  4512. \draw (t0) to (z);
  4513. \draw (z) to (y);
  4514. \draw (z) to (w);
  4515. \draw (x) to (w);
  4516. \draw (y) to (w);
  4517. \draw (v) to (w);
  4518. \end{tikzpicture}
  4519. \]
  4520. Now \code{tmp\_1}, \code{x}, and \code{v} are equally saturated.
  4521. We choose to color \code{v} with $1$.
  4522. \[
  4523. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4524. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4525. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4526. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4527. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4528. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4529. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4530. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4531. \draw (t0) to (t1);
  4532. \draw (t0) to (z);
  4533. \draw (z) to (y);
  4534. \draw (z) to (w);
  4535. \draw (x) to (w);
  4536. \draw (y) to (w);
  4537. \draw (v) to (w);
  4538. \end{tikzpicture}
  4539. \]
  4540. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4541. \[
  4542. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4543. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4544. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4545. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4546. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4547. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4548. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4549. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4550. \draw (t0) to (t1);
  4551. \draw (t0) to (z);
  4552. \draw (z) to (y);
  4553. \draw (z) to (w);
  4554. \draw (x) to (w);
  4555. \draw (y) to (w);
  4556. \draw (v) to (w);
  4557. \end{tikzpicture}
  4558. \]
  4559. So we obtain the following coloring:
  4560. \[
  4561. \{ \ttm{tmp\_0} \mapsto 0,
  4562. \ttm{tmp\_1} \mapsto 1,
  4563. \ttm{z} \mapsto 1,
  4564. \ttm{x} \mapsto 1,
  4565. \ttm{y} \mapsto 2,
  4566. \ttm{w} \mapsto 0,
  4567. \ttm{v} \mapsto 1 \}
  4568. \]
  4569. \fi}
  4570. We recommend creating an auxiliary function named \code{color\_graph}
  4571. that takes an interference graph and a list of all the variables in
  4572. the program. This function should return a mapping of variables to
  4573. their colors (represented as natural numbers). By creating this helper
  4574. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4575. when we add support for functions.
  4576. To prioritize the processing of highly saturated nodes inside the
  4577. \code{color\_graph} function, we recommend using the priority queue
  4578. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4579. addition, you will need to maintain a mapping from variables to their
  4580. ``handles'' in the priority queue so that you can notify the priority
  4581. queue when their saturation changes.}
  4582. {\if\edition\racketEd\color{olive}
  4583. \begin{figure}[tp]
  4584. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4585. \small
  4586. \begin{tcolorbox}[title=Priority Queue]
  4587. A \emph{priority queue} is a collection of items in which the
  4588. removal of items is governed by priority. In a ``min'' queue,
  4589. lower priority items are removed first. An implementation is in
  4590. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4591. queue} \index{subject}{minimum priority queue}
  4592. \begin{description}
  4593. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4594. priority queue that uses the $\itm{cmp}$ predicate to determine
  4595. whether its first argument has lower or equal priority to its
  4596. second argument.
  4597. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4598. items in the queue.
  4599. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4600. the item into the queue and returns a handle for the item in the
  4601. queue.
  4602. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4603. the lowest priority.
  4604. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4605. notifies the queue that the priority has decreased for the item
  4606. associated with the given handle.
  4607. \end{description}
  4608. \end{tcolorbox}
  4609. %\end{wrapfigure}
  4610. \caption{The priority queue data structure.}
  4611. \label{fig:priority-queue}
  4612. \end{figure}
  4613. \fi}
  4614. With the coloring complete, we finalize the assignment of variables to
  4615. registers and stack locations. We map the first $k$ colors to the $k$
  4616. registers and the rest of the colors to stack locations. Suppose for
  4617. the moment that we have just one register to use for register
  4618. allocation, \key{rcx}. Then we have the following map from colors to
  4619. locations.
  4620. \[
  4621. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4622. \]
  4623. Composing this mapping with the coloring, we arrive at the following
  4624. assignment of variables to locations.
  4625. {\if\edition\racketEd\color{olive}
  4626. \begin{gather*}
  4627. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4628. \ttm{w} \mapsto \key{\%rcx}, \,
  4629. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4630. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4631. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4632. \ttm{t} \mapsto \key{\%rcx} \}
  4633. \end{gather*}
  4634. \fi}
  4635. {\if\edition\pythonEd\color{purple}
  4636. \begin{gather*}
  4637. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4638. \ttm{w} \mapsto \key{\%rcx}, \,
  4639. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4640. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4641. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4642. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4643. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4644. \end{gather*}
  4645. \fi}
  4646. Adapt the code from the \code{assign\_homes} pass
  4647. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  4648. assigned location. Applying the above assignment to our running
  4649. example, on the left, yields the program on the right.
  4650. % why frame size of 32? -JGS
  4651. \begin{center}
  4652. {\if\edition\racketEd\color{olive}
  4653. \begin{minipage}{0.3\textwidth}
  4654. \begin{lstlisting}
  4655. movq $1, v
  4656. movq $42, w
  4657. movq v, x
  4658. addq $7, x
  4659. movq x, y
  4660. movq x, z
  4661. addq w, z
  4662. movq y, t
  4663. negq t
  4664. movq z, %rax
  4665. addq t, %rax
  4666. jmp conclusion
  4667. \end{lstlisting}
  4668. \end{minipage}
  4669. $\Rightarrow\qquad$
  4670. \begin{minipage}{0.45\textwidth}
  4671. \begin{lstlisting}
  4672. movq $1, -8(%rbp)
  4673. movq $42, %rcx
  4674. movq -8(%rbp), -8(%rbp)
  4675. addq $7, -8(%rbp)
  4676. movq -8(%rbp), -16(%rbp)
  4677. movq -8(%rbp), -8(%rbp)
  4678. addq %rcx, -8(%rbp)
  4679. movq -16(%rbp), %rcx
  4680. negq %rcx
  4681. movq -8(%rbp), %rax
  4682. addq %rcx, %rax
  4683. jmp conclusion
  4684. \end{lstlisting}
  4685. \end{minipage}
  4686. \fi}
  4687. {\if\edition\pythonEd\color{purple}
  4688. \begin{minipage}{0.3\textwidth}
  4689. \begin{lstlisting}
  4690. movq $1, v
  4691. movq $42, w
  4692. movq v, x
  4693. addq $7, x
  4694. movq x, y
  4695. movq x, z
  4696. addq w, z
  4697. movq y, tmp_0
  4698. negq tmp_0
  4699. movq z, tmp_1
  4700. addq tmp_0, tmp_1
  4701. movq tmp_1, %rdi
  4702. callq print_int
  4703. \end{lstlisting}
  4704. \end{minipage}
  4705. $\Rightarrow\qquad$
  4706. \begin{minipage}{0.45\textwidth}
  4707. \begin{lstlisting}
  4708. movq $1, -8(%rbp)
  4709. movq $42, %rcx
  4710. movq -8(%rbp), -8(%rbp)
  4711. addq $7, -8(%rbp)
  4712. movq -8(%rbp), -16(%rbp)
  4713. movq -8(%rbp), -8(%rbp)
  4714. addq %rcx, -8(%rbp)
  4715. movq -16(%rbp), %rcx
  4716. negq %rcx
  4717. movq -8(%rbp), -8(%rbp)
  4718. addq %rcx, -8(%rbp)
  4719. movq -8(%rbp), %rdi
  4720. callq print_int
  4721. \end{lstlisting}
  4722. \end{minipage}
  4723. \fi}
  4724. \end{center}
  4725. \begin{exercise}\normalfont
  4726. %
  4727. Implement the compiler pass \code{allocate\_registers}.
  4728. %
  4729. Create five programs that exercise all of the register allocation
  4730. algorithm, including spilling variables to the stack.
  4731. %
  4732. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  4733. \code{run-tests.rkt} script with the three new passes:
  4734. \code{uncover\_live}, \code{build\_interference}, and
  4735. \code{allocate\_registers}.
  4736. %
  4737. Temporarily remove the \code{print\_x86} pass from the list of passes
  4738. and the call to \code{compiler-tests}.
  4739. Run the script to test the register allocator.
  4740. }
  4741. %
  4742. \python{Run the \code{run-tests.py} script to to check whether the
  4743. output programs produce the same result as the input programs.}
  4744. \end{exercise}
  4745. \section{Patch Instructions}
  4746. \label{sec:patch-instructions}
  4747. The remaining step in the compilation to x86 is to ensure that the
  4748. instructions have at most one argument that is a memory access.
  4749. %
  4750. In the running example, the instruction \code{movq -8(\%rbp),
  4751. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  4752. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  4753. then move \code{rax} into \code{-16(\%rbp)}.
  4754. %
  4755. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4756. problematic, but it can simply be deleted. In general, we recommend
  4757. deleting all the trivial moves whose source and destination are the
  4758. same location.
  4759. %
  4760. The following is the output of \code{patch\_instructions} on the
  4761. running example.
  4762. \begin{center}
  4763. {\if\edition\racketEd\color{olive}
  4764. \begin{minipage}{0.4\textwidth}
  4765. \begin{lstlisting}
  4766. movq $1, -8(%rbp)
  4767. movq $42, %rcx
  4768. movq -8(%rbp), -8(%rbp)
  4769. addq $7, -8(%rbp)
  4770. movq -8(%rbp), -16(%rbp)
  4771. movq -8(%rbp), -8(%rbp)
  4772. addq %rcx, -8(%rbp)
  4773. movq -16(%rbp), %rcx
  4774. negq %rcx
  4775. movq -8(%rbp), %rax
  4776. addq %rcx, %rax
  4777. jmp conclusion
  4778. \end{lstlisting}
  4779. \end{minipage}
  4780. $\Rightarrow\qquad$
  4781. \begin{minipage}{0.45\textwidth}
  4782. \begin{lstlisting}
  4783. movq $1, -8(%rbp)
  4784. movq $42, %rcx
  4785. addq $7, -8(%rbp)
  4786. movq -8(%rbp), %rax
  4787. movq %rax, -16(%rbp)
  4788. addq %rcx, -8(%rbp)
  4789. movq -16(%rbp), %rcx
  4790. negq %rcx
  4791. movq -8(%rbp), %rax
  4792. addq %rcx, %rax
  4793. jmp conclusion
  4794. \end{lstlisting}
  4795. \end{minipage}
  4796. \fi}
  4797. {\if\edition\pythonEd\color{purple}
  4798. \begin{minipage}{0.4\textwidth}
  4799. \begin{lstlisting}
  4800. movq $1, -8(%rbp)
  4801. movq $42, %rcx
  4802. movq -8(%rbp), -8(%rbp)
  4803. addq $7, -8(%rbp)
  4804. movq -8(%rbp), -16(%rbp)
  4805. movq -8(%rbp), -8(%rbp)
  4806. addq %rcx, -8(%rbp)
  4807. movq -16(%rbp), %rcx
  4808. negq %rcx
  4809. movq -8(%rbp), -8(%rbp)
  4810. addq %rcx, -8(%rbp)
  4811. movq -8(%rbp), %rdi
  4812. callq print_int
  4813. \end{lstlisting}
  4814. \end{minipage}
  4815. $\Rightarrow\qquad$
  4816. \begin{minipage}{0.45\textwidth}
  4817. \begin{lstlisting}
  4818. movq $1, -8(%rbp)
  4819. movq $42, %rcx
  4820. addq $7, -8(%rbp)
  4821. movq -8(%rbp), %rax
  4822. movq %rax, -16(%rbp)
  4823. addq %rcx, -8(%rbp)
  4824. movq -16(%rbp), %rcx
  4825. negq %rcx
  4826. addq %rcx, -8(%rbp)
  4827. movq -8(%rbp), %rdi
  4828. callq print_int
  4829. \end{lstlisting}
  4830. \end{minipage}
  4831. \fi}
  4832. \end{center}
  4833. \begin{exercise}\normalfont
  4834. %
  4835. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  4836. %
  4837. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  4838. %in the \code{run-tests.rkt} script.
  4839. %
  4840. Run the script to test the \code{patch\_instructions} pass.
  4841. \end{exercise}
  4842. \section{Print x86}
  4843. \label{sec:print-x86-reg-alloc}
  4844. \index{subject}{calling conventions}
  4845. \index{subject}{prelude}\index{subject}{conclusion}
  4846. Recall that the \code{print\_x86} pass generates the prelude and
  4847. conclusion instructions to satisfy the x86 calling conventions
  4848. (Section~\ref{sec:calling-conventions}). With the addition of the
  4849. register allocator, the callee-saved registers used by the register
  4850. allocator must be saved in the prelude and restored in the conclusion.
  4851. In the \code{allocate\_registers} pass,
  4852. %
  4853. \racket{add an entry to the \itm{info}
  4854. of \code{X86Program} named \code{used\_callee}}
  4855. %
  4856. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  4857. %
  4858. that stores the set of
  4859. callee-saved registers that were assigned to variables. The
  4860. \code{print\_x86} pass can then access this information to decide which
  4861. callee-saved registers need to be saved and restored.
  4862. %
  4863. When calculating the size of the frame to adjust the \code{rsp} in the
  4864. prelude, make sure to take into account the space used for saving the
  4865. callee-saved registers. Also, don't forget that the frame needs to be
  4866. a multiple of 16 bytes!
  4867. An overview of all of the passes involved in register allocation is
  4868. shown in Figure~\ref{fig:reg-alloc-passes}.
  4869. \begin{figure}[tbp]
  4870. {\if\edition\racketEd\color{olive}
  4871. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4872. \node (Rvar) at (0,2) {\large \LangVar{}};
  4873. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4874. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  4875. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  4876. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  4877. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  4878. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  4879. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  4880. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  4881. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  4882. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  4883. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-3);
  4884. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  4885. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  4886. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  4887. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  4888. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  4889. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  4890. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  4891. \end{tikzpicture}
  4892. \fi}
  4893. {\if\edition\pythonEd\color{purple}
  4894. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4895. \node (Rvar-1) at (0,2) {\large \LangVar{}};
  4896. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4897. \node (x86-1) at (3,0) {\large \LangXVar{}};
  4898. \node (x86-2) at (6,0) {\large \LangXVar{}};
  4899. \node (x86-3) at (9,0) {\large \LangXInt{}};
  4900. \node (x86-4) at (11,0) {\large \LangXInt{}};
  4901. \path[->,bend left=15] (Rvar-1) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-2);
  4902. \path[->,bend right=15] (Rvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  4903. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize allocate\_reg.} (x86-2);
  4904. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  4905. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86} (x86-4);
  4906. \end{tikzpicture}
  4907. \fi}
  4908. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  4909. \label{fig:reg-alloc-passes}
  4910. \end{figure}
  4911. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  4912. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  4913. use of registers and the stack, we have limited the register allocator
  4914. to use just two registers: \code{rbx} and \code{rcx}. In the
  4915. prelude\index{subject}{prelude} of the \code{main} function, we push
  4916. \code{rbx} onto the stack because it is a callee-saved register and it
  4917. was assigned to variable by the register allocator. We subtract
  4918. \code{8} from the \code{rsp} at the end of the prelude to reserve
  4919. space for the one spilled variable. After that subtraction, the
  4920. \code{rsp} is aligned to 16 bytes.
  4921. Moving on to the program proper, we see how the registers were
  4922. allocated.
  4923. %
  4924. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  4925. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  4926. %
  4927. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  4928. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  4929. were assigned to \code{rbx}.}
  4930. %
  4931. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  4932. location \code{-16(\%rbp)}. Recall that the prelude saved the
  4933. callee-save register \code{rbx} onto the stack. The spilled variables
  4934. must be placed lower on the stack than the saved callee-save
  4935. registers, so in this case \racket{\code{w}}\python{z} is placed at
  4936. \code{-16(\%rbp)}.
  4937. In the conclusion\index{subject}{conclusion}, we undo the work that was
  4938. done in the prelude. We move the stack pointer up by \code{8} bytes
  4939. (the room for spilled variables), then we pop the old values of
  4940. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  4941. \code{retq} to return control to the operating system.
  4942. \begin{figure}[tbp]
  4943. % var_test_28.rkt
  4944. % (use-minimal-set-of-registers! #t)
  4945. % and only rbx rcx
  4946. % tmp 0 rbx
  4947. % z 1 rcx
  4948. % y 0 rbx
  4949. % w 2 16(%rbp)
  4950. % v 0 rbx
  4951. % x 0 rbx
  4952. {\if\edition\racketEd\color{olive}
  4953. \begin{lstlisting}
  4954. start:
  4955. movq $1, %rbx
  4956. movq $42, -16(%rbp)
  4957. addq $7, %rbx
  4958. movq %rbx, %rcx
  4959. addq -16(%rbp), %rcx
  4960. negq %rbx
  4961. movq %rcx, %rax
  4962. addq %rbx, %rax
  4963. jmp conclusion
  4964. .globl main
  4965. main:
  4966. pushq %rbp
  4967. movq %rsp, %rbp
  4968. pushq %rbx
  4969. subq $8, %rsp
  4970. jmp start
  4971. conclusion:
  4972. addq $8, %rsp
  4973. popq %rbx
  4974. popq %rbp
  4975. retq
  4976. \end{lstlisting}
  4977. \fi}
  4978. {\if\edition\pythonEd\color{purple}
  4979. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  4980. \begin{lstlisting}
  4981. .globl main
  4982. main:
  4983. pushq %rbp
  4984. movq %rsp, %rbp
  4985. pushq %rbx
  4986. subq $8, %rsp
  4987. movq $1, %rcx
  4988. movq $42, %rbx
  4989. addq $7, %rcx
  4990. movq %rcx, -16(%rbp)
  4991. addq %rbx, -16(%rbp)
  4992. negq %rcx
  4993. movq -16(%rbp), %rbx
  4994. addq %rcx, %rbx
  4995. movq %rbx, %rdi
  4996. callq print_int
  4997. addq $8, %rsp
  4998. popq %rbx
  4999. popq %rbp
  5000. retq
  5001. \end{lstlisting}
  5002. \fi}
  5003. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  5004. \label{fig:running-example-x86}
  5005. \end{figure}
  5006. \begin{exercise}\normalfont
  5007. Update the \code{print\_x86} pass as described in this section.
  5008. %
  5009. \racket{
  5010. In the \code{run-tests.rkt} script, reinstate \code{print\_x86} in the
  5011. list of passes and the call to \code{compiler-tests}.}
  5012. %
  5013. Run the script to test the complete compiler for \LangVar{} that
  5014. performs register allocation.
  5015. \end{exercise}
  5016. \section{Challenge: Move Biasing}
  5017. \label{sec:move-biasing}
  5018. \index{subject}{move biasing}
  5019. This section describes an enhancement to the register allocator for
  5020. students looking for an extra challenge or who have a deeper interest
  5021. in register allocation.
  5022. {\if\edition\racketEd\color{olive}
  5023. To motivate the need for move biasing we return to the running example
  5024. but this time use all of the general purpose registers. So we have
  5025. the following mapping of color numbers to registers.
  5026. \[
  5027. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5028. \]
  5029. Using the same assignment of variables to color numbers that was
  5030. produced by the register allocator described in the last section, we
  5031. get the following program.
  5032. \begin{center}
  5033. \begin{minipage}{0.3\textwidth}
  5034. \begin{lstlisting}
  5035. movq $1, v
  5036. movq $42, w
  5037. movq v, x
  5038. addq $7, x
  5039. movq x, y
  5040. movq x, z
  5041. addq w, z
  5042. movq y, t
  5043. negq t
  5044. movq z, %rax
  5045. addq t, %rax
  5046. jmp conclusion
  5047. \end{lstlisting}
  5048. \end{minipage}
  5049. $\Rightarrow\qquad$
  5050. \begin{minipage}{0.45\textwidth}
  5051. \begin{lstlisting}
  5052. movq $1, %rdx
  5053. movq $42, %rcx
  5054. movq %rdx, %rdx
  5055. addq $7, %rdx
  5056. movq %rdx, %rsi
  5057. movq %rdx, %rdx
  5058. addq %rcx, %rdx
  5059. movq %rsi, %rcx
  5060. negq %rcx
  5061. movq %rdx, %rax
  5062. addq %rcx, %rax
  5063. jmp conclusion
  5064. \end{lstlisting}
  5065. \end{minipage}
  5066. \end{center}
  5067. In the above output code there are two \key{movq} instructions that
  5068. can be removed because their source and target are the same. However,
  5069. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5070. register, we could instead remove three \key{movq} instructions. We
  5071. can accomplish this by taking into account which variables appear in
  5072. \key{movq} instructions with which other variables.
  5073. \fi}
  5074. {\if\edition\pythonEd\color{purple}
  5075. %
  5076. To motivate the need for move biasing we return to the running example
  5077. and recall that Section~\ref{sec:patch-instructions} we were able to
  5078. remove three trivial move instructions from the running
  5079. example. However, we could remove another trivial move if we were able
  5080. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5081. We say that two variables $p$ and $q$ are \emph{move
  5082. related}\index{subject}{move related} if they participate together in a
  5083. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5084. \key{movq} $q$\key{,} $p$. When deciding which variable to
  5085. color next, when there are multiple variables with the same
  5086. saturation, prefer variables that can be assigned the same
  5087. color as a move related variable that has already been colored.
  5088. Furthermore, when the register allocator chooses a color
  5089. for a variable, it should prefer a color that has already been used
  5090. for a move-related variable (assuming that they do not interfere). Of
  5091. course, this preference should not override the preference for
  5092. registers over stack locations. This preference should be used as a
  5093. tie breaker when choosing between registers or when choosing between
  5094. stack locations.
  5095. We recommend representing the move relationships in a graph, similar
  5096. to how we represented interference. The following is the \emph{move
  5097. graph} for our running example.
  5098. {\if\edition\racketEd\color{olive}
  5099. \[
  5100. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5101. \node (rax) at (0,0) {$\ttm{rax}$};
  5102. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5103. \node (t) at (0,2) {$\ttm{t}$};
  5104. \node (z) at (3,2) {$\ttm{z}$};
  5105. \node (x) at (6,2) {$\ttm{x}$};
  5106. \node (y) at (3,0) {$\ttm{y}$};
  5107. \node (w) at (6,0) {$\ttm{w}$};
  5108. \node (v) at (9,0) {$\ttm{v}$};
  5109. \draw (v) to (x);
  5110. \draw (x) to (y);
  5111. \draw (x) to (z);
  5112. \draw (y) to (t);
  5113. \end{tikzpicture}
  5114. \]
  5115. \fi}
  5116. %
  5117. {\if\edition\pythonEd\color{purple}
  5118. \[
  5119. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5120. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5121. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5122. \node (z) at (3,2) {$\ttm{z}$};
  5123. \node (x) at (6,2) {$\ttm{x}$};
  5124. \node (y) at (3,0) {$\ttm{y}$};
  5125. \node (w) at (6,0) {$\ttm{w}$};
  5126. \node (v) at (9,0) {$\ttm{v}$};
  5127. \draw (y) to (t0);
  5128. \draw (z) to (x);
  5129. \draw (z) to (t1);
  5130. \draw (x) to (y);
  5131. \draw (x) to (v);
  5132. \end{tikzpicture}
  5133. \]
  5134. \fi}
  5135. {\if\edition\racketEd\color{olive}
  5136. Now we replay the graph coloring, pausing to see the coloring of
  5137. \code{y}. Recall the following configuration. The most saturated vertices
  5138. were \code{w} and \code{y}.
  5139. \[
  5140. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5141. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5142. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5143. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5144. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5145. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5146. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5147. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5148. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5149. \draw (t1) to (rax);
  5150. \draw (t1) to (z);
  5151. \draw (z) to (y);
  5152. \draw (z) to (w);
  5153. \draw (x) to (w);
  5154. \draw (y) to (w);
  5155. \draw (v) to (w);
  5156. \draw (v) to (rsp);
  5157. \draw (w) to (rsp);
  5158. \draw (x) to (rsp);
  5159. \draw (y) to (rsp);
  5160. \path[-.,bend left=15] (z) edge node {} (rsp);
  5161. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5162. \draw (rax) to (rsp);
  5163. \end{tikzpicture}
  5164. \]
  5165. %
  5166. Last time we chose to color \code{w} with $0$. But this time we see
  5167. that \code{w} is not move related to any vertex, but \code{y} is move
  5168. related to \code{t}. So we choose to color \code{y} the same color as
  5169. \code{t}, $0$.
  5170. \[
  5171. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5172. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5173. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5174. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5175. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5176. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5177. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5178. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5179. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5180. \draw (t1) to (rax);
  5181. \draw (t1) to (z);
  5182. \draw (z) to (y);
  5183. \draw (z) to (w);
  5184. \draw (x) to (w);
  5185. \draw (y) to (w);
  5186. \draw (v) to (w);
  5187. \draw (v) to (rsp);
  5188. \draw (w) to (rsp);
  5189. \draw (x) to (rsp);
  5190. \draw (y) to (rsp);
  5191. \path[-.,bend left=15] (z) edge node {} (rsp);
  5192. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5193. \draw (rax) to (rsp);
  5194. \end{tikzpicture}
  5195. \]
  5196. Now \code{w} is the most saturated, so we color it $2$.
  5197. \[
  5198. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5199. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5200. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5201. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5202. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5203. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5204. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5205. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5206. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5207. \draw (t1) to (rax);
  5208. \draw (t1) to (z);
  5209. \draw (z) to (y);
  5210. \draw (z) to (w);
  5211. \draw (x) to (w);
  5212. \draw (y) to (w);
  5213. \draw (v) to (w);
  5214. \draw (v) to (rsp);
  5215. \draw (w) to (rsp);
  5216. \draw (x) to (rsp);
  5217. \draw (y) to (rsp);
  5218. \path[-.,bend left=15] (z) edge node {} (rsp);
  5219. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5220. \draw (rax) to (rsp);
  5221. \end{tikzpicture}
  5222. \]
  5223. At this point, vertices \code{x} and \code{v} are most saturated, but
  5224. \code{x} is move related to \code{y} and \code{z}, so we color
  5225. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5226. \[
  5227. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5228. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5229. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5230. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5231. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5232. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5233. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5234. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5235. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5236. \draw (t1) to (rax);
  5237. \draw (t) to (z);
  5238. \draw (z) to (y);
  5239. \draw (z) to (w);
  5240. \draw (x) to (w);
  5241. \draw (y) to (w);
  5242. \draw (v) to (w);
  5243. \draw (v) to (rsp);
  5244. \draw (w) to (rsp);
  5245. \draw (x) to (rsp);
  5246. \draw (y) to (rsp);
  5247. \path[-.,bend left=15] (z) edge node {} (rsp);
  5248. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5249. \draw (rax) to (rsp);
  5250. \end{tikzpicture}
  5251. \]
  5252. \fi}
  5253. %
  5254. {\if\edition\pythonEd\color{purple}
  5255. Now we replay the graph coloring, pausing before the coloring of
  5256. \code{w}. Recall the following configuration. The most saturated vertices
  5257. were \code{tmp\_1}, \code{w}, and \code{y}.
  5258. \[
  5259. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5260. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5261. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5262. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5263. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5264. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5265. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5266. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5267. \draw (t0) to (t1);
  5268. \draw (t0) to (z);
  5269. \draw (z) to (y);
  5270. \draw (z) to (w);
  5271. \draw (x) to (w);
  5272. \draw (y) to (w);
  5273. \draw (v) to (w);
  5274. \end{tikzpicture}
  5275. \]
  5276. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5277. or \code{y}, but note that \code{w} is not move related to any
  5278. variables, wheras \code{y} and \code{tmp\_1} are move related to
  5279. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5280. \code{y} and color it $0$, we can delete another move instruction.
  5281. \[
  5282. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5283. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5284. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5285. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5286. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5287. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5288. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5289. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5290. \draw (t0) to (t1);
  5291. \draw (t0) to (z);
  5292. \draw (z) to (y);
  5293. \draw (z) to (w);
  5294. \draw (x) to (w);
  5295. \draw (y) to (w);
  5296. \draw (v) to (w);
  5297. \end{tikzpicture}
  5298. \]
  5299. Now \code{w} is the most saturated, so we color it $2$.
  5300. \[
  5301. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5302. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5303. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5304. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5305. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5306. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5307. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5308. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5309. \draw (t0) to (t1);
  5310. \draw (t0) to (z);
  5311. \draw (z) to (y);
  5312. \draw (z) to (w);
  5313. \draw (x) to (w);
  5314. \draw (y) to (w);
  5315. \draw (v) to (w);
  5316. \end{tikzpicture}
  5317. \]
  5318. To finish the coloring, \code{x} and \code{v} get $0$ and
  5319. \code{tmp\_1} gets $1$.
  5320. \[
  5321. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5322. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5323. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5324. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5325. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5326. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5327. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5328. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5329. \draw (t0) to (t1);
  5330. \draw (t0) to (z);
  5331. \draw (z) to (y);
  5332. \draw (z) to (w);
  5333. \draw (x) to (w);
  5334. \draw (y) to (w);
  5335. \draw (v) to (w);
  5336. \end{tikzpicture}
  5337. \]
  5338. \fi}
  5339. So we have the following assignment of variables to registers.
  5340. {\if\edition\racketEd\color{olive}
  5341. \begin{gather*}
  5342. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5343. \ttm{w} \mapsto \key{\%rsi}, \,
  5344. \ttm{x} \mapsto \key{\%rcx}, \,
  5345. \ttm{y} \mapsto \key{\%rcx}, \,
  5346. \ttm{z} \mapsto \key{\%rdx}, \,
  5347. \ttm{t} \mapsto \key{\%rcx} \}
  5348. \end{gather*}
  5349. \fi}
  5350. {\if\edition\pythonEd\color{purple}
  5351. \begin{gather*}
  5352. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5353. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5354. \ttm{x} \mapsto \key{\%rcx}, \,
  5355. \ttm{y} \mapsto \key{\%rcx}, \\
  5356. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5357. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5358. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5359. \end{gather*}
  5360. \fi}
  5361. We apply this register assignment to the running example, on the left,
  5362. to obtain the code in the middle. The \code{patch\_instructions} then
  5363. deletes the trivial moves to obtain the code on the right.
  5364. {\if\edition\racketEd\color{olive}
  5365. \begin{minipage}{0.25\textwidth}
  5366. \begin{lstlisting}
  5367. movq $1, v
  5368. movq $42, w
  5369. movq v, x
  5370. addq $7, x
  5371. movq x, y
  5372. movq x, z
  5373. addq w, z
  5374. movq y, t
  5375. negq t
  5376. movq z, %rax
  5377. addq t, %rax
  5378. jmp conclusion
  5379. \end{lstlisting}
  5380. \end{minipage}
  5381. $\Rightarrow\qquad$
  5382. \begin{minipage}{0.25\textwidth}
  5383. \begin{lstlisting}
  5384. movq $1, %rcx
  5385. movq $42, %rsi
  5386. movq %rcx, %rcx
  5387. addq $7, %rcx
  5388. movq %rcx, %rcx
  5389. movq %rcx, %rdx
  5390. addq %rsi, %rdx
  5391. movq %rcx, %rcx
  5392. negq %rcx
  5393. movq %rdx, %rax
  5394. addq %rcx, %rax
  5395. jmp conclusion
  5396. \end{lstlisting}
  5397. \end{minipage}
  5398. $\Rightarrow\qquad$
  5399. \begin{minipage}{0.25\textwidth}
  5400. \begin{lstlisting}
  5401. movq $1, %rcx
  5402. movq $42, %rsi
  5403. addq $7, %rcx
  5404. movq %rcx, %rdx
  5405. addq %rsi, %rdx
  5406. negq %rcx
  5407. movq %rdx, %rax
  5408. addq %rcx, %rax
  5409. jmp conclusion
  5410. \end{lstlisting}
  5411. \end{minipage}
  5412. \fi}
  5413. {\if\edition\pythonEd\color{purple}
  5414. \begin{minipage}{0.25\textwidth}
  5415. \begin{lstlisting}
  5416. movq $1, v
  5417. movq $42, w
  5418. movq v, x
  5419. addq $7, x
  5420. movq x, y
  5421. movq x, z
  5422. addq w, z
  5423. movq y, tmp_0
  5424. negq tmp_0
  5425. movq z, tmp_1
  5426. addq tmp_0, tmp_1
  5427. movq tmp_1, %rdi
  5428. callq _print_int\end{lstlisting}
  5429. \end{minipage}
  5430. $\Rightarrow\qquad$
  5431. \begin{minipage}{0.25\textwidth}
  5432. \begin{lstlisting}
  5433. movq $1, %rcx
  5434. movq $42, -16(%rbp)
  5435. movq %rcx, %rcx
  5436. addq $7, %rcx
  5437. movq %rcx, %rcx
  5438. movq %rcx, -8(%rbp)
  5439. addq -16(%rbp), -8(%rbp)
  5440. movq %rcx, %rcx
  5441. negq %rcx
  5442. movq -8(%rbp), -8(%rbp)
  5443. addq %rcx, -8(%rbp)
  5444. movq -8(%rbp), %rdi
  5445. callq _print_int
  5446. \end{lstlisting}
  5447. \end{minipage}
  5448. $\Rightarrow\qquad$
  5449. \begin{minipage}{0.25\textwidth}
  5450. \begin{lstlisting}
  5451. movq $1, %rcx
  5452. movq $42, -16(%rbp)
  5453. addq $7, %rcx
  5454. movq %rcx, -8(%rbp)
  5455. movq -16(%rbp), %rax
  5456. addq %rax, -8(%rbp)
  5457. negq %rcx
  5458. addq %rcx, -8(%rbp)
  5459. movq -8(%rbp), %rdi
  5460. callq print_int
  5461. \end{lstlisting}
  5462. \end{minipage}
  5463. \fi}
  5464. \begin{exercise}\normalfont
  5465. Change your implementation of \code{allocate\_registers} to take move
  5466. biasing into account. Create two new tests that include at least one
  5467. opportunity for move biasing and visually inspect the output x86
  5468. programs to make sure that your move biasing is working properly. Make
  5469. sure that your compiler still passes all of the tests.
  5470. \end{exercise}
  5471. %To do: another neat challenge would be to do
  5472. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5473. %% \subsection{Output of the Running Example}
  5474. %% \label{sec:reg-alloc-output}
  5475. % challenge: prioritize variables based on execution frequencies
  5476. % and the number of uses of a variable
  5477. % challenge: enhance the coloring algorithm using Chaitin's
  5478. % approach of prioritizing high-degree variables
  5479. % by removing low-degree variables (coloring them later)
  5480. % from the interference graph
  5481. \section{Further Reading}
  5482. \label{sec:register-allocation-further-reading}
  5483. Early register allocation algorithms were developed for Fortran
  5484. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5485. of graph coloring began in the late 1970s and early 1980s with the
  5486. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5487. algorithm is based on the following observation of
  5488. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  5489. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  5490. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  5491. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5492. different colors, but since there are less than $k$ of them, there
  5493. will be one or more colors left over to use for coloring $v$ in $G$.
  5494. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5495. less than $k$ from the graph and recursively colors the rest of the
  5496. graph. Upon returning from the recursion, it colors $v$ with one of
  5497. the available colors and returns. \citet{Chaitin:1982vn} augments
  5498. this algorithm to handle spilling as follows. If there are no vertices
  5499. of degree lower than $k$ then pick a vertex at random, spill it,
  5500. remove it from the graph, and proceed recursively to color the rest of
  5501. the graph.
  5502. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5503. move-related and that don't interfere with each other, a process
  5504. called \emph{coalescing}. While coalescing decreases the number of
  5505. moves, it can make the graph more difficult to
  5506. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5507. which two variables are merged only if they have fewer than $k$
  5508. neighbors of high degree. \citet{George:1996aa} observe that
  5509. conservative coalescing is sometimes too conservative and make it more
  5510. aggressive by iterating the coalescing with the removal of low-degree
  5511. vertices.
  5512. %
  5513. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5514. also propose \emph{biased coloring} in which a variable is assigned to
  5515. the same color as another move-related variable if possible, as
  5516. discussed in Section~\ref{sec:move-biasing}.
  5517. %
  5518. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5519. performs coalescing, graph coloring, and spill code insertion until
  5520. all variables have been assigned a location.
  5521. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5522. spills variables that don't have to be: a high-degree variable can be
  5523. colorable if many of its neighbors are assigned the same color.
  5524. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5525. high-degree vertex is not immediately spilled. Instead the decision is
  5526. deferred until after the recursive call, at which point it is apparent
  5527. whether there is actually an available color or not. We observe that
  5528. this algorithm is equivalent to the smallest-last ordering
  5529. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5530. be registers and the rest to be stack locations.
  5531. %% biased coloring
  5532. Earlier editions of the compiler course at Indiana University
  5533. \citep{Dybvig:2010aa} were based on the algorithm of
  5534. \citet{Briggs:1994kx}.
  5535. The smallest-last ordering algorithm is one of many \emph{greedy}
  5536. coloring algorithms. A greedy coloring algorithm visits all the
  5537. vertices in a particular order and assigns each one the first
  5538. available color. An \emph{offline} greedy algorithm chooses the
  5539. ordering up-front, prior to assigning colors. The algorithm of
  5540. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5541. ordering does not depend on the colors assigned, so the algorithm
  5542. could be split into two phases. Other orderings are possible. For
  5543. example, \citet{Chow:1984ys} order variables according to an estimate
  5544. of runtime cost.
  5545. An \emph{online} greedy coloring algorithm uses information about the
  5546. current assignment of colors to influence the order in which the
  5547. remaining vertices are colored. The saturation-based algorithm
  5548. described in this chapter is one such algorithm. We choose to use
  5549. saturation-based coloring is because it is fun to introduce graph
  5550. coloring via Sudoku.
  5551. A register allocator may choose to map each variable to just one
  5552. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5553. variable to one or more locations. The later can be achieved by
  5554. \emph{live range splitting}, where a variable is replaced by several
  5555. variables that each handle part of its live
  5556. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5557. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5558. %% replacement algorithm, bottom-up local
  5559. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5560. %% Cooper: top-down (priority bassed), bottom-up
  5561. %% top-down
  5562. %% order variables by priority (estimated cost)
  5563. %% caveat: split variables into two groups:
  5564. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5565. %% color the constrained ones first
  5566. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5567. %% cite J. Cocke for an algorithm that colors variables
  5568. %% in a high-degree first ordering
  5569. %Register Allocation via Usage Counts, Freiburghouse CACM
  5570. \citet{Palsberg:2007si} observe that many of the interference graphs
  5571. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5572. that is, every cycle with four or more edges has an edge which is not
  5573. part of the cycle but which connects two vertices on the cycle. Such
  5574. graphs can be optimally colored by the greedy algorithm with a vertex
  5575. ordering determined by maximum cardinality search.
  5576. In situations where compile time is of utmost importance, such as in
  5577. just-in-time compilers, graph coloring algorithms can be too expensive
  5578. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  5579. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5580. \chapter{Booleans and Control Flow}
  5581. \label{ch:Rif}
  5582. \index{subject}{Boolean}
  5583. \index{subject}{control flow}
  5584. \index{subject}{conditional expression}
  5585. The \LangInt{} and \LangVar{} languages only have a single kind of
  5586. value, integers. In this chapter we add a second kind of value, the
  5587. Booleans, to create the \LangIf{} language. The Boolean values
  5588. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5589. respectively in \racket{Racket}\python{Python}.
  5590. The \LangIf{} language includes several
  5591. operations that involve Booleans (\key{and}, \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if} expression \python{and statement}.
  5592. With the addition of \key{if}, programs can have non-trivial control flow which
  5593. \racket{impacts \code{explicate\_control} and liveness analysis}
  5594. \python{impacts liveness analysis and motivates a new pass named
  5595. \code{explicate\_control}}. Also, because
  5596. we now have two kinds of values, we need to handle programs that apply
  5597. an operation to the wrong kind of value, such as \code{(not 1)}.
  5598. There are two language design options for such situations. One option
  5599. is to signal an error and the other is to provide a wider
  5600. interpretation of the operation. \racket{The Racket
  5601. language}\python{Python} uses a mixture of these two options,
  5602. depending on the operation and the kind of value. For example, the
  5603. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5604. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5605. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5606. %
  5607. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5608. in Racket because \code{car} expects a pair.}
  5609. %
  5610. \python{On the other hand, \code{1[0]} results in a run-time error
  5611. in Python because an ``\code{int} object is not subscriptable''.}
  5612. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5613. design choices as \racket{Racket}\python{Python}, except much of the
  5614. error detection happens at compile time instead of run
  5615. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5616. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5617. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5618. Racket}\python{MyPy} reports a compile-time error
  5619. %
  5620. \racket{because Racket expects the type of the argument to be of the form
  5621. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5622. %
  5623. \python{stating that a ``value of type \code{int} is not indexable''.}
  5624. The \LangIf{} language performs type checking during compilation like
  5625. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5626. alternative choice, that is, a dynamically typed language like
  5627. \racket{Racket}\python{Python}.
  5628. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5629. for some operations we are more restrictive, for example, rejecting
  5630. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5631. This chapter is organized as follows. We begin by defining the syntax
  5632. and interpreter for the \LangIf{} language
  5633. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5634. checking and build a type checker for \LangIf{}
  5635. (Section~\ref{sec:type-check-Rif}).
  5636. %
  5637. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5638. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5639. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5640. %
  5641. The remaining sections of this chapter discuss how our compiler passes
  5642. change to accommodate Booleans and conditional control flow. There is
  5643. a new pass, named \code{shrink}, that translates some operators into
  5644. others, thereby reducing the number of operators that need to be
  5645. handled in later passes.
  5646. %
  5647. \racket{The largest changes occur in \code{explicate\_control}, to
  5648. translate \code{if} expressions into control-flow graphs
  5649. (Section~\ref{sec:explicate-control-Rif}).}
  5650. %
  5651. \python{The largest addition is a new pass named
  5652. \code{explicate\_control} that translates \code{if} expressions and
  5653. statements into control-flow graphs
  5654. (Section~\ref{sec:explicate-control-Rif}).}
  5655. %
  5656. Regarding register allocation, there is the interesting question of
  5657. how to handle conditional jumps during liveness analysis.
  5658. \section{The \LangIf{} Language}
  5659. \label{sec:lang-if}
  5660. The concrete syntax of the \LangIf{} language is defined in
  5661. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  5662. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  5663. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5664. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5665. operators to include
  5666. \begin{enumerate}
  5667. \item subtraction on integers,
  5668. \item the logical operators \key{and}, \key{or} and \key{not},
  5669. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5670. for comparing two integers or two Booleans for equality, and
  5671. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5672. comparing integers.
  5673. \end{enumerate}
  5674. \racket{We reorganize the abstract syntax for the primitive
  5675. operations in Figure~\ref{fig:Rif-syntax}, using only one grammar
  5676. rule for all of them. This means that the grammar no longer checks
  5677. whether the arity of an operators matches the number of
  5678. arguments. That responsibility is moved to the type checker for
  5679. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Rif}.}
  5680. \begin{figure}[tp]
  5681. \centering
  5682. \fbox{
  5683. \begin{minipage}{0.96\textwidth}
  5684. {\if\edition\racketEd\color{olive}
  5685. \[
  5686. \begin{array}{lcl}
  5687. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5688. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5689. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} } \MID \CSUB{\Exp}{\Exp} \\
  5690. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} } \\
  5691. &\MID& \itm{bool}
  5692. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5693. \MID (\key{not}\;\Exp) \\
  5694. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5695. \LangIfM{} &::=& \Exp
  5696. \end{array}
  5697. \]
  5698. \fi}
  5699. {\if\edition\pythonEd\color{purple}
  5700. \[
  5701. \begin{array}{rcl}
  5702. \itm{binop} &::= & \key{+} \MID \key{-} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5703. \itm{uniop} &::= & \key{-} \MID \key{not} \\
  5704. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \itm{uniop}\;\Exp \MID \Exp \; \itm{binop} \; \Exp \MID \Var{} \\
  5705. &\MID& \TRUE \MID \FALSE \MID \Exp\;\key{if}\;\Exp\;\key{else}\;\Exp\\
  5706. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp
  5707. \MID \key{if}\; \Exp \;\key{:}\; \Stmt^{+} \;\key{else:}\; \Stmt^{+}\\
  5708. \LangVarM{} &::=& \Stmt^{*}
  5709. \end{array}
  5710. \]
  5711. \fi}
  5712. \end{minipage}
  5713. }
  5714. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  5715. (Figure~\ref{fig:Rvar-concrete-syntax}) with Booleans and conditionals.}
  5716. \label{fig:Rif-concrete-syntax}
  5717. \end{figure}
  5718. \begin{figure}[tp]
  5719. \centering
  5720. \fbox{
  5721. \begin{minipage}{0.96\textwidth}
  5722. {\if\edition\racketEd\color{olive}
  5723. \[
  5724. \begin{array}{lcl}
  5725. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5726. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5727. \itm{op} &::= & \itm{cmp} \MID \code{read} \MID \code{+} \MID \code{-}
  5728. \MID \code{and} \MID \code{or} \MID \code{not} \\
  5729. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  5730. &\MID& \PRIM{\itm{op}}{\Exp\ldots}\\
  5731. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5732. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  5733. \end{array}
  5734. \]
  5735. \fi}
  5736. {\if\edition\pythonEd\color{purple}
  5737. \[
  5738. \begin{array}{lcl}
  5739. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  5740. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  5741. \itm{bool} &::=& \code{True} \MID \code{False} \\
  5742. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  5743. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  5744. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  5745. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  5746. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  5747. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  5748. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  5749. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5750. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  5751. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  5752. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  5753. \end{array}
  5754. \]
  5755. \fi}
  5756. \end{minipage}
  5757. }
  5758. \caption{The abstract syntax of \LangIf{}.}
  5759. \label{fig:Rif-syntax}
  5760. \end{figure}
  5761. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  5762. which inherits from the interpreter for \LangVar{}
  5763. (Figure~\ref{fig:interp-Rvar}). The literals \TRUE{} and \FALSE{}
  5764. evaluate to the corresponding Boolean values. The conditional
  5765. expression $\CIF{\itm{cnd}}{\itm{thn}}{\itm{els}}$ evaluates \itm{cnd}
  5766. and then either evaluates \itm{thn} or \itm{els} depending on whether
  5767. \itm{cnd} produced \TRUE{} or \FALSE{}. The logical operations
  5768. \code{and}, \code{or}, and \code{not} behave as you might expect, but
  5769. note that the \code{and} an \code{or} operations are
  5770. short-circuiting.
  5771. %
  5772. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  5773. is not evaluated if $e_1$ evaluates to \FALSE{}.
  5774. %
  5775. Similarly, given the expression $\COR{e_1}{e_2}$, the expression $e_2$
  5776. is not evaluated if $e_1$ evaluates to \TRUE{}.
  5777. \racket{With the increase in the number of primitive operations, the
  5778. interpreter would become repetitive without some care. We refactor
  5779. the case for \code{Prim}, moving the code that differs with each
  5780. operation into the \code{interp_op} method shown in in
  5781. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  5782. separately because of its short-circuiting behavior.}
  5783. \begin{figure}[tbp]
  5784. {\if\edition\racketEd\color{olive}
  5785. \begin{lstlisting}
  5786. (define interp_Rif_class
  5787. (class interp_Rvar_class
  5788. (super-new)
  5789. (define/public (interp_op op) ...)
  5790. (define/override ((interp_exp env) e)
  5791. (define recur (interp_exp env))
  5792. (match e
  5793. [(Bool b) b]
  5794. [(If cnd thn els)
  5795. (match (recur cnd)
  5796. [#t (recur thn)]
  5797. [#f (recur els)])]
  5798. [(Prim 'and (list e1 e2))
  5799. (match (recur e1)
  5800. [#t (match (recur e2) [#t #t] [#f #f])]
  5801. [#f #f])]
  5802. [(Prim op args)
  5803. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  5804. [else ((super interp_exp env) e)]))
  5805. ))
  5806. (define (interp_Rif p)
  5807. (send (new interp_Rif_class) interp_program p))
  5808. \end{lstlisting}
  5809. \fi}
  5810. {\if\edition\pythonEd\color{purple}
  5811. \begin{lstlisting}
  5812. class InterpPif(InterpPvar):
  5813. def interp_exp(self, e, env):
  5814. match e:
  5815. case IfExp(test, body, orelse):
  5816. match self.interp_exp(test, env):
  5817. case True:
  5818. return self.interp_exp(body, env)
  5819. case False:
  5820. return self.interp_exp(orelse, env)
  5821. case BinOp(left, Sub(), right):
  5822. l = self.interp_exp(left, env)
  5823. r = self.interp_exp(right, env)
  5824. return l - r
  5825. case UnaryOp(Not(), v):
  5826. return not self.interp_exp(v, env)
  5827. case BoolOp(left, And(), right):
  5828. match self.interp_exp(left, env):
  5829. case True:
  5830. return self.interp_exp(right, env)
  5831. case False:
  5832. return False
  5833. case BoolOp(left, Or(), right):
  5834. match self.interp_exp(left, env):
  5835. case True:
  5836. return True
  5837. case False:
  5838. return self.interp_exp(right, env)
  5839. case Compare(left, [cmp], [right]):
  5840. l = self.interp_exp(left, env)
  5841. r = self.interp_exp(right, env)
  5842. return self.interp_cmp(cmp)(l, r)
  5843. case _:
  5844. return super().interp_exp(e, env)
  5845. def interp_stmts(self, ss, env):
  5846. if len(ss) == 0:
  5847. return
  5848. match ss[0]:
  5849. case If(test, body, orelse):
  5850. match self.interp_exp(test, env):
  5851. case True:
  5852. return self.interp_stmts(body + ss[1:], env)
  5853. case False:
  5854. return self.interp_stmts(orelse + ss[1:], env)
  5855. case _:
  5856. return super().interp_stmts(ss, env)
  5857. ...
  5858. \end{lstlisting}
  5859. \fi}
  5860. \caption{Interpreter for the \LangIf{} language. \racket{(See
  5861. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  5862. \python{(See Figure~\ref{fig:interp-cmp-Rif} for \code{interp\_cmp}.)}}
  5863. \label{fig:interp-Rif}
  5864. \end{figure}
  5865. {\if\edition\racketEd\color{olive}
  5866. \begin{figure}[tbp]
  5867. \begin{lstlisting}
  5868. (define/public (interp_op op)
  5869. (match op
  5870. ['+ fx+]
  5871. ['- fx-]
  5872. ['read read-fixnum]
  5873. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  5874. ['or (lambda (v1 v2)
  5875. (cond [(and (boolean? v1) (boolean? v2))
  5876. (or v1 v2)]))]
  5877. ['eq? (lambda (v1 v2)
  5878. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5879. (and (boolean? v1) (boolean? v2))
  5880. (and (vector? v1) (vector? v2)))
  5881. (eq? v1 v2)]))]
  5882. ['< (lambda (v1 v2)
  5883. (cond [(and (fixnum? v1) (fixnum? v2))
  5884. (< v1 v2)]))]
  5885. ['<= (lambda (v1 v2)
  5886. (cond [(and (fixnum? v1) (fixnum? v2))
  5887. (<= v1 v2)]))]
  5888. ['> (lambda (v1 v2)
  5889. (cond [(and (fixnum? v1) (fixnum? v2))
  5890. (> v1 v2)]))]
  5891. ['>= (lambda (v1 v2)
  5892. (cond [(and (fixnum? v1) (fixnum? v2))
  5893. (>= v1 v2)]))]
  5894. [else (error 'interp_op "unknown operator")]))
  5895. \end{lstlisting}
  5896. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  5897. \label{fig:interp-op-Rif}
  5898. \end{figure}
  5899. \fi}
  5900. {\if\edition\pythonEd\color{purple}
  5901. \begin{figure}
  5902. \begin{lstlisting}
  5903. class InterpPif(InterpPvar):
  5904. ...
  5905. def interp_cmp(self, cmp):
  5906. match cmp:
  5907. case Lt():
  5908. return lambda x, y: x < y
  5909. case LtE():
  5910. return lambda x, y: x <= y
  5911. case Gt():
  5912. return lambda x, y: x > y
  5913. case GtE():
  5914. return lambda x, y: x >= y
  5915. case Eq():
  5916. return lambda x, y: x == y
  5917. case NotEq():
  5918. return lambda x, y: x != y
  5919. \end{lstlisting}
  5920. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  5921. \label{fig:interp-cmp-Rif}
  5922. \end{figure}
  5923. \fi}
  5924. \section{Type Checking \LangIf{} Programs}
  5925. \label{sec:type-check-Rif}
  5926. \index{subject}{type checking}
  5927. \index{subject}{semantic analysis}
  5928. It is helpful to think about type checking in two complementary
  5929. ways. A type checker predicts the type of value that will be produced
  5930. by each expression in the program. For \LangIf{}, we have just two types,
  5931. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  5932. {\if\edition\racketEd\color{olive}
  5933. \begin{lstlisting}
  5934. (+ 10 (- (+ 12 20)))
  5935. \end{lstlisting}
  5936. \fi}
  5937. {\if\edition\pythonEd\color{purple}
  5938. \begin{lstlisting}
  5939. 10 + -(12 + 20)
  5940. \end{lstlisting}
  5941. \fi}
  5942. \noindent produces a value of type \INTTY{} while
  5943. {\if\edition\racketEd\color{olive}
  5944. \begin{lstlisting}
  5945. (and (not #f) #t)
  5946. \end{lstlisting}
  5947. \fi}
  5948. {\if\edition\pythonEd\color{purple}
  5949. \begin{lstlisting}
  5950. (not False) and True
  5951. \end{lstlisting}
  5952. \fi}
  5953. \noindent produces a value of type \BOOLTY{}.
  5954. Another way to think about type checking is that it enforces a set of
  5955. rules about which operators can be applied to which kinds of
  5956. values. For example, our type checker for \LangIf{} signals an error
  5957. for the below expression
  5958. {\if\edition\racketEd\color{olive}
  5959. \begin{lstlisting}
  5960. (not (+ 10 (- (+ 12 20))))
  5961. \end{lstlisting}
  5962. \fi}
  5963. {\if\edition\pythonEd\color{purple}
  5964. \begin{lstlisting}
  5965. not (10 + -(12 + 20))
  5966. \end{lstlisting}
  5967. \fi}
  5968. The subexpression
  5969. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  5970. has type \INTTY{} but the type checker enforces the rule that the argument of
  5971. \code{not} must be an expression of type \BOOLTY{}.
  5972. We implement type checking using classes and methods because they
  5973. provide the open recursion needed to reuse code as we extend the type
  5974. checker in later chapters, analogous to the use of classes and methods
  5975. for the interpreters (Section~\ref{sec:extensible-interp}).
  5976. We separate the type checker for the \LangVar{} fragment into its own
  5977. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  5978. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  5979. from the type checker for \LangVar{}. These type checkers are in the
  5980. files
  5981. \racket{\code{type-check-Rvar.rkt}}\python{\code{type\_check\_Pvar.py}}
  5982. and
  5983. \racket{\code{type-check-Rif.rkt}}\python{\code{type\_check\_Pif.py}}
  5984. of the support code.
  5985. %
  5986. Each type checker is a structurally recursive function over the AST.
  5987. Given an input expression \code{e}, the type checker either signals an
  5988. error or returns an expression and its type (\INTTY{} or
  5989. \BOOLTY{}). It returns an expression because there are situations
  5990. in which we want to change or update the expression.
  5991. Next we discuss the \code{match} cases in \code{type\_check\_exp} of
  5992. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  5993. \INTTY{}. To handle variables, the type checker uses the
  5994. environment \code{env} to map variables to types. Consider the case
  5995. for \key{let}. We type check the initializing expression to obtain
  5996. its type \key{T} and then associate type \code{T} with the variable
  5997. \code{x} in the environment used to type check the body of the
  5998. \key{let}. Thus, when the type checker encounters a use of variable
  5999. \code{x}, it can find its type in the environment. Regarding
  6000. primitive operators, we recursively analyze the arguments and then
  6001. invoke \code{type\_check\_op} to check whether the argument types are
  6002. allowed.
  6003. Several auxiliary methods are used in the type checker. The method
  6004. \code{operator-types} defines a dictionary that maps the operator
  6005. names to their parameter and return types. The \code{type-equal?}
  6006. method determines whether two types are equal, which for now simply
  6007. dispatches to \code{equal?} (deep equality). The
  6008. \code{check-type-equal?} method triggers an error if the two types are
  6009. not equal. The \code{type-check-op} method looks up the operator in
  6010. the \code{operator-types} dictionary and then checks whether the
  6011. argument types are equal to the parameter types. The result is the
  6012. return type of the operator.
  6013. \begin{figure}[tbp]
  6014. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6015. (define type-check-Rvar_class
  6016. (class object%
  6017. (super-new)
  6018. (define/public (operator-types)
  6019. '((+ . ((Integer Integer) . Integer))
  6020. (- . ((Integer) . Integer))
  6021. (read . (() . Integer))))
  6022. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6023. (define/public (check-type-equal? t1 t2 e)
  6024. (unless (type-equal? t1 t2)
  6025. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6026. (define/public (type-check-op op arg-types e)
  6027. (match (dict-ref (operator-types) op)
  6028. [`(,param-types . ,return-type)
  6029. (for ([at arg-types] [pt param-types])
  6030. (check-type-equal? at pt e))
  6031. return-type]
  6032. [else (error 'type-check-op "unrecognized ~a" op)]))
  6033. (define/public (type-check-exp env)
  6034. (lambda (e)
  6035. (match e
  6036. [(Int n) (values (Int n) 'Integer)]
  6037. [(Var x) (values (Var x) (dict-ref env x))]
  6038. [(Let x e body)
  6039. (define-values (e^ Te) ((type-check-exp env) e))
  6040. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6041. (values (Let x e^ b) Tb)]
  6042. [(Prim op es)
  6043. (define-values (new-es ts)
  6044. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6045. (values (Prim op new-es) (type-check-op op ts e))]
  6046. [else (error 'type-check-exp "couldn't match" e)])))
  6047. (define/public (type-check-program e)
  6048. (match e
  6049. [(Program info body)
  6050. (define-values (body^ Tb) ((type-check-exp '()) body))
  6051. (check-type-equal? Tb 'Integer body)
  6052. (Program info body^)]
  6053. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  6054. ))
  6055. (define (type-check-Rvar p)
  6056. (send (new type-check-Rvar_class) type-check-program p))
  6057. \end{lstlisting}
  6058. \caption{Type checker for the \LangVar{} language.}
  6059. \label{fig:type-check-Rvar}
  6060. \end{figure}
  6061. \begin{figure}[tbp]
  6062. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6063. (define type-check-Rif_class
  6064. (class type-check-Rvar_class
  6065. (super-new)
  6066. (inherit check-type-equal?)
  6067. (define/override (operator-types)
  6068. (append '((- . ((Integer Integer) . Integer))
  6069. (and . ((Boolean Boolean) . Boolean))
  6070. (or . ((Boolean Boolean) . Boolean))
  6071. (< . ((Integer Integer) . Boolean))
  6072. (<= . ((Integer Integer) . Boolean))
  6073. (> . ((Integer Integer) . Boolean))
  6074. (>= . ((Integer Integer) . Boolean))
  6075. (not . ((Boolean) . Boolean))
  6076. )
  6077. (super operator-types)))
  6078. (define/override (type-check-exp env)
  6079. (lambda (e)
  6080. (match e
  6081. [(Prim 'eq? (list e1 e2))
  6082. (define-values (e1^ T1) ((type-check-exp env) e1))
  6083. (define-values (e2^ T2) ((type-check-exp env) e2))
  6084. (check-type-equal? T1 T2 e)
  6085. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6086. [(Bool b) (values (Bool b) 'Boolean)]
  6087. [(If cnd thn els)
  6088. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6089. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6090. (define-values (els^ Te) ((type-check-exp env) els))
  6091. (check-type-equal? Tc 'Boolean e)
  6092. (check-type-equal? Tt Te e)
  6093. (values (If cnd^ thn^ els^) Te)]
  6094. [else ((super type-check-exp env) e)])))
  6095. ))
  6096. (define (type-check-Rif p)
  6097. (send (new type-check-Rif_class) type-check-program p))
  6098. \end{lstlisting}
  6099. \caption{Type checker for the \LangIf{} language.}
  6100. \label{fig:type-check-Rif}
  6101. \end{figure}
  6102. Next we discuss the type checker for \LangIf{} in
  6103. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  6104. two arguments to have the same type. The type of a Boolean constant is
  6105. \code{Boolean}. The condition of an \code{if} must be of
  6106. \code{Boolean} type and the two branches must have the same type. The
  6107. \code{operator-types} function adds dictionary entries for the other
  6108. new operators.
  6109. \begin{exercise}\normalfont
  6110. Create 10 new test programs in \LangIf{}. Half of the programs should
  6111. have a type error. For those programs, create an empty file with the
  6112. same base name but with file extension \code{.tyerr}. For example, if
  6113. the test \code{cond\_test\_14.rkt} is expected to error, then create
  6114. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  6115. \code{interp-tests} and \code{compiler-tests} that a type error is
  6116. expected. The other half of the test programs should not have type
  6117. errors.
  6118. In the \code{run-tests.rkt} script, change the second argument of
  6119. \code{interp-tests} and \code{compiler-tests} to
  6120. \code{type-check-Rif}, which causes the type checker to run prior to
  6121. the compiler passes. Temporarily change the \code{passes} to an empty
  6122. list and run the script, thereby checking that the new test programs
  6123. either type check or not as intended.
  6124. \end{exercise}
  6125. \section{The \LangCIf{} Intermediate Language}
  6126. \label{sec:Cif}
  6127. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  6128. \LangCIf{} intermediate language. (The concrete syntax is in the
  6129. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  6130. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  6131. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  6132. \key{\#f} to the \Arg{} non-terminal.
  6133. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6134. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6135. statement is a comparison operation and the branches are \code{goto}
  6136. statements, making it straightforward to compile \code{if} statements
  6137. to x86.
  6138. \begin{figure}[tp]
  6139. \fbox{
  6140. \begin{minipage}{0.96\textwidth}
  6141. \small
  6142. \[
  6143. \begin{array}{lcl}
  6144. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  6145. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  6146. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  6147. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6148. &\MID& \UNIOP{\key{'not}}{\Atm}
  6149. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6150. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  6151. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  6152. \MID \GOTO{\itm{label}} \\
  6153. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  6154. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  6155. \end{array}
  6156. \]
  6157. \end{minipage}
  6158. }
  6159. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  6160. (Figure~\ref{fig:c0-syntax}).}
  6161. \label{fig:c1-syntax}
  6162. \end{figure}
  6163. \section{The \LangXIf{} Language}
  6164. \label{sec:x86-if}
  6165. \index{subject}{x86} To implement the new logical operations, the comparison
  6166. operations, and the \key{if} expression, we need to delve further into
  6167. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6168. define the concrete and abstract syntax for the \LangXIf{} subset
  6169. of x86, which includes instructions for logical operations,
  6170. comparisons, and conditional jumps.
  6171. One challenge is that x86 does not provide an instruction that
  6172. directly implements logical negation (\code{not} in \LangIf{} and
  6173. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6174. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6175. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6176. bit of its arguments, and writes the results into its second argument.
  6177. Recall the truth table for exclusive-or:
  6178. \begin{center}
  6179. \begin{tabular}{l|cc}
  6180. & 0 & 1 \\ \hline
  6181. 0 & 0 & 1 \\
  6182. 1 & 1 & 0
  6183. \end{tabular}
  6184. \end{center}
  6185. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6186. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6187. for the bit $1$, the result is the opposite of the second bit. Thus,
  6188. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6189. the first argument:
  6190. \[
  6191. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  6192. \qquad\Rightarrow\qquad
  6193. \begin{array}{l}
  6194. \key{movq}~ \Arg\key{,} \Var\\
  6195. \key{xorq}~ \key{\$1,} \Var
  6196. \end{array}
  6197. \]
  6198. \begin{figure}[tp]
  6199. \fbox{
  6200. \begin{minipage}{0.96\textwidth}
  6201. \[
  6202. \begin{array}{lcl}
  6203. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6204. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6205. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6206. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6207. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6208. \key{subq} \; \Arg\key{,} \Arg \MID
  6209. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6210. && \gray{ \key{callq} \; \itm{label} \MID
  6211. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} } \\
  6212. && \gray{ \itm{label}\key{:}\; \Instr }
  6213. \MID \key{xorq}~\Arg\key{,}~\Arg
  6214. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6215. && \key{set}cc~\Arg
  6216. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6217. \MID \key{j}cc~\itm{label}
  6218. \\
  6219. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6220. & & \gray{ \key{main:} \; \Instr\ldots }
  6221. \end{array}
  6222. \]
  6223. \end{minipage}
  6224. }
  6225. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6226. \label{fig:x86-1-concrete}
  6227. \end{figure}
  6228. \begin{figure}[tp]
  6229. \fbox{
  6230. \begin{minipage}{0.98\textwidth}
  6231. \small
  6232. \[
  6233. \begin{array}{lcl}
  6234. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6235. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6236. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6237. \MID \BYTEREG{\itm{bytereg}} \\
  6238. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6239. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6240. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6241. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6242. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6243. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6244. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6245. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6246. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6247. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6248. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6249. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  6250. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6251. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6252. \end{array}
  6253. \]
  6254. \end{minipage}
  6255. }
  6256. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6257. \label{fig:x86-1}
  6258. \end{figure}
  6259. Next we consider the x86 instructions that are relevant for compiling
  6260. the comparison operations. The \key{cmpq} instruction compares its two
  6261. arguments to determine whether one argument is less than, equal, or
  6262. greater than the other argument. The \key{cmpq} instruction is unusual
  6263. regarding the order of its arguments and where the result is
  6264. placed. The argument order is backwards: if you want to test whether
  6265. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6266. \key{cmpq} is placed in the special EFLAGS register. This register
  6267. cannot be accessed directly but it can be queried by a number of
  6268. instructions, including the \key{set} instruction. The instruction
  6269. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6270. depending on whether the comparison comes out according to the
  6271. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6272. for less-or-equal, \key{g} for greater, \key{ge} for
  6273. greater-or-equal). The \key{set} instruction has an annoying quirk in
  6274. that its destination argument must be single byte register, such as
  6275. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6276. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6277. instruction can be used to move from a single byte register to a
  6278. normal 64-bit register. The abstract syntax for the \code{set}
  6279. instruction differs from the concrete syntax in that it separates the
  6280. instruction name from the condition code.
  6281. The x86 instruction for conditional jump is relevant to the
  6282. compilation of \key{if} expressions. The instruction
  6283. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  6284. the instruction after \itm{label} depending on whether the result in
  6285. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  6286. jump instruction falls through to the next instruction. Like the
  6287. abstract syntax for \code{set}, the abstract syntax for conditional
  6288. jump separates the instruction name from the condition code. For
  6289. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  6290. the conditional jump instruction relies on the EFLAGS register, it is
  6291. common for it to be immediately preceded by a \key{cmpq} instruction
  6292. to set the EFLAGS register.
  6293. \section{Shrink the \LangIf{} Language}
  6294. \label{sec:shrink-Rif}
  6295. % TODO: consider dropping the shrinking of there operations where
  6296. % it hurts the generated x86 code, such as >, <, -, etc.
  6297. % (suggestion from Andrew Tolmach).
  6298. The \LangIf{} language includes several operators that are easily
  6299. expressible with other operators. For example, subtraction is
  6300. expressible using addition and negation.
  6301. \[
  6302. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6303. \]
  6304. Several of the comparison operations are expressible using less-than
  6305. and logical negation.
  6306. \[
  6307. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6308. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6309. \]
  6310. The \key{let} is needed in the above translation to ensure that
  6311. expression $e_1$ is evaluated before $e_2$.
  6312. By performing these translations in the front-end of the compiler, the
  6313. later passes of the compiler do not need to deal with these operators,
  6314. making the passes shorter.
  6315. %% On the other hand, sometimes
  6316. %% these translations make it more difficult to generate the most
  6317. %% efficient code with respect to the number of instructions. However,
  6318. %% these differences typically do not affect the number of accesses to
  6319. %% memory, which is the primary factor that determines execution time on
  6320. %% modern computer architectures.
  6321. \begin{exercise}\normalfont
  6322. Implement the pass \code{shrink} to remove subtraction, \key{and},
  6323. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  6324. translating them to other constructs in \LangIf{}.
  6325. %
  6326. Create six test programs that involve these operators.
  6327. %
  6328. In the \code{run-tests.rkt} script, add the following entry for
  6329. \code{shrink} to the list of passes (it should be the only pass at
  6330. this point).
  6331. \begin{lstlisting}
  6332. (list "shrink" shrink interp_Rif type-check-Rif)
  6333. \end{lstlisting}
  6334. This instructs \code{interp-tests} to run the intepreter
  6335. \code{interp\_Rif} and the type checker \code{type-check-Rif} on the
  6336. output of \code{shrink}.
  6337. %
  6338. Run the script to test your compiler on all the test programs.
  6339. \end{exercise}
  6340. \section{Uniquify Variables}
  6341. \label{sec:uniquify-Rif}
  6342. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6343. \code{if} expressions.
  6344. \begin{exercise}\normalfont
  6345. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6346. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6347. \begin{lstlisting}
  6348. (list "uniquify" uniquify interp_Rif type_check_Rif)
  6349. \end{lstlisting}
  6350. Run the script to test your compiler.
  6351. \end{exercise}
  6352. \section{Remove Complex Operands}
  6353. \label{sec:remove-complex-opera-Rif}
  6354. The output language for this pass is \LangIfANF{}
  6355. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  6356. \LangIf{}. The \code{Bool} form is an atomic expressions but
  6357. \code{If} is not. All three sub-expressions of an \code{If} are
  6358. allowed to be complex expressions but the operands of \code{not} and
  6359. the comparisons must be atoms.
  6360. Add cases for \code{Bool} and \code{If} to the \code{rco\_exp} and
  6361. \code{rco\_atom} functions according to whether the output needs to be
  6362. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  6363. Regarding \code{If}, it is particularly important to \textbf{not}
  6364. replace its condition with a temporary variable because that would
  6365. interfere with the generation of high-quality output in the
  6366. \code{explicate-control} pass.
  6367. \begin{figure}[tp]
  6368. \centering
  6369. \fbox{
  6370. \begin{minipage}{0.96\textwidth}
  6371. \[
  6372. \begin{array}{rcl}
  6373. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  6374. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6375. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6376. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6377. &\MID& \UNIOP{\key{not}}{\Atm} \\
  6378. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6379. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  6380. \end{array}
  6381. \]
  6382. \end{minipage}
  6383. }
  6384. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  6385. \label{fig:Rif-anf-syntax}
  6386. \end{figure}
  6387. \begin{exercise}\normalfont
  6388. %
  6389. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  6390. and \code{rco\_exp} functions in \code{compiler.rkt}.
  6391. %
  6392. Create three new \LangInt{} programs that exercise the interesting
  6393. code in this pass.
  6394. %
  6395. In the \code{run-tests.rkt} script, add the following entry to the
  6396. list of \code{passes} and then run the script to test your compiler.
  6397. \begin{lstlisting}
  6398. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  6399. \end{lstlisting}
  6400. \end{exercise}
  6401. \section{Explicate Control}
  6402. \label{sec:explicate-control-Rif}
  6403. Recall that the purpose of \code{explicate-control} is to make the
  6404. order of evaluation explicit in the syntax of the program. With the
  6405. addition of \key{if} this get more interesting.
  6406. As a motivating example, consider the following program that has an
  6407. \key{if} expression nested in the predicate of another \key{if}.
  6408. % cond_test_41.rkt, if_lt_eq.py
  6409. \begin{center}
  6410. \begin{minipage}{0.96\textwidth}
  6411. \begin{lstlisting}
  6412. (let ([x (read)])
  6413. (let ([y (read)])
  6414. (if (if (< x 1) (eq? x 0) (eq? x 2))
  6415. (+ y 2)
  6416. (+ y 10))))
  6417. \end{lstlisting}
  6418. \end{minipage}
  6419. \end{center}
  6420. %
  6421. The naive way to compile \key{if} and the comparison would be to
  6422. handle each of them in isolation, regardless of their context. Each
  6423. comparison would be translated into a \key{cmpq} instruction followed
  6424. by a couple instructions to move the result from the EFLAGS register
  6425. into a general purpose register or stack location. Each \key{if} would
  6426. be translated into a \key{cmpq} instruction followed by a conditional
  6427. jump. The generated code for the inner \key{if} in the above example
  6428. would be as follows.
  6429. \begin{center}
  6430. \begin{minipage}{0.96\textwidth}
  6431. \begin{lstlisting}
  6432. ...
  6433. cmpq $1, x ;; (< x 1)
  6434. setl %al
  6435. movzbq %al, tmp
  6436. cmpq $1, tmp ;; (if ...)
  6437. je then_branch_1
  6438. jmp else_branch_1
  6439. ...
  6440. \end{lstlisting}
  6441. \end{minipage}
  6442. \end{center}
  6443. However, if we take context into account we can do better and reduce
  6444. the use of \key{cmpq} instructions for accessing the EFLAG register.
  6445. Our goal will be compile \key{if} expressions so that the relevant
  6446. comparison instruction appears directly before the conditional jump.
  6447. For example, we want to generate the following code for the inner
  6448. \code{if}.
  6449. \begin{center}
  6450. \begin{minipage}{0.96\textwidth}
  6451. \begin{lstlisting}
  6452. ...
  6453. cmpq $1, x
  6454. je then_branch_1
  6455. jmp else_branch_1
  6456. ...
  6457. \end{lstlisting}
  6458. \end{minipage}
  6459. \end{center}
  6460. One way to achieve this is to reorganize the code at the level of
  6461. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  6462. the following code.
  6463. \begin{center}
  6464. \begin{minipage}{0.96\textwidth}
  6465. \begin{lstlisting}
  6466. (let ([x (read)])
  6467. (let ([y (read)])
  6468. (if (< x 1)
  6469. (if (eq? x 0)
  6470. (+ y 2)
  6471. (+ y 10))
  6472. (if (eq? x 2)
  6473. (+ y 2)
  6474. (+ y 10)))))
  6475. \end{lstlisting}
  6476. \end{minipage}
  6477. \end{center}
  6478. Unfortunately, this approach duplicates the two branches from the
  6479. outer \code{if} and a compiler must never duplicate code!
  6480. We need a way to perform the above transformation but without
  6481. duplicating code. That is, we need a way for different parts of a
  6482. program to refer to the same piece of code. At the level of x86
  6483. assembly this is straightforward because we can label the code for
  6484. each branch and insert jumps in all the places that need to execute
  6485. the branch. In our intermediate language, we need to move away from
  6486. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  6487. particular, we use a standard program representation called a
  6488. \emph{control flow graph} (CFG), due to Frances Elizabeth
  6489. \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex is a
  6490. labeled sequence of code, called a \emph{basic block}, and each edge
  6491. represents a jump to another block. The \key{CProgram} construct of
  6492. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  6493. as an alist mapping labels to basic blocks. Each basic block is
  6494. represented by the $\Tail$ non-terminal.
  6495. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  6496. \code{remove-complex-opera*} pass and then the
  6497. \code{explicate-control} pass on the example program. We walk through
  6498. the output program and then discuss the algorithm.
  6499. %
  6500. Following the order of evaluation in the output of
  6501. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  6502. and then the comparison \lstinline{(< x 1)} in the predicate of the
  6503. inner \key{if}. In the output of \code{explicate-control}, in the
  6504. block labeled \code{start}, is two assignment statements followed by a
  6505. \code{if} statement that branches to \code{block40} or
  6506. \code{block41}. The blocks associated with those labels contain the
  6507. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  6508. respectively. In particular, we start \code{block40} with the
  6509. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  6510. \code{block39}, the two branches of the outer \key{if}, i.e.,
  6511. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  6512. \code{block41} is similar.
  6513. \begin{figure}[tbp]
  6514. \begin{tabular}{lll}
  6515. \begin{minipage}{0.4\textwidth}
  6516. % cond_test_41.rkt
  6517. \begin{lstlisting}
  6518. (let ([x (read)])
  6519. (let ([y (read)])
  6520. (if (if (< x 1)
  6521. (eq? x 0)
  6522. (eq? x 2))
  6523. (+ y 2)
  6524. (+ y 10))))
  6525. \end{lstlisting}
  6526. \hspace{40pt}$\Downarrow$
  6527. \begin{lstlisting}
  6528. (let ([x (read)])
  6529. (let ([y (read)])
  6530. (if (if (< x 1)
  6531. (eq? x 0)
  6532. (eq? x 2))
  6533. (+ y 2)
  6534. (+ y 10))))
  6535. \end{lstlisting}
  6536. \end{minipage}
  6537. &
  6538. $\Rightarrow$
  6539. &
  6540. \begin{minipage}{0.55\textwidth}
  6541. \begin{lstlisting}
  6542. start:
  6543. x = (read);
  6544. y = (read);
  6545. if (< x 1) goto block40;
  6546. else goto block41;
  6547. block40:
  6548. if (eq? x 0) goto block38;
  6549. else goto block39;
  6550. block41:
  6551. if (eq? x 2) goto block38;
  6552. else goto block39;
  6553. block38:
  6554. return (+ y 2);
  6555. block39:
  6556. return (+ y 10);
  6557. \end{lstlisting}
  6558. \end{minipage}
  6559. \end{tabular}
  6560. \caption{Translation from \LangIf{} to \LangCIf{}
  6561. via the \code{explicate-control}.}
  6562. \label{fig:explicate-control-s1-38}
  6563. \end{figure}
  6564. %% The nice thing about the output of \code{explicate-control} is that
  6565. %% there are no unnecessary comparisons and every comparison is part of a
  6566. %% conditional jump.
  6567. %% The down-side of this output is that it includes
  6568. %% trivial blocks, such as the blocks labeled \code{block92} through
  6569. %% \code{block95}, that only jump to another block. We discuss a solution
  6570. %% to this problem in Section~\ref{sec:opt-jumps}.
  6571. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  6572. \code{explicate-control} for \LangVar{} using two mutually recursive
  6573. functions, \code{explicate-tail} and \code{explicate-assign}. The
  6574. former function translates expressions in tail position whereas the
  6575. later function translates expressions on the right-hand-side of a
  6576. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  6577. have a new kind of position to deal with: the predicate position of
  6578. the \key{if}. We need another function, \code{explicate-pred}, that
  6579. takes an \LangIf{} expression and two blocks for the then-branch and
  6580. else-branch. The output of \code{explicate-pred} is a block.
  6581. %
  6582. In the following paragraphs we discuss specific cases in the
  6583. \code{explicate-pred} function as well as additions to the
  6584. \code{explicate-tail} and \code{explicate-assign} functions.
  6585. \begin{figure}[tbp]
  6586. \begin{lstlisting}
  6587. (define (explicate-pred cnd thn els)
  6588. (match cnd
  6589. [(Var x) ___]
  6590. [(Let x rhs body) ___]
  6591. [(Prim 'not (list e)) ___]
  6592. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  6593. (IfStmt (Prim op arg*) (force (block->goto thn))
  6594. (force (block->goto els)))]
  6595. [(Bool b) (if b thn els)]
  6596. [(If cnd^ thn^ els^) ___]
  6597. [else (error "explicate-pred unhandled case" cnd)]))
  6598. \end{lstlisting}
  6599. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  6600. \label{fig:explicate-pred}
  6601. \end{figure}
  6602. The skeleton for the \code{explicate-pred} function is given in
  6603. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  6604. that can have type \code{Boolean}. We detail a few cases here and
  6605. leave the rest for the reader. The input to this function is an
  6606. expression and two blocks, \code{thn} and \code{els}, for the two
  6607. branches of the enclosing \key{if}.
  6608. %
  6609. Consider the case for Boolean constants in
  6610. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  6611. evaluation\index{subject}{partial evaluation} and output either the \code{thn}
  6612. or \code{els} branch depending on whether the constant is true or
  6613. false. This case demonstrates that we sometimes discard the \code{thn}
  6614. or \code{els} blocks that are input to \code{explicate-pred}.
  6615. The case for \key{if} in \code{explicate-pred} is particularly
  6616. illuminating because it deals with the challenges we discussed above
  6617. regarding nested \key{if} expressions
  6618. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  6619. \lstinline{els^} branches of the \key{if} inherit their context from
  6620. the current one, that is, predicate context. So you should recursively
  6621. apply \code{explicate-pred} to the \lstinline{thn^} and
  6622. \lstinline{els^} branches. For both of those recursive calls, pass
  6623. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  6624. and \code{els} may get used twice, once inside each recursive call. As
  6625. discussed above, to avoid duplicating code, we need to add them to the
  6626. control-flow graph so that we can instead refer to them by name and
  6627. execute them with a \key{goto}. However, as we saw in the cases above
  6628. for Boolean constants, the blocks \code{thn} and \code{els} may not
  6629. get used at all and we don't want to prematurely add them to the
  6630. control-flow graph if they end up being discarded.
  6631. The solution to this conundrum is to use \emph{lazy
  6632. evaluation}\index{subject}{lazy evaluation}\citep{Friedman:1976aa} to delay
  6633. adding the blocks to the control-flow graph until the points where we
  6634. know they will be used. Racket provides support for lazy evaluation
  6635. with the
  6636. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  6637. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  6638. \index{subject}{delay} creates a \emph{promise}\index{subject}{promise} in which the
  6639. evaluation of the expressions is postponed. When \key{(force}
  6640. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the first
  6641. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  6642. $e_n$ is cached in the promise and returned. If \code{force} is
  6643. applied again to the same promise, then the cached result is returned.
  6644. If \code{force} is applied to an argument that is not a promise,
  6645. \code{force} simply returns the argument.
  6646. We use lazy evaluation for the input and output blocks of the
  6647. functions \code{explicate-pred} and \code{explicate-assign} and for
  6648. the output block of \code{explicate-tail}. So instead of taking and
  6649. returning blocks, they take and return promises. Furthermore, when we
  6650. come to a situation in which we a block might be used more than once,
  6651. as in the case for \code{if} in \code{explicate-pred}, we transform
  6652. the promise into a new promise that will add the block to the
  6653. control-flow graph and return a \code{goto}. The following auxiliary
  6654. function named \code{block->goto} accomplishes this task. It begins
  6655. with \code{delay} to create a promise. When forced, this promise will
  6656. force the original promise. If that returns a \code{goto} (because the
  6657. block was already added to the control-flow graph), then we return the
  6658. \code{goto}. Otherwise we add the block to the control-flow graph with
  6659. another auxiliary function named \code{add-node}. That function
  6660. returns the label for the new block, which we use to create a
  6661. \code{goto}.
  6662. \begin{lstlisting}
  6663. (define (block->goto block)
  6664. (delay
  6665. (define b (force block))
  6666. (match b
  6667. [(Goto label) (Goto label)]
  6668. [else (Goto (add-node b))])))
  6669. \end{lstlisting}
  6670. Returning to the discussion of \code{explicate-pred}
  6671. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  6672. operators. This is one of the base cases of the recursive function so
  6673. we translate the comparison to an \code{if} statement. We apply
  6674. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  6675. that will add then to the control-flow graph, which we can immediately
  6676. \code{force} to obtain the two goto's that form the branches of the
  6677. \code{if} statement.
  6678. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  6679. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  6680. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  6681. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  6682. %% results from the two recursive calls. We complete the case for
  6683. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  6684. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  6685. %% the result $B_5$.
  6686. %% \[
  6687. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  6688. %% \quad\Rightarrow\quad
  6689. %% B_5
  6690. %% \]
  6691. The \code{explicate-tail} and \code{explicate-assign} functions need
  6692. additional cases for Boolean constants and \key{if}.
  6693. %
  6694. In the cases for \code{if}, the two branches inherit the current
  6695. context, so in \code{explicate-tail} they are in tail position and in
  6696. \code{explicate-assign} they are in assignment position. The
  6697. \code{cont} parameter of \code{explicate-assign} is used in both
  6698. recursive calls, so make sure to use \code{block->goto} on it.
  6699. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  6700. %% inherit the current context, so they are in tail position. Thus, the
  6701. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  6702. %% \code{explicate-tail}.
  6703. %% %
  6704. %% We need to pass $B_0$ as the accumulator argument for both of these
  6705. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  6706. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  6707. %% to the control-flow graph and obtain a promised goto $G_0$.
  6708. %% %
  6709. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  6710. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  6711. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  6712. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  6713. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  6714. %% \[
  6715. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  6716. %% \]
  6717. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  6718. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  6719. %% should not be confused with the labels for the blocks that appear in
  6720. %% the generated code. We initially construct unlabeled blocks; we only
  6721. %% attach labels to blocks when we add them to the control-flow graph, as
  6722. %% we see in the next case.
  6723. %% Next consider the case for \key{if} in the \code{explicate-assign}
  6724. %% function. The context of the \key{if} is an assignment to some
  6725. %% variable $x$ and then the control continues to some promised block
  6726. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  6727. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  6728. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  6729. %% branches of the \key{if} inherit the current context, so they are in
  6730. %% assignment positions. Let $B_2$ be the result of applying
  6731. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  6732. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  6733. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  6734. %% the result of applying \code{explicate-pred} to the predicate
  6735. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  6736. %% translates to the promise $B_4$.
  6737. %% \[
  6738. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  6739. %% \]
  6740. %% This completes the description of \code{explicate-control} for \LangIf{}.
  6741. The way in which the \code{shrink} pass transforms logical operations
  6742. such as \code{and} and \code{or} can impact the quality of code
  6743. generated by \code{explicate-control}. For example, consider the
  6744. following program.
  6745. % cond_test_21.rkt, and_eq_input.py
  6746. \begin{lstlisting}
  6747. (if (and (eq? (read) 0) (eq? (read) 1))
  6748. 0
  6749. 42)
  6750. \end{lstlisting}
  6751. The \code{and} operation should transform into something that the
  6752. \code{explicate-pred} function can still analyze and descend through to
  6753. reach the underlying \code{eq?} conditions. Ideally, your
  6754. \code{explicate-control} pass should generate code similar to the
  6755. following for the above program.
  6756. \begin{center}
  6757. \begin{lstlisting}
  6758. start:
  6759. tmp1 = (read);
  6760. if (eq? tmp1 0) goto block40;
  6761. else goto block39;
  6762. block40:
  6763. tmp2 = (read);
  6764. if (eq? tmp2 1) goto block38;
  6765. else goto block39;
  6766. block38:
  6767. return 0;
  6768. block39:
  6769. return 42;
  6770. \end{lstlisting}
  6771. \end{center}
  6772. \begin{exercise}\normalfont
  6773. Implement the pass \code{explicate-control} by adding the cases for
  6774. Boolean constants and \key{if} to the \code{explicate-tail} and
  6775. \code{explicate-assign}. Implement the auxiliary function
  6776. \code{explicate-pred} for predicate contexts.
  6777. %
  6778. Create test cases that exercise all of the new cases in the code for
  6779. this pass.
  6780. %
  6781. Add the following entry to the list of \code{passes} in
  6782. \code{run-tests.rkt} and then run this script to test your compiler.
  6783. \begin{lstlisting}
  6784. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  6785. \end{lstlisting}
  6786. \end{exercise}
  6787. \section{Select Instructions}
  6788. \label{sec:select-Rif}
  6789. \index{subject}{instruction selection}
  6790. The \code{select-instructions} pass translate \LangCIf{} to
  6791. \LangXIfVar{}. Recall that we implement this pass using three
  6792. auxiliary functions, one for each of the non-terminals $\Atm$,
  6793. $\Stmt$, and $\Tail$.
  6794. For $\Atm$, we have new cases for the Booleans. We take the usual
  6795. approach of encoding them as integers, with true as 1 and false as 0.
  6796. \[
  6797. \key{\#t} \Rightarrow \key{1}
  6798. \qquad
  6799. \key{\#f} \Rightarrow \key{0}
  6800. \]
  6801. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  6802. be implemented in terms of \code{xorq} as we discussed at the
  6803. beginning of this section. Given an assignment
  6804. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  6805. if the left-hand side $\itm{var}$ is
  6806. the same as $\Atm$, then just the \code{xorq} suffices.
  6807. \[
  6808. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  6809. \quad\Rightarrow\quad
  6810. \key{xorq}~\key{\$}1\key{,}~\Var
  6811. \]
  6812. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  6813. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  6814. x86. Then we have
  6815. \[
  6816. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  6817. \quad\Rightarrow\quad
  6818. \begin{array}{l}
  6819. \key{movq}~\Arg\key{,}~\Var\\
  6820. \key{xorq}~\key{\$}1\key{,}~\Var
  6821. \end{array}
  6822. \]
  6823. Next consider the cases for \code{eq?} and less-than comparison.
  6824. Translating these operations to x86 is slightly involved due to the
  6825. unusual nature of the \key{cmpq} instruction discussed above. We
  6826. recommend translating an assignment from \code{eq?} into the following
  6827. sequence of three instructions. \\
  6828. \begin{tabular}{lll}
  6829. \begin{minipage}{0.4\textwidth}
  6830. \begin{lstlisting}
  6831. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  6832. \end{lstlisting}
  6833. \end{minipage}
  6834. &
  6835. $\Rightarrow$
  6836. &
  6837. \begin{minipage}{0.4\textwidth}
  6838. \begin{lstlisting}
  6839. cmpq |$\Arg_2$|, |$\Arg_1$|
  6840. sete %al
  6841. movzbq %al, |$\Var$|
  6842. \end{lstlisting}
  6843. \end{minipage}
  6844. \end{tabular} \\
  6845. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  6846. and \key{if} statements. Both are straightforward to translate to
  6847. x86. A \key{goto} becomes a jump instruction.
  6848. \[
  6849. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  6850. \]
  6851. An \key{if} statement becomes a compare instruction followed by a
  6852. conditional jump (for the ``then'' branch) and the fall-through is to
  6853. a regular jump (for the ``else'' branch).\\
  6854. \begin{tabular}{lll}
  6855. \begin{minipage}{0.4\textwidth}
  6856. \begin{lstlisting}
  6857. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  6858. else goto |$\ell_2$|;
  6859. \end{lstlisting}
  6860. \end{minipage}
  6861. &
  6862. $\Rightarrow$
  6863. &
  6864. \begin{minipage}{0.4\textwidth}
  6865. \begin{lstlisting}
  6866. cmpq |$\Arg_2$|, |$\Arg_1$|
  6867. je |$\ell_1$|
  6868. jmp |$\ell_2$|
  6869. \end{lstlisting}
  6870. \end{minipage}
  6871. \end{tabular} \\
  6872. \begin{exercise}\normalfont
  6873. Expand your \code{select-instructions} pass to handle the new features
  6874. of the \LangIf{} language.
  6875. %
  6876. Add the following entry to the list of \code{passes} in
  6877. \code{run-tests.rkt}
  6878. \begin{lstlisting}
  6879. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  6880. \end{lstlisting}
  6881. %
  6882. Run the script to test your compiler on all the test programs.
  6883. \end{exercise}
  6884. \section{Register Allocation}
  6885. \label{sec:register-allocation-Rif}
  6886. \index{subject}{register allocation}
  6887. The changes required for \LangIf{} affect liveness analysis, building the
  6888. interference graph, and assigning homes, but the graph coloring
  6889. algorithm itself does not change.
  6890. \subsection{Liveness Analysis}
  6891. \label{sec:liveness-analysis-Rif}
  6892. \index{subject}{liveness analysis}
  6893. Recall that for \LangVar{} we implemented liveness analysis for a single
  6894. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  6895. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  6896. produces many basic blocks arranged in a control-flow graph. We
  6897. recommend that you create a new auxiliary function named
  6898. \code{uncover-live-CFG} that applies liveness analysis to a
  6899. control-flow graph.
  6900. The first question we is: what order should we process the basic
  6901. blocks in the control-flow graph? Recall that to perform liveness
  6902. analysis on a basic block we need to know its live-after set. If a
  6903. basic block has no successors (i.e. no out-edges in the control flow
  6904. graph), then it has an empty live-after set and we can immediately
  6905. apply liveness analysis to it. If a basic block has some successors,
  6906. then we need to complete liveness analysis on those blocks first. In
  6907. graph theory, a sequence of nodes is in \emph{topological
  6908. order}\index{subject}{topological order} if each vertex comes before its
  6909. successors. We need the opposite, so we can transpose the graph
  6910. before computing a topological order.
  6911. %
  6912. Use the \code{tsort} and \code{transpose} functions of the Racket
  6913. \code{graph} package to accomplish this.
  6914. %
  6915. As an aside, a topological ordering is only guaranteed to exist if the
  6916. graph does not contain any cycles. That is indeed the case for the
  6917. control-flow graphs that we generate from \LangIf{} programs.
  6918. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  6919. learn how to handle cycles in the control-flow graph.
  6920. You'll need to construct a directed graph to represent the
  6921. control-flow graph. Do not use the \code{directed-graph} of the
  6922. \code{graph} package because that only allows at most one edge between
  6923. each pair of vertices, but a control-flow graph may have multiple
  6924. edges between a pair of vertices. The \code{multigraph.rkt} file in
  6925. the support code implements a graph representation that allows
  6926. multiple edges between a pair of vertices.
  6927. The next question is how to analyze jump instructions. Recall that in
  6928. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  6929. \code{label->live} that maps each label to the set of live locations
  6930. at the beginning of its block. We use \code{label->live} to determine
  6931. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  6932. that we have many basic blocks, \code{label->live} needs to be updated
  6933. as we process the blocks. In particular, after performing liveness
  6934. analysis on a block, we take the live-before set of its first
  6935. instruction and associate that with the block's label in the
  6936. \code{label->live}.
  6937. In \LangXIfVar{} we also have the conditional jump
  6938. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  6939. this instruction is particularly interesting because during
  6940. compilation we do not know which way a conditional jump will go. So
  6941. we do not know whether to use the live-before set for the following
  6942. instruction or the live-before set for the $\itm{label}$. However,
  6943. there is no harm to the correctness of the compiler if we classify
  6944. more locations as live than the ones that are truly live during a
  6945. particular execution of the instruction. Thus, we can take the union
  6946. of the live-before sets from the following instruction and from the
  6947. mapping for $\itm{label}$ in \code{label->live}.
  6948. The auxiliary functions for computing the variables in an
  6949. instruction's argument and for computing the variables read-from ($R$)
  6950. or written-to ($W$) by an instruction need to be updated to handle the
  6951. new kinds of arguments and instructions in \LangXIfVar{}.
  6952. \begin{exercise}\normalfont
  6953. Update the \code{uncover\_live} \racket{pass}\python{function} and implement the
  6954. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  6955. to the control-flow graph. Add the following entry to the list of
  6956. \code{passes} in the \code{run-tests.rkt} script.
  6957. \begin{lstlisting}
  6958. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  6959. \end{lstlisting}
  6960. \end{exercise}
  6961. \subsection{Build the Interference Graph}
  6962. \label{sec:build-interference-Rif}
  6963. Many of the new instructions in \LangXIfVar{} can be handled in the
  6964. same way as the instructions in \LangXVar{}. Thus, if your code was
  6965. already quite general, it will not need to be changed to handle the
  6966. new instructions. If you code is not general enough, we recommend that
  6967. you change your code to be more general. For example, you can factor
  6968. out the computing of the the read and write sets for each kind of
  6969. instruction into two auxiliary functions.
  6970. Note that the \key{movzbq} instruction requires some special care,
  6971. similar to the \key{movq} instruction. See rule number 1 in
  6972. Section~\ref{sec:build-interference}.
  6973. \begin{exercise}\normalfont
  6974. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  6975. following entries to the list of \code{passes} in the
  6976. \code{run-tests.rkt} script.
  6977. \begin{lstlisting}
  6978. (list "build-interference" build-interference interp-pseudo-x86-1)
  6979. (list "allocate-registers" allocate-registers interp-x86-1)
  6980. \end{lstlisting}
  6981. Run the script to test your compiler on all the \LangIf{} test
  6982. programs.
  6983. \end{exercise}
  6984. \section{Patch Instructions}
  6985. The second argument of the \key{cmpq} instruction must not be an
  6986. immediate value (such as an integer). So if you are comparing two
  6987. immediates, we recommend inserting a \key{movq} instruction to put the
  6988. second argument in \key{rax}. Also, recall that instructions may have
  6989. at most one memory reference.
  6990. %
  6991. The second argument of the \key{movzbq} must be a register.
  6992. %
  6993. There are no special restrictions on the jump instructions.
  6994. \begin{exercise}\normalfont
  6995. %
  6996. Update \code{patch-instructions} pass for \LangXIfVar{}.
  6997. %
  6998. Add the following entry to the list of \code{passes} in
  6999. \code{run-tests.rkt} and then run this script to test your compiler.
  7000. \begin{lstlisting}
  7001. (list "patch-instructions" patch-instructions interp-x86-1)
  7002. \end{lstlisting}
  7003. \end{exercise}
  7004. \begin{figure}[tbp]
  7005. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7006. \node (Rif) at (0,2) {\large \LangIf{}};
  7007. \node (Rif-2) at (3,2) {\large \LangIf{}};
  7008. \node (Rif-3) at (6,2) {\large \LangIf{}};
  7009. \node (Rif-4) at (9,2) {\large \LangIf{}};
  7010. \node (Rif-5) at (12,2) {\large \LangIf{}};
  7011. \node (C1-1) at (3,0) {\large \LangCIf{}};
  7012. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  7013. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  7014. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  7015. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  7016. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  7017. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  7018. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  7019. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  7020. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  7021. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  7022. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  7023. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  7024. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7025. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7026. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7027. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  7028. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  7029. \end{tikzpicture}
  7030. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  7031. \label{fig:Rif-passes}
  7032. \end{figure}
  7033. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  7034. compilation of \LangIf{}.
  7035. \section{An Example Translation}
  7036. Figure~\ref{fig:if-example-x86} shows a simple example program in
  7037. \LangIf{} translated to x86, showing the results of
  7038. \code{explicate-control}, \code{select-instructions}, and the final
  7039. x86 assembly code.
  7040. \begin{figure}[tbp]
  7041. \begin{tabular}{lll}
  7042. \begin{minipage}{0.4\textwidth}
  7043. % cond_test_20.rkt, eq_input.py
  7044. \begin{lstlisting}
  7045. (if (eq? (read) 1) 42 0)
  7046. \end{lstlisting}
  7047. $\Downarrow$
  7048. \begin{lstlisting}
  7049. start:
  7050. tmp7951 = (read);
  7051. if (eq? tmp7951 1)
  7052. goto block7952;
  7053. else
  7054. goto block7953;
  7055. block7952:
  7056. return 42;
  7057. block7953:
  7058. return 0;
  7059. \end{lstlisting}
  7060. $\Downarrow$
  7061. \begin{lstlisting}
  7062. start:
  7063. callq read_int
  7064. movq %rax, tmp7951
  7065. cmpq $1, tmp7951
  7066. je block7952
  7067. jmp block7953
  7068. block7953:
  7069. movq $0, %rax
  7070. jmp conclusion
  7071. block7952:
  7072. movq $42, %rax
  7073. jmp conclusion
  7074. \end{lstlisting}
  7075. \end{minipage}
  7076. &
  7077. $\Rightarrow\qquad$
  7078. \begin{minipage}{0.4\textwidth}
  7079. \begin{lstlisting}
  7080. start:
  7081. callq read_int
  7082. movq %rax, %rcx
  7083. cmpq $1, %rcx
  7084. je block7952
  7085. jmp block7953
  7086. block7953:
  7087. movq $0, %rax
  7088. jmp conclusion
  7089. block7952:
  7090. movq $42, %rax
  7091. jmp conclusion
  7092. .globl main
  7093. main:
  7094. pushq %rbp
  7095. movq %rsp, %rbp
  7096. pushq %r13
  7097. pushq %r12
  7098. pushq %rbx
  7099. pushq %r14
  7100. subq $0, %rsp
  7101. jmp start
  7102. conclusion:
  7103. addq $0, %rsp
  7104. popq %r14
  7105. popq %rbx
  7106. popq %r12
  7107. popq %r13
  7108. popq %rbp
  7109. retq
  7110. \end{lstlisting}
  7111. \end{minipage}
  7112. \end{tabular}
  7113. \caption{Example compilation of an \key{if} expression to x86.}
  7114. \label{fig:if-example-x86}
  7115. \end{figure}
  7116. \section{Challenge: Remove Jumps}
  7117. \label{sec:opt-jumps}
  7118. %% Recall that in the example output of \code{explicate-control} in
  7119. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  7120. %% \code{block60} are trivial blocks, they do nothing but jump to another
  7121. %% block. The first goal of this challenge assignment is to remove those
  7122. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  7123. %% \code{explicate-control} on the left and shows the result of bypassing
  7124. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  7125. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  7126. %% \code{block55}. The optimized code on the right of
  7127. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  7128. %% \code{then} branch jumping directly to \code{block55}. The story is
  7129. %% similar for the \code{else} branch, as well as for the two branches in
  7130. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  7131. %% have been optimized in this way, there are no longer any jumps to
  7132. %% blocks \code{block57} through \code{block60}, so they can be removed.
  7133. %% \begin{figure}[tbp]
  7134. %% \begin{tabular}{lll}
  7135. %% \begin{minipage}{0.4\textwidth}
  7136. %% \begin{lstlisting}
  7137. %% block62:
  7138. %% tmp54 = (read);
  7139. %% if (eq? tmp54 2) then
  7140. %% goto block59;
  7141. %% else
  7142. %% goto block60;
  7143. %% block61:
  7144. %% tmp53 = (read);
  7145. %% if (eq? tmp53 0) then
  7146. %% goto block57;
  7147. %% else
  7148. %% goto block58;
  7149. %% block60:
  7150. %% goto block56;
  7151. %% block59:
  7152. %% goto block55;
  7153. %% block58:
  7154. %% goto block56;
  7155. %% block57:
  7156. %% goto block55;
  7157. %% block56:
  7158. %% return (+ 700 77);
  7159. %% block55:
  7160. %% return (+ 10 32);
  7161. %% start:
  7162. %% tmp52 = (read);
  7163. %% if (eq? tmp52 1) then
  7164. %% goto block61;
  7165. %% else
  7166. %% goto block62;
  7167. %% \end{lstlisting}
  7168. %% \end{minipage}
  7169. %% &
  7170. %% $\Rightarrow$
  7171. %% &
  7172. %% \begin{minipage}{0.55\textwidth}
  7173. %% \begin{lstlisting}
  7174. %% block62:
  7175. %% tmp54 = (read);
  7176. %% if (eq? tmp54 2) then
  7177. %% goto block55;
  7178. %% else
  7179. %% goto block56;
  7180. %% block61:
  7181. %% tmp53 = (read);
  7182. %% if (eq? tmp53 0) then
  7183. %% goto block55;
  7184. %% else
  7185. %% goto block56;
  7186. %% block56:
  7187. %% return (+ 700 77);
  7188. %% block55:
  7189. %% return (+ 10 32);
  7190. %% start:
  7191. %% tmp52 = (read);
  7192. %% if (eq? tmp52 1) then
  7193. %% goto block61;
  7194. %% else
  7195. %% goto block62;
  7196. %% \end{lstlisting}
  7197. %% \end{minipage}
  7198. %% \end{tabular}
  7199. %% \caption{Optimize jumps by removing trivial blocks.}
  7200. %% \label{fig:optimize-jumps}
  7201. %% \end{figure}
  7202. %% The name of this pass is \code{optimize-jumps}. We recommend
  7203. %% implementing this pass in two phases. The first phrase builds a hash
  7204. %% table that maps labels to possibly improved labels. The second phase
  7205. %% changes the target of each \code{goto} to use the improved label. If
  7206. %% the label is for a trivial block, then the hash table should map the
  7207. %% label to the first non-trivial block that can be reached from this
  7208. %% label by jumping through trivial blocks. If the label is for a
  7209. %% non-trivial block, then the hash table should map the label to itself;
  7210. %% we do not want to change jumps to non-trivial blocks.
  7211. %% The first phase can be accomplished by constructing an empty hash
  7212. %% table, call it \code{short-cut}, and then iterating over the control
  7213. %% flow graph. Each time you encouter a block that is just a \code{goto},
  7214. %% then update the hash table, mapping the block's source to the target
  7215. %% of the \code{goto}. Also, the hash table may already have mapped some
  7216. %% labels to the block's source, to you must iterate through the hash
  7217. %% table and update all of those so that they instead map to the target
  7218. %% of the \code{goto}.
  7219. %% For the second phase, we recommend iterating through the $\Tail$ of
  7220. %% each block in the program, updating the target of every \code{goto}
  7221. %% according to the mapping in \code{short-cut}.
  7222. %% \begin{exercise}\normalfont
  7223. %% Implement the \code{optimize-jumps} pass as a transformation from
  7224. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  7225. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  7226. %% example programs. Then check that your compiler still passes all of
  7227. %% your tests.
  7228. %% \end{exercise}
  7229. There is an opportunity for optimizing jumps that is apparent in the
  7230. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  7231. ends with a jump to \code{block7953} and there are no other jumps to
  7232. \code{block7953} in the rest of the program. In this situation we can
  7233. avoid the runtime overhead of this jump by merging \code{block7953}
  7234. into the preceding block, in this case the \code{start} block.
  7235. Figure~\ref{fig:remove-jumps} shows the output of
  7236. \code{select-instructions} on the left and the result of this
  7237. optimization on the right.
  7238. \begin{figure}[tbp]
  7239. \begin{tabular}{lll}
  7240. \begin{minipage}{0.5\textwidth}
  7241. % cond_test_20.rkt
  7242. \begin{lstlisting}
  7243. start:
  7244. callq read_int
  7245. movq %rax, tmp7951
  7246. cmpq $1, tmp7951
  7247. je block7952
  7248. jmp block7953
  7249. block7953:
  7250. movq $0, %rax
  7251. jmp conclusion
  7252. block7952:
  7253. movq $42, %rax
  7254. jmp conclusion
  7255. \end{lstlisting}
  7256. \end{minipage}
  7257. &
  7258. $\Rightarrow\qquad$
  7259. \begin{minipage}{0.4\textwidth}
  7260. \begin{lstlisting}
  7261. start:
  7262. callq read_int
  7263. movq %rax, tmp7951
  7264. cmpq $1, tmp7951
  7265. je block7952
  7266. movq $0, %rax
  7267. jmp conclusion
  7268. block7952:
  7269. movq $42, %rax
  7270. jmp conclusion
  7271. \end{lstlisting}
  7272. \end{minipage}
  7273. \end{tabular}
  7274. \caption{Merging basic blocks by removing unnecessary jumps.}
  7275. \label{fig:remove-jumps}
  7276. \end{figure}
  7277. \begin{exercise}\normalfont
  7278. %
  7279. Implement a pass named \code{remove-jumps} that merges basic blocks
  7280. into their preceding basic block, when there is only one preceding
  7281. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  7282. %
  7283. In the \code{run-tests.rkt} script, add the following entry to the
  7284. list of \code{passes} between \code{allocate-registers}
  7285. and \code{patch-instructions}.
  7286. \begin{lstlisting}
  7287. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  7288. \end{lstlisting}
  7289. Run this script to test your compiler.
  7290. %
  7291. Check that \code{remove-jumps} accomplishes the goal of merging basic
  7292. blocks on several test programs.
  7293. \end{exercise}
  7294. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7295. \chapter{Tuples and Garbage Collection}
  7296. \label{ch:Rvec}
  7297. \index{subject}{tuple}
  7298. \index{subject}{vector}
  7299. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  7300. %% all the IR grammars are spelled out! \\ --Jeremy}
  7301. %% \margincomment{\scriptsize Be more explicit about how to deal with
  7302. %% the root stack. \\ --Jeremy}
  7303. In this chapter we study the implementation of mutable tuples, called
  7304. vectors in Racket. This language feature is the first to use the
  7305. computer's \emph{heap}\index{subject}{heap} because the lifetime of a Racket
  7306. tuple is indefinite, that is, a tuple lives forever from the
  7307. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  7308. is important to reclaim the space associated with a tuple when it is
  7309. no longer needed, which is why we also study \emph{garbage collection}
  7310. \emph{garbage collection} techniques in this chapter.
  7311. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  7312. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  7313. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  7314. \code{void} value. The reason for including the later is that the
  7315. \code{vector-set!} operation returns a value of type
  7316. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  7317. called the \code{Unit} type in the programming languages
  7318. literature. Racket's \code{Void} type is inhabited by a single value
  7319. \code{void} which corresponds to \code{unit} or \code{()} in the
  7320. literature~\citep{Pierce:2002hj}.}.
  7321. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  7322. copying live objects back and forth between two halves of the
  7323. heap. The garbage collector requires coordination with the compiler so
  7324. that it can see all of the \emph{root} pointers, that is, pointers in
  7325. registers or on the procedure call stack.
  7326. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  7327. discuss all the necessary changes and additions to the compiler
  7328. passes, including a new compiler pass named \code{expose-allocation}.
  7329. \section{The \LangVec{} Language}
  7330. \label{sec:r3}
  7331. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  7332. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  7333. \LangVec{} language includes three new forms: \code{vector} for creating a
  7334. tuple, \code{vector-ref} for reading an element of a tuple, and
  7335. \code{vector-set!} for writing to an element of a tuple. The program
  7336. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  7337. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  7338. the 3-tuple, demonstrating that tuples are first-class values. The
  7339. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  7340. of the \key{if} is taken. The element at index $0$ of \code{t} is
  7341. \code{40}, to which we add \code{2}, the element at index $0$ of the
  7342. 1-tuple. So the result of the program is \code{42}.
  7343. \begin{figure}[tbp]
  7344. \centering
  7345. \fbox{
  7346. \begin{minipage}{0.96\textwidth}
  7347. \[
  7348. \begin{array}{lcl}
  7349. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}}
  7350. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}\\
  7351. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  7352. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  7353. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  7354. \MID \LP\key{and}\;\Exp\;\Exp\RP
  7355. \MID \LP\key{or}\;\Exp\;\Exp\RP
  7356. \MID \LP\key{not}\;\Exp\RP } \\
  7357. &\MID& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  7358. \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  7359. &\MID& \LP\key{vector}\;\Exp\ldots\RP
  7360. \MID \LP\key{vector-length}\;\Exp\RP \\
  7361. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  7362. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  7363. &\MID& \LP\key{void}\RP \MID \LP\key{has-type}~\Exp~\Type\RP\\
  7364. \LangVecM{} &::=& \Exp
  7365. \end{array}
  7366. \]
  7367. \end{minipage}
  7368. }
  7369. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  7370. (Figure~\ref{fig:Rif-concrete-syntax}).}
  7371. \label{fig:Rvec-concrete-syntax}
  7372. \end{figure}
  7373. \begin{figure}[tbp]
  7374. \begin{lstlisting}
  7375. (let ([t (vector 40 #t (vector 2))])
  7376. (if (vector-ref t 1)
  7377. (+ (vector-ref t 0)
  7378. (vector-ref (vector-ref t 2) 0))
  7379. 44))
  7380. \end{lstlisting}
  7381. \caption{Example program that creates tuples and reads from them.}
  7382. \label{fig:vector-eg}
  7383. \end{figure}
  7384. \begin{figure}[tp]
  7385. \centering
  7386. \fbox{
  7387. \begin{minipage}{0.96\textwidth}
  7388. \[
  7389. \begin{array}{lcl}
  7390. \itm{op} &::=& \ldots \MID \code{vector} \MID \code{vector-length} \\
  7391. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  7392. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  7393. \MID \BOOL{\itm{bool}}
  7394. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  7395. &\MID& \VECREF{\Exp}{\INT{\Int}}\\
  7396. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  7397. &\MID& \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP \\
  7398. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  7399. \end{array}
  7400. \]
  7401. \end{minipage}
  7402. }
  7403. \caption{The abstract syntax of \LangVec{}.}
  7404. \label{fig:Rvec-syntax}
  7405. \end{figure}
  7406. \index{subject}{allocate}
  7407. \index{subject}{heap allocate}
  7408. Tuples are our first encounter with heap-allocated data, which raises
  7409. several interesting issues. First, variable binding performs a
  7410. shallow-copy when dealing with tuples, which means that different
  7411. variables can refer to the same tuple, that is, different variables
  7412. can be \emph{aliases} for the same entity. Consider the following
  7413. example in which both \code{t1} and \code{t2} refer to the same tuple.
  7414. Thus, the mutation through \code{t2} is visible when referencing the
  7415. tuple from \code{t1}, so the result of this program is \code{42}.
  7416. \index{subject}{alias}\index{subject}{mutation}
  7417. \begin{center}
  7418. \begin{minipage}{0.96\textwidth}
  7419. \begin{lstlisting}
  7420. (let ([t1 (vector 3 7)])
  7421. (let ([t2 t1])
  7422. (let ([_ (vector-set! t2 0 42)])
  7423. (vector-ref t1 0))))
  7424. \end{lstlisting}
  7425. \end{minipage}
  7426. \end{center}
  7427. The next issue concerns the lifetime of tuples. Of course, they are
  7428. created by the \code{vector} form, but when does their lifetime end?
  7429. Notice that \LangVec{} does not include an operation for deleting
  7430. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  7431. of static scoping. For example, the following program returns
  7432. \code{42} even though the variable \code{w} goes out of scope prior to
  7433. the \code{vector-ref} that reads from the vector it was bound to.
  7434. \begin{center}
  7435. \begin{minipage}{0.96\textwidth}
  7436. \begin{lstlisting}
  7437. (let ([v (vector (vector 44))])
  7438. (let ([x (let ([w (vector 42)])
  7439. (let ([_ (vector-set! v 0 w)])
  7440. 0))])
  7441. (+ x (vector-ref (vector-ref v 0) 0))))
  7442. \end{lstlisting}
  7443. \end{minipage}
  7444. \end{center}
  7445. From the perspective of programmer-observable behavior, tuples live
  7446. forever. Of course, if they really lived forever, then many programs
  7447. would run out of memory.\footnote{The \LangVec{} language does not have
  7448. looping or recursive functions, so it is nigh impossible to write a
  7449. program in \LangVec{} that will run out of memory. However, we add
  7450. recursive functions in the next Chapter!} A Racket implementation
  7451. must therefore perform automatic garbage collection.
  7452. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  7453. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  7454. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  7455. terms of the corresponding operations in Racket. One subtle point is
  7456. that the \code{vector-set!} operation returns the \code{\#<void>}
  7457. value. The \code{\#<void>} value can be passed around just like other
  7458. values inside an \LangVec{} program and a \code{\#<void>} value can be
  7459. compared for equality with another \code{\#<void>} value. However,
  7460. there are no other operations specific to the the \code{\#<void>}
  7461. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  7462. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  7463. otherwise.
  7464. \begin{figure}[tbp]
  7465. \begin{lstlisting}
  7466. (define interp-Rvec_class
  7467. (class interp-Rif_class
  7468. (super-new)
  7469. (define/override (interp-op op)
  7470. (match op
  7471. ['eq? (lambda (v1 v2)
  7472. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7473. (and (boolean? v1) (boolean? v2))
  7474. (and (vector? v1) (vector? v2))
  7475. (and (void? v1) (void? v2)))
  7476. (eq? v1 v2)]))]
  7477. ['vector vector]
  7478. ['vector-length vector-length]
  7479. ['vector-ref vector-ref]
  7480. ['vector-set! vector-set!]
  7481. [else (super interp-op op)]
  7482. ))
  7483. (define/override ((interp-exp env) e)
  7484. (define recur (interp-exp env))
  7485. (match e
  7486. [(HasType e t) (recur e)]
  7487. [(Void) (void)]
  7488. [else ((super interp-exp env) e)]
  7489. ))
  7490. ))
  7491. (define (interp-Rvec p)
  7492. (send (new interp-Rvec_class) interp-program p))
  7493. \end{lstlisting}
  7494. \caption{Interpreter for the \LangVec{} language.}
  7495. \label{fig:interp-Rvec}
  7496. \end{figure}
  7497. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  7498. deserves some explanation. When allocating a vector, we need to know
  7499. which elements of the vector are pointers (i.e. are also vectors). We
  7500. can obtain this information during type checking. The type checker in
  7501. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  7502. expression, it also wraps every \key{vector} creation with the form
  7503. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  7504. %
  7505. To create the s-expression for the \code{Vector} type in
  7506. Figure~\ref{fig:type-check-Rvec}, we use the
  7507. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  7508. operator} \code{,@} to insert the list \code{t*} without its usual
  7509. start and end parentheses. \index{subject}{unquote-slicing}
  7510. \begin{figure}[tp]
  7511. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7512. (define type-check-Rvec_class
  7513. (class type-check-Rif_class
  7514. (super-new)
  7515. (inherit check-type-equal?)
  7516. (define/override (type-check-exp env)
  7517. (lambda (e)
  7518. (define recur (type-check-exp env))
  7519. (match e
  7520. [(Void) (values (Void) 'Void)]
  7521. [(Prim 'vector es)
  7522. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  7523. (define t `(Vector ,@t*))
  7524. (values (HasType (Prim 'vector e*) t) t)]
  7525. [(Prim 'vector-ref (list e1 (Int i)))
  7526. (define-values (e1^ t) (recur e1))
  7527. (match t
  7528. [`(Vector ,ts ...)
  7529. (unless (and (0 . <= . i) (i . < . (length ts)))
  7530. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  7531. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  7532. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  7533. [(Prim 'vector-set! (list e1 (Int i) arg) )
  7534. (define-values (e-vec t-vec) (recur e1))
  7535. (define-values (e-arg^ t-arg) (recur arg))
  7536. (match t-vec
  7537. [`(Vector ,ts ...)
  7538. (unless (and (0 . <= . i) (i . < . (length ts)))
  7539. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  7540. (check-type-equal? (list-ref ts i) t-arg e)
  7541. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  7542. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  7543. [(Prim 'vector-length (list e))
  7544. (define-values (e^ t) (recur e))
  7545. (match t
  7546. [`(Vector ,ts ...)
  7547. (values (Prim 'vector-length (list e^)) 'Integer)]
  7548. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  7549. [(Prim 'eq? (list arg1 arg2))
  7550. (define-values (e1 t1) (recur arg1))
  7551. (define-values (e2 t2) (recur arg2))
  7552. (match* (t1 t2)
  7553. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  7554. [(other wise) (check-type-equal? t1 t2 e)])
  7555. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  7556. [(HasType (Prim 'vector es) t)
  7557. ((type-check-exp env) (Prim 'vector es))]
  7558. [(HasType e1 t)
  7559. (define-values (e1^ t^) (recur e1))
  7560. (check-type-equal? t t^ e)
  7561. (values (HasType e1^ t) t)]
  7562. [else ((super type-check-exp env) e)]
  7563. )))
  7564. ))
  7565. (define (type-check-Rvec p)
  7566. (send (new type-check-Rvec_class) type-check-program p))
  7567. \end{lstlisting}
  7568. \caption{Type checker for the \LangVec{} language.}
  7569. \label{fig:type-check-Rvec}
  7570. \end{figure}
  7571. \section{Garbage Collection}
  7572. \label{sec:GC}
  7573. Here we study a relatively simple algorithm for garbage collection
  7574. that is the basis of state-of-the-art garbage
  7575. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  7576. particular, we describe a two-space copying
  7577. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  7578. perform the
  7579. copy~\citep{Cheney:1970aa}.
  7580. \index{subject}{copying collector}
  7581. \index{subject}{two-space copying collector}
  7582. Figure~\ref{fig:copying-collector} gives a
  7583. coarse-grained depiction of what happens in a two-space collector,
  7584. showing two time steps, prior to garbage collection (on the top) and
  7585. after garbage collection (on the bottom). In a two-space collector,
  7586. the heap is divided into two parts named the FromSpace and the
  7587. ToSpace. Initially, all allocations go to the FromSpace until there is
  7588. not enough room for the next allocation request. At that point, the
  7589. garbage collector goes to work to make more room.
  7590. \index{subject}{ToSpace}
  7591. \index{subject}{FromSpace}
  7592. The garbage collector must be careful not to reclaim tuples that will
  7593. be used by the program in the future. Of course, it is impossible in
  7594. general to predict what a program will do, but we can over approximate
  7595. the will-be-used tuples by preserving all tuples that could be
  7596. accessed by \emph{any} program given the current computer state. A
  7597. program could access any tuple whose address is in a register or on
  7598. the procedure call stack. These addresses are called the \emph{root
  7599. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  7600. transitively reachable from the root set. Thus, it is safe for the
  7601. garbage collector to reclaim the tuples that are not reachable in this
  7602. way.
  7603. So the goal of the garbage collector is twofold:
  7604. \begin{enumerate}
  7605. \item preserve all tuple that are reachable from the root set via a
  7606. path of pointers, that is, the \emph{live} tuples, and
  7607. \item reclaim the memory of everything else, that is, the
  7608. \emph{garbage}.
  7609. \end{enumerate}
  7610. A copying collector accomplishes this by copying all of the live
  7611. objects from the FromSpace into the ToSpace and then performs a sleight
  7612. of hand, treating the ToSpace as the new FromSpace and the old
  7613. FromSpace as the new ToSpace. In the example of
  7614. Figure~\ref{fig:copying-collector}, there are three pointers in the
  7615. root set, one in a register and two on the stack. All of the live
  7616. objects have been copied to the ToSpace (the right-hand side of
  7617. Figure~\ref{fig:copying-collector}) in a way that preserves the
  7618. pointer relationships. For example, the pointer in the register still
  7619. points to a 2-tuple whose first element is a 3-tuple and whose second
  7620. element is a 2-tuple. There are four tuples that are not reachable
  7621. from the root set and therefore do not get copied into the ToSpace.
  7622. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  7623. created by a well-typed program in \LangVec{} because it contains a
  7624. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  7625. We design the garbage collector to deal with cycles to begin with so
  7626. we will not need to revisit this issue.
  7627. \begin{figure}[tbp]
  7628. \centering
  7629. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  7630. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  7631. \caption{A copying collector in action.}
  7632. \label{fig:copying-collector}
  7633. \end{figure}
  7634. There are many alternatives to copying collectors (and their bigger
  7635. siblings, the generational collectors) when its comes to garbage
  7636. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  7637. reference counting~\citep{Collins:1960aa}. The strengths of copying
  7638. collectors are that allocation is fast (just a comparison and pointer
  7639. increment), there is no fragmentation, cyclic garbage is collected,
  7640. and the time complexity of collection only depends on the amount of
  7641. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  7642. main disadvantages of a two-space copying collector is that it uses a
  7643. lot of space and takes a long time to perform the copy, though these
  7644. problems are ameliorated in generational collectors. Racket and
  7645. Scheme programs tend to allocate many small objects and generate a lot
  7646. of garbage, so copying and generational collectors are a good fit.
  7647. Garbage collection is an active research topic, especially concurrent
  7648. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  7649. developing new techniques and revisiting old
  7650. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  7651. meet every year at the International Symposium on Memory Management to
  7652. present these findings.
  7653. \subsection{Graph Copying via Cheney's Algorithm}
  7654. \label{sec:cheney}
  7655. \index{subject}{Cheney's algorithm}
  7656. Let us take a closer look at the copying of the live objects. The
  7657. allocated objects and pointers can be viewed as a graph and we need to
  7658. copy the part of the graph that is reachable from the root set. To
  7659. make sure we copy all of the reachable vertices in the graph, we need
  7660. an exhaustive graph traversal algorithm, such as depth-first search or
  7661. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  7662. such algorithms take into account the possibility of cycles by marking
  7663. which vertices have already been visited, so as to ensure termination
  7664. of the algorithm. These search algorithms also use a data structure
  7665. such as a stack or queue as a to-do list to keep track of the vertices
  7666. that need to be visited. We use breadth-first search and a trick
  7667. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  7668. and copying tuples into the ToSpace.
  7669. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  7670. copy progresses. The queue is represented by a chunk of contiguous
  7671. memory at the beginning of the ToSpace, using two pointers to track
  7672. the front and the back of the queue. The algorithm starts by copying
  7673. all tuples that are immediately reachable from the root set into the
  7674. ToSpace to form the initial queue. When we copy a tuple, we mark the
  7675. old tuple to indicate that it has been visited. We discuss how this
  7676. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  7677. pointers inside the copied tuples in the queue still point back to the
  7678. FromSpace. Once the initial queue has been created, the algorithm
  7679. enters a loop in which it repeatedly processes the tuple at the front
  7680. of the queue and pops it off the queue. To process a tuple, the
  7681. algorithm copies all the tuple that are directly reachable from it to
  7682. the ToSpace, placing them at the back of the queue. The algorithm then
  7683. updates the pointers in the popped tuple so they point to the newly
  7684. copied tuples.
  7685. \begin{figure}[tbp]
  7686. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  7687. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  7688. \label{fig:cheney}
  7689. \end{figure}
  7690. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  7691. tuple whose second element is $42$ to the back of the queue. The other
  7692. pointer goes to a tuple that has already been copied, so we do not
  7693. need to copy it again, but we do need to update the pointer to the new
  7694. location. This can be accomplished by storing a \emph{forwarding
  7695. pointer} to the new location in the old tuple, back when we initially
  7696. copied the tuple into the ToSpace. This completes one step of the
  7697. algorithm. The algorithm continues in this way until the front of the
  7698. queue is empty, that is, until the front catches up with the back.
  7699. \subsection{Data Representation}
  7700. \label{sec:data-rep-gc}
  7701. The garbage collector places some requirements on the data
  7702. representations used by our compiler. First, the garbage collector
  7703. needs to distinguish between pointers and other kinds of data. There
  7704. are several ways to accomplish this.
  7705. \begin{enumerate}
  7706. \item Attached a tag to each object that identifies what type of
  7707. object it is~\citep{McCarthy:1960dz}.
  7708. \item Store different types of objects in different
  7709. regions~\citep{Steele:1977ab}.
  7710. \item Use type information from the program to either generate
  7711. type-specific code for collecting or to generate tables that can
  7712. guide the
  7713. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  7714. \end{enumerate}
  7715. Dynamically typed languages, such as Lisp, need to tag objects
  7716. anyways, so option 1 is a natural choice for those languages.
  7717. However, \LangVec{} is a statically typed language, so it would be
  7718. unfortunate to require tags on every object, especially small and
  7719. pervasive objects like integers and Booleans. Option 3 is the
  7720. best-performing choice for statically typed languages, but comes with
  7721. a relatively high implementation complexity. To keep this chapter
  7722. within a 2-week time budget, we recommend a combination of options 1
  7723. and 2, using separate strategies for the stack and the heap.
  7724. Regarding the stack, we recommend using a separate stack for pointers,
  7725. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  7726. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  7727. is, when a local variable needs to be spilled and is of type
  7728. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  7729. stack instead of the normal procedure call stack. Furthermore, we
  7730. always spill vector-typed variables if they are live during a call to
  7731. the collector, thereby ensuring that no pointers are in registers
  7732. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  7733. example from Figure~\ref{fig:copying-collector} and contrasts it with
  7734. the data layout using a root stack. The root stack contains the two
  7735. pointers from the regular stack and also the pointer in the second
  7736. register.
  7737. \begin{figure}[tbp]
  7738. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  7739. \caption{Maintaining a root stack to facilitate garbage collection.}
  7740. \label{fig:shadow-stack}
  7741. \end{figure}
  7742. The problem of distinguishing between pointers and other kinds of data
  7743. also arises inside of each tuple on the heap. We solve this problem by
  7744. attaching a tag, an extra 64-bits, to each
  7745. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  7746. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  7747. that we have drawn the bits in a big-endian way, from right-to-left,
  7748. with bit location 0 (the least significant bit) on the far right,
  7749. which corresponds to the direction of the x86 shifting instructions
  7750. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  7751. is dedicated to specifying which elements of the tuple are pointers,
  7752. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  7753. indicates there is a pointer and a 0 bit indicates some other kind of
  7754. data. The pointer mask starts at bit location 7. We have limited
  7755. tuples to a maximum size of 50 elements, so we just need 50 bits for
  7756. the pointer mask. The tag also contains two other pieces of
  7757. information. The length of the tuple (number of elements) is stored in
  7758. bits location 1 through 6. Finally, the bit at location 0 indicates
  7759. whether the tuple has yet to be copied to the ToSpace. If the bit has
  7760. value 1, then this tuple has not yet been copied. If the bit has
  7761. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  7762. of a pointer are always zero anyways because our tuples are 8-byte
  7763. aligned.)
  7764. \begin{figure}[tbp]
  7765. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  7766. \caption{Representation of tuples in the heap.}
  7767. \label{fig:tuple-rep}
  7768. \end{figure}
  7769. \subsection{Implementation of the Garbage Collector}
  7770. \label{sec:organize-gz}
  7771. \index{subject}{prelude}
  7772. An implementation of the copying collector is provided in the
  7773. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  7774. interface to the garbage collector that is used by the compiler. The
  7775. \code{initialize} function creates the FromSpace, ToSpace, and root
  7776. stack and should be called in the prelude of the \code{main}
  7777. function. The arguments of \code{initialize} are the root stack size
  7778. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  7779. good choice for both. The \code{initialize} function puts the address
  7780. of the beginning of the FromSpace into the global variable
  7781. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  7782. the address that is 1-past the last element of the FromSpace. (We use
  7783. half-open intervals to represent chunks of
  7784. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  7785. points to the first element of the root stack.
  7786. As long as there is room left in the FromSpace, your generated code
  7787. can allocate tuples simply by moving the \code{free\_ptr} forward.
  7788. %
  7789. The amount of room left in FromSpace is the difference between the
  7790. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  7791. function should be called when there is not enough room left in the
  7792. FromSpace for the next allocation. The \code{collect} function takes
  7793. a pointer to the current top of the root stack (one past the last item
  7794. that was pushed) and the number of bytes that need to be
  7795. allocated. The \code{collect} function performs the copying collection
  7796. and leaves the heap in a state such that the next allocation will
  7797. succeed.
  7798. \begin{figure}[tbp]
  7799. \begin{lstlisting}
  7800. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  7801. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  7802. int64_t* free_ptr;
  7803. int64_t* fromspace_begin;
  7804. int64_t* fromspace_end;
  7805. int64_t** rootstack_begin;
  7806. \end{lstlisting}
  7807. \caption{The compiler's interface to the garbage collector.}
  7808. \label{fig:gc-header}
  7809. \end{figure}
  7810. %% \begin{exercise}
  7811. %% In the file \code{runtime.c} you will find the implementation of
  7812. %% \code{initialize} and a partial implementation of \code{collect}.
  7813. %% The \code{collect} function calls another function, \code{cheney},
  7814. %% to perform the actual copy, and that function is left to the reader
  7815. %% to implement. The following is the prototype for \code{cheney}.
  7816. %% \begin{lstlisting}
  7817. %% static void cheney(int64_t** rootstack_ptr);
  7818. %% \end{lstlisting}
  7819. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  7820. %% rootstack (which is an array of pointers). The \code{cheney} function
  7821. %% also communicates with \code{collect} through the global
  7822. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  7823. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  7824. %% the ToSpace:
  7825. %% \begin{lstlisting}
  7826. %% static int64_t* tospace_begin;
  7827. %% static int64_t* tospace_end;
  7828. %% \end{lstlisting}
  7829. %% The job of the \code{cheney} function is to copy all the live
  7830. %% objects (reachable from the root stack) into the ToSpace, update
  7831. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  7832. %% update the root stack so that it points to the objects in the
  7833. %% ToSpace, and finally to swap the global pointers for the FromSpace
  7834. %% and ToSpace.
  7835. %% \end{exercise}
  7836. %% \section{Compiler Passes}
  7837. %% \label{sec:code-generation-gc}
  7838. The introduction of garbage collection has a non-trivial impact on our
  7839. compiler passes. We introduce a new compiler pass named
  7840. \code{expose-allocation}. We make
  7841. significant changes to \code{select-instructions},
  7842. \code{build-interference}, \code{allocate-registers}, and
  7843. \code{print\_x86} and make minor changes in several more passes. The
  7844. following program will serve as our running example. It creates two
  7845. tuples, one nested inside the other. Both tuples have length one. The
  7846. program accesses the element in the inner tuple tuple via two vector
  7847. references.
  7848. % tests/s2_17.rkt
  7849. \begin{lstlisting}
  7850. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  7851. \end{lstlisting}
  7852. \section{Shrink}
  7853. \label{sec:shrink-Rvec}
  7854. Recall that the \code{shrink} pass translates the primitives operators
  7855. into a smaller set of primitives. Because this pass comes after type
  7856. checking, but before the passes that require the type information in
  7857. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  7858. to wrap \code{HasType} around each AST node that it generates.
  7859. \section{Expose Allocation}
  7860. \label{sec:expose-allocation}
  7861. The pass \code{expose-allocation} lowers the \code{vector} creation
  7862. form into a conditional call to the collector followed by the
  7863. allocation. We choose to place the \code{expose-allocation} pass
  7864. before \code{remove-complex-opera*} because the code generated by
  7865. \code{expose-allocation} contains complex operands. We also place
  7866. \code{expose-allocation} before \code{explicate-control} because
  7867. \code{expose-allocation} introduces new variables using \code{let},
  7868. but \code{let} is gone after \code{explicate-control}.
  7869. The output of \code{expose-allocation} is a language \LangAlloc{} that
  7870. extends \LangVec{} with the three new forms that we use in the translation
  7871. of the \code{vector} form.
  7872. \[
  7873. \begin{array}{lcl}
  7874. \Exp &::=& \cdots
  7875. \MID (\key{collect} \,\itm{int})
  7876. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  7877. \MID (\key{global-value} \,\itm{name})
  7878. \end{array}
  7879. \]
  7880. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  7881. $n$ bytes. It will become a call to the \code{collect} function in
  7882. \code{runtime.c} in \code{select-instructions}. The
  7883. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  7884. \index{subject}{allocate}
  7885. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  7886. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  7887. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  7888. a global variable, such as \code{free\_ptr}.
  7889. In the following, we show the transformation for the \code{vector}
  7890. form into 1) a sequence of let-bindings for the initializing
  7891. expressions, 2) a conditional call to \code{collect}, 3) a call to
  7892. \code{allocate}, and 4) the initialization of the vector. In the
  7893. following, \itm{len} refers to the length of the vector and
  7894. \itm{bytes} is how many total bytes need to be allocated for the
  7895. vector, which is 8 for the tag plus \itm{len} times 8.
  7896. \begin{lstlisting}
  7897. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  7898. |$\Longrightarrow$|
  7899. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  7900. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  7901. (global-value fromspace_end))
  7902. (void)
  7903. (collect |\itm{bytes}|))])
  7904. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  7905. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  7906. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  7907. |$v$|) ... )))) ...)
  7908. \end{lstlisting}
  7909. In the above, we suppressed all of the \code{has-type} forms in the
  7910. output for the sake of readability. The placement of the initializing
  7911. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  7912. sequence of \code{vector-set!} is important, as those expressions may
  7913. trigger garbage collection and we cannot have an allocated but
  7914. uninitialized tuple on the heap during a collection.
  7915. Figure~\ref{fig:expose-alloc-output} shows the output of the
  7916. \code{expose-allocation} pass on our running example.
  7917. \begin{figure}[tbp]
  7918. % tests/s2_17.rkt
  7919. \begin{lstlisting}
  7920. (vector-ref
  7921. (vector-ref
  7922. (let ([vecinit7976
  7923. (let ([vecinit7972 42])
  7924. (let ([collectret7974
  7925. (if (< (+ (global-value free_ptr) 16)
  7926. (global-value fromspace_end))
  7927. (void)
  7928. (collect 16)
  7929. )])
  7930. (let ([alloc7971 (allocate 1 (Vector Integer))])
  7931. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  7932. alloc7971)
  7933. )
  7934. )
  7935. )
  7936. ])
  7937. (let ([collectret7978
  7938. (if (< (+ (global-value free_ptr) 16)
  7939. (global-value fromspace_end))
  7940. (void)
  7941. (collect 16)
  7942. )])
  7943. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  7944. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  7945. alloc7975)
  7946. )
  7947. )
  7948. )
  7949. 0)
  7950. 0)
  7951. \end{lstlisting}
  7952. \caption{Output of the \code{expose-allocation} pass, minus
  7953. all of the \code{has-type} forms.}
  7954. \label{fig:expose-alloc-output}
  7955. \end{figure}
  7956. \section{Remove Complex Operands}
  7957. \label{sec:remove-complex-opera-Rvec}
  7958. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  7959. should all be treated as complex operands.
  7960. %% A new case for
  7961. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  7962. %% handled carefully to prevent the \code{Prim} node from being separated
  7963. %% from its enclosing \code{HasType}.
  7964. Figure~\ref{fig:Rvec-anf-syntax}
  7965. shows the grammar for the output language \LangVecANF{} of this
  7966. pass, which is \LangVec{} in administrative normal form.
  7967. \begin{figure}[tp]
  7968. \centering
  7969. \fbox{
  7970. \begin{minipage}{0.96\textwidth}
  7971. \small
  7972. \[
  7973. \begin{array}{rcl}
  7974. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }
  7975. \MID \VOID{} \\
  7976. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7977. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7978. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7979. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7980. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  7981. &\MID& \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  7982. \MID \LP\key{GlobalValue}~\Var\RP\\
  7983. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  7984. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  7985. \end{array}
  7986. \]
  7987. \end{minipage}
  7988. }
  7989. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  7990. \label{fig:Rvec-anf-syntax}
  7991. \end{figure}
  7992. \section{Explicate Control and the \LangCVec{} language}
  7993. \label{sec:explicate-control-r3}
  7994. \begin{figure}[tp]
  7995. \fbox{
  7996. \begin{minipage}{0.96\textwidth}
  7997. \small
  7998. \[
  7999. \begin{array}{lcl}
  8000. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  8001. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  8002. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  8003. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  8004. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  8005. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  8006. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  8007. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  8008. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  8009. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  8010. \MID \LP\key{Collect} \,\itm{int}\RP \\
  8011. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  8012. \MID \GOTO{\itm{label}} } \\
  8013. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8014. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  8015. \end{array}
  8016. \]
  8017. \end{minipage}
  8018. }
  8019. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  8020. (Figure~\ref{fig:c1-syntax}).}
  8021. \label{fig:c2-syntax}
  8022. \end{figure}
  8023. The output of \code{explicate-control} is a program in the
  8024. intermediate language \LangCVec{}, whose abstract syntax is defined in
  8025. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  8026. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  8027. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  8028. \key{vector-set!}, and \key{global-value} expressions and the
  8029. \code{collect} statement. The \code{explicate-control} pass can treat
  8030. these new forms much like the other expression forms that we've
  8031. already encoutered.
  8032. \section{Select Instructions and the \LangXGlobal{} Language}
  8033. \label{sec:select-instructions-gc}
  8034. \index{subject}{instruction selection}
  8035. %% void (rep as zero)
  8036. %% allocate
  8037. %% collect (callq collect)
  8038. %% vector-ref
  8039. %% vector-set!
  8040. %% global (postpone)
  8041. In this pass we generate x86 code for most of the new operations that
  8042. were needed to compile tuples, including \code{Allocate},
  8043. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  8044. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  8045. the later has a different concrete syntax (see
  8046. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  8047. \index{subject}{x86}
  8048. The \code{vector-ref} and \code{vector-set!} forms translate into
  8049. \code{movq} instructions. (The plus one in the offset is to get past
  8050. the tag at the beginning of the tuple representation.)
  8051. \begin{lstlisting}
  8052. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  8053. |$\Longrightarrow$|
  8054. movq |$\itm{vec}'$|, %r11
  8055. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  8056. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  8057. |$\Longrightarrow$|
  8058. movq |$\itm{vec}'$|, %r11
  8059. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  8060. movq $0, |$\itm{lhs'}$|
  8061. \end{lstlisting}
  8062. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  8063. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  8064. register \code{r11} ensures that offset expression
  8065. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  8066. removing \code{r11} from consideration by the register allocating.
  8067. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  8068. \code{rax}. Then the generated code for \code{vector-set!} would be
  8069. \begin{lstlisting}
  8070. movq |$\itm{vec}'$|, %rax
  8071. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  8072. movq $0, |$\itm{lhs}'$|
  8073. \end{lstlisting}
  8074. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  8075. \code{patch-instructions} would insert a move through \code{rax}
  8076. as follows.
  8077. \begin{lstlisting}
  8078. movq |$\itm{vec}'$|, %rax
  8079. movq |$\itm{arg}'$|, %rax
  8080. movq %rax, |$8(n+1)$|(%rax)
  8081. movq $0, |$\itm{lhs}'$|
  8082. \end{lstlisting}
  8083. But the above sequence of instructions does not work because we're
  8084. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  8085. $\itm{arg}'$) at the same time!
  8086. We compile the \code{allocate} form to operations on the
  8087. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  8088. is the next free address in the FromSpace, so we copy it into
  8089. \code{r11} and then move it forward by enough space for the tuple
  8090. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  8091. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  8092. initialize the \itm{tag} and finally copy the address in \code{r11} to
  8093. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  8094. tag is organized. We recommend using the Racket operations
  8095. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  8096. during compilation. The type annotation in the \code{vector} form is
  8097. used to determine the pointer mask region of the tag.
  8098. \begin{lstlisting}
  8099. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  8100. |$\Longrightarrow$|
  8101. movq free_ptr(%rip), %r11
  8102. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  8103. movq $|$\itm{tag}$|, 0(%r11)
  8104. movq %r11, |$\itm{lhs}'$|
  8105. \end{lstlisting}
  8106. The \code{collect} form is compiled to a call to the \code{collect}
  8107. function in the runtime. The arguments to \code{collect} are 1) the
  8108. top of the root stack and 2) the number of bytes that need to be
  8109. allocated. We use another dedicated register, \code{r15}, to
  8110. store the pointer to the top of the root stack. So \code{r15} is not
  8111. available for use by the register allocator.
  8112. \begin{lstlisting}
  8113. (collect |$\itm{bytes}$|)
  8114. |$\Longrightarrow$|
  8115. movq %r15, %rdi
  8116. movq $|\itm{bytes}|, %rsi
  8117. callq collect
  8118. \end{lstlisting}
  8119. \begin{figure}[tp]
  8120. \fbox{
  8121. \begin{minipage}{0.96\textwidth}
  8122. \[
  8123. \begin{array}{lcl}
  8124. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  8125. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  8126. & & \gray{ \key{main:} \; \Instr\ldots }
  8127. \end{array}
  8128. \]
  8129. \end{minipage}
  8130. }
  8131. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  8132. \label{fig:x86-2-concrete}
  8133. \end{figure}
  8134. \begin{figure}[tp]
  8135. \fbox{
  8136. \begin{minipage}{0.96\textwidth}
  8137. \small
  8138. \[
  8139. \begin{array}{lcl}
  8140. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  8141. \MID \BYTEREG{\Reg}} \\
  8142. &\MID& (\key{Global}~\Var) \\
  8143. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  8144. \end{array}
  8145. \]
  8146. \end{minipage}
  8147. }
  8148. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  8149. \label{fig:x86-2}
  8150. \end{figure}
  8151. The concrete and abstract syntax of the \LangXGlobal{} language is
  8152. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  8153. differs from \LangXIf{} just in the addition of the form for global
  8154. variables.
  8155. %
  8156. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  8157. \code{select-instructions} pass on the running example.
  8158. \begin{figure}[tbp]
  8159. \centering
  8160. % tests/s2_17.rkt
  8161. \begin{minipage}[t]{0.5\textwidth}
  8162. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8163. block35:
  8164. movq free_ptr(%rip), alloc9024
  8165. addq $16, free_ptr(%rip)
  8166. movq alloc9024, %r11
  8167. movq $131, 0(%r11)
  8168. movq alloc9024, %r11
  8169. movq vecinit9025, 8(%r11)
  8170. movq $0, initret9026
  8171. movq alloc9024, %r11
  8172. movq 8(%r11), tmp9034
  8173. movq tmp9034, %r11
  8174. movq 8(%r11), %rax
  8175. jmp conclusion
  8176. block36:
  8177. movq $0, collectret9027
  8178. jmp block35
  8179. block38:
  8180. movq free_ptr(%rip), alloc9020
  8181. addq $16, free_ptr(%rip)
  8182. movq alloc9020, %r11
  8183. movq $3, 0(%r11)
  8184. movq alloc9020, %r11
  8185. movq vecinit9021, 8(%r11)
  8186. movq $0, initret9022
  8187. movq alloc9020, vecinit9025
  8188. movq free_ptr(%rip), tmp9031
  8189. movq tmp9031, tmp9032
  8190. addq $16, tmp9032
  8191. movq fromspace_end(%rip), tmp9033
  8192. cmpq tmp9033, tmp9032
  8193. jl block36
  8194. jmp block37
  8195. block37:
  8196. movq %r15, %rdi
  8197. movq $16, %rsi
  8198. callq 'collect
  8199. jmp block35
  8200. block39:
  8201. movq $0, collectret9023
  8202. jmp block38
  8203. \end{lstlisting}
  8204. \end{minipage}
  8205. \begin{minipage}[t]{0.45\textwidth}
  8206. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8207. start:
  8208. movq $42, vecinit9021
  8209. movq free_ptr(%rip), tmp9028
  8210. movq tmp9028, tmp9029
  8211. addq $16, tmp9029
  8212. movq fromspace_end(%rip), tmp9030
  8213. cmpq tmp9030, tmp9029
  8214. jl block39
  8215. jmp block40
  8216. block40:
  8217. movq %r15, %rdi
  8218. movq $16, %rsi
  8219. callq 'collect
  8220. jmp block38
  8221. \end{lstlisting}
  8222. \end{minipage}
  8223. \caption{Output of the \code{select-instructions} pass.}
  8224. \label{fig:select-instr-output-gc}
  8225. \end{figure}
  8226. \clearpage
  8227. \section{Register Allocation}
  8228. \label{sec:reg-alloc-gc}
  8229. \index{subject}{register allocation}
  8230. As discussed earlier in this chapter, the garbage collector needs to
  8231. access all the pointers in the root set, that is, all variables that
  8232. are vectors. It will be the responsibility of the register allocator
  8233. to make sure that:
  8234. \begin{enumerate}
  8235. \item the root stack is used for spilling vector-typed variables, and
  8236. \item if a vector-typed variable is live during a call to the
  8237. collector, it must be spilled to ensure it is visible to the
  8238. collector.
  8239. \end{enumerate}
  8240. The later responsibility can be handled during construction of the
  8241. interference graph, by adding interference edges between the call-live
  8242. vector-typed variables and all the callee-saved registers. (They
  8243. already interfere with the caller-saved registers.) The type
  8244. information for variables is in the \code{Program} form, so we
  8245. recommend adding another parameter to the \code{build-interference}
  8246. function to communicate this alist.
  8247. The spilling of vector-typed variables to the root stack can be
  8248. handled after graph coloring, when choosing how to assign the colors
  8249. (integers) to registers and stack locations. The \code{Program} output
  8250. of this pass changes to also record the number of spills to the root
  8251. stack.
  8252. % build-interference
  8253. %
  8254. % callq
  8255. % extra parameter for var->type assoc. list
  8256. % update 'program' and 'if'
  8257. % allocate-registers
  8258. % allocate spilled vectors to the rootstack
  8259. % don't change color-graph
  8260. \section{Print x86}
  8261. \label{sec:print-x86-gc}
  8262. \index{subject}{prelude}\index{subject}{conclusion}
  8263. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  8264. \code{print\_x86} pass on the running example. In the prelude and
  8265. conclusion of the \code{main} function, we treat the root stack very
  8266. much like the regular stack in that we move the root stack pointer
  8267. (\code{r15}) to make room for the spills to the root stack, except
  8268. that the root stack grows up instead of down. For the running
  8269. example, there was just one spill so we increment \code{r15} by 8
  8270. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  8271. One issue that deserves special care is that there may be a call to
  8272. \code{collect} prior to the initializing assignments for all the
  8273. variables in the root stack. We do not want the garbage collector to
  8274. accidentally think that some uninitialized variable is a pointer that
  8275. needs to be followed. Thus, we zero-out all locations on the root
  8276. stack in the prelude of \code{main}. In
  8277. Figure~\ref{fig:print-x86-output-gc}, the instruction
  8278. %
  8279. \lstinline{movq $0, (%r15)}
  8280. %
  8281. accomplishes this task. The garbage collector tests each root to see
  8282. if it is null prior to dereferencing it.
  8283. \begin{figure}[htbp]
  8284. \begin{minipage}[t]{0.5\textwidth}
  8285. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8286. block35:
  8287. movq free_ptr(%rip), %rcx
  8288. addq $16, free_ptr(%rip)
  8289. movq %rcx, %r11
  8290. movq $131, 0(%r11)
  8291. movq %rcx, %r11
  8292. movq -8(%r15), %rax
  8293. movq %rax, 8(%r11)
  8294. movq $0, %rdx
  8295. movq %rcx, %r11
  8296. movq 8(%r11), %rcx
  8297. movq %rcx, %r11
  8298. movq 8(%r11), %rax
  8299. jmp conclusion
  8300. block36:
  8301. movq $0, %rcx
  8302. jmp block35
  8303. block38:
  8304. movq free_ptr(%rip), %rcx
  8305. addq $16, free_ptr(%rip)
  8306. movq %rcx, %r11
  8307. movq $3, 0(%r11)
  8308. movq %rcx, %r11
  8309. movq %rbx, 8(%r11)
  8310. movq $0, %rdx
  8311. movq %rcx, -8(%r15)
  8312. movq free_ptr(%rip), %rcx
  8313. addq $16, %rcx
  8314. movq fromspace_end(%rip), %rdx
  8315. cmpq %rdx, %rcx
  8316. jl block36
  8317. movq %r15, %rdi
  8318. movq $16, %rsi
  8319. callq collect
  8320. jmp block35
  8321. block39:
  8322. movq $0, %rcx
  8323. jmp block38
  8324. \end{lstlisting}
  8325. \end{minipage}
  8326. \begin{minipage}[t]{0.45\textwidth}
  8327. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8328. start:
  8329. movq $42, %rbx
  8330. movq free_ptr(%rip), %rdx
  8331. addq $16, %rdx
  8332. movq fromspace_end(%rip), %rcx
  8333. cmpq %rcx, %rdx
  8334. jl block39
  8335. movq %r15, %rdi
  8336. movq $16, %rsi
  8337. callq collect
  8338. jmp block38
  8339. .globl main
  8340. main:
  8341. pushq %rbp
  8342. movq %rsp, %rbp
  8343. pushq %r13
  8344. pushq %r12
  8345. pushq %rbx
  8346. pushq %r14
  8347. subq $0, %rsp
  8348. movq $16384, %rdi
  8349. movq $16384, %rsi
  8350. callq initialize
  8351. movq rootstack_begin(%rip), %r15
  8352. movq $0, (%r15)
  8353. addq $8, %r15
  8354. jmp start
  8355. conclusion:
  8356. subq $8, %r15
  8357. addq $0, %rsp
  8358. popq %r14
  8359. popq %rbx
  8360. popq %r12
  8361. popq %r13
  8362. popq %rbp
  8363. retq
  8364. \end{lstlisting}
  8365. \end{minipage}
  8366. \caption{Output of the \code{print\_x86} pass.}
  8367. \label{fig:print-x86-output-gc}
  8368. \end{figure}
  8369. \begin{figure}[p]
  8370. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8371. \node (Rvec) at (0,2) {\large \LangVec{}};
  8372. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  8373. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  8374. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  8375. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  8376. \node (C2-4) at (3,0) {\large \LangCVec{}};
  8377. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  8378. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  8379. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  8380. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  8381. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  8382. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  8383. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  8384. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  8385. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  8386. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  8387. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  8388. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  8389. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  8390. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8391. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8392. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8393. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  8394. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  8395. \end{tikzpicture}
  8396. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  8397. \label{fig:Rvec-passes}
  8398. \end{figure}
  8399. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  8400. for the compilation of \LangVec{}.
  8401. \section{Challenge: Simple Structures}
  8402. \label{sec:simple-structures}
  8403. \index{subject}{struct}
  8404. \index{subject}{structure}
  8405. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  8406. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  8407. Recall that a \code{struct} in Typed Racket is a user-defined data
  8408. type that contains named fields and that is heap allocated, similar to
  8409. a vector. The following is an example of a structure definition, in
  8410. this case the definition of a \code{point} type.
  8411. \begin{lstlisting}
  8412. (struct point ([x : Integer] [y : Integer]) #:mutable)
  8413. \end{lstlisting}
  8414. \begin{figure}[tbp]
  8415. \centering
  8416. \fbox{
  8417. \begin{minipage}{0.96\textwidth}
  8418. \[
  8419. \begin{array}{lcl}
  8420. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  8421. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  8422. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  8423. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  8424. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  8425. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  8426. \MID (\key{and}\;\Exp\;\Exp)
  8427. \MID (\key{or}\;\Exp\;\Exp)
  8428. \MID (\key{not}\;\Exp) } \\
  8429. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  8430. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  8431. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  8432. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  8433. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  8434. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  8435. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  8436. \LangStruct{} &::=& \Def \ldots \; \Exp
  8437. \end{array}
  8438. \]
  8439. \end{minipage}
  8440. }
  8441. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  8442. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  8443. \label{fig:r3s-concrete-syntax}
  8444. \end{figure}
  8445. An instance of a structure is created using function call syntax, with
  8446. the name of the structure in the function position:
  8447. \begin{lstlisting}
  8448. (point 7 12)
  8449. \end{lstlisting}
  8450. Function-call syntax is also used to read the value in a field of a
  8451. structure. The function name is formed by the structure name, a dash,
  8452. and the field name. The following example uses \code{point-x} and
  8453. \code{point-y} to access the \code{x} and \code{y} fields of two point
  8454. instances.
  8455. \begin{center}
  8456. \begin{lstlisting}
  8457. (let ([pt1 (point 7 12)])
  8458. (let ([pt2 (point 4 3)])
  8459. (+ (- (point-x pt1) (point-x pt2))
  8460. (- (point-y pt1) (point-y pt2)))))
  8461. \end{lstlisting}
  8462. \end{center}
  8463. Similarly, to write to a field of a structure, use its set function,
  8464. whose name starts with \code{set-}, followed by the structure name,
  8465. then a dash, then the field name, and concluded with an exclamation
  8466. mark. The following example uses \code{set-point-x!} to change the
  8467. \code{x} field from \code{7} to \code{42}.
  8468. \begin{center}
  8469. \begin{lstlisting}
  8470. (let ([pt (point 7 12)])
  8471. (let ([_ (set-point-x! pt 42)])
  8472. (point-x pt)))
  8473. \end{lstlisting}
  8474. \end{center}
  8475. \begin{exercise}\normalfont
  8476. Extend your compiler with support for simple structures, compiling
  8477. \LangStruct{} to x86 assembly code. Create five new test cases that use
  8478. structures and test your compiler.
  8479. \end{exercise}
  8480. \section{Challenge: Generational Collection}
  8481. The copying collector described in Section~\ref{sec:GC} can incur
  8482. significant runtime overhead because the call to \code{collect} takes
  8483. time proportional to all of the live data. One way to reduce this
  8484. overhead is to reduce how much data is inspected in each call to
  8485. \code{collect}. In particular, researchers have observed that recently
  8486. allocated data is more likely to become garbage then data that has
  8487. survived one or more previous calls to \code{collect}. This insight
  8488. motivated the creation of \emph{generational garbage collectors}
  8489. \index{subject}{generational garbage collector} that
  8490. 1) segregates data according to its age into two or more generations,
  8491. 2) allocates less space for younger generations, so collecting them is
  8492. faster, and more space for the older generations, and 3) performs
  8493. collection on the younger generations more frequently then for older
  8494. generations~\citep{Wilson:1992fk}.
  8495. For this challenge assignment, the goal is to adapt the copying
  8496. collector implemented in \code{runtime.c} to use two generations, one
  8497. for young data and one for old data. Each generation consists of a
  8498. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  8499. \code{collect} function to use the two generations.
  8500. \begin{enumerate}
  8501. \item Copy the young generation's FromSpace to its ToSpace then switch
  8502. the role of the ToSpace and FromSpace
  8503. \item If there is enough space for the requested number of bytes in
  8504. the young FromSpace, then return from \code{collect}.
  8505. \item If there is not enough space in the young FromSpace for the
  8506. requested bytes, then move the data from the young generation to the
  8507. old one with the following steps:
  8508. \begin{enumerate}
  8509. \item If there is enough room in the old FromSpace, copy the young
  8510. FromSpace to the old FromSpace and then return.
  8511. \item If there is not enough room in the old FromSpace, then collect
  8512. the old generation by copying the old FromSpace to the old ToSpace
  8513. and swap the roles of the old FromSpace and ToSpace.
  8514. \item If there is enough room now, copy the young FromSpace to the
  8515. old FromSpace and return. Otherwise, allocate a larger FromSpace
  8516. and ToSpace for the old generation. Copy the young FromSpace and
  8517. the old FromSpace into the larger FromSpace for the old
  8518. generation and then return.
  8519. \end{enumerate}
  8520. \end{enumerate}
  8521. We recommend that you generalize the \code{cheney} function so that it
  8522. can be used for all the copies mentioned above: between the young
  8523. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  8524. between the young FromSpace and old FromSpace. This can be
  8525. accomplished by adding parameters to \code{cheney} that replace its
  8526. use of the global variables \code{fromspace\_begin},
  8527. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  8528. Note that the collection of the young generation does not traverse the
  8529. old generation. This introduces a potential problem: there may be
  8530. young data that is only reachable through pointers in the old
  8531. generation. If these pointers are not taken into account, the
  8532. collector could throw away young data that is live! One solution,
  8533. called \emph{pointer recording}, is to maintain a set of all the
  8534. pointers from the old generation into the new generation and consider
  8535. this set as part of the root set. To maintain this set, the compiler
  8536. must insert extra instructions around every \code{vector-set!}. If the
  8537. vector being modified is in the old generation, and if the value being
  8538. written is a pointer into the new generation, than that pointer must
  8539. be added to the set. Also, if the value being overwritten was a
  8540. pointer into the new generation, then that pointer should be removed
  8541. from the set.
  8542. \begin{exercise}\normalfont
  8543. Adapt the \code{collect} function in \code{runtime.c} to implement
  8544. generational garbage collection, as outlined in this section.
  8545. Update the code generation for \code{vector-set!} to implement
  8546. pointer recording. Make sure that your new compiler and runtime
  8547. passes your test suite.
  8548. \end{exercise}
  8549. % Further Reading
  8550. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8551. \chapter{Functions}
  8552. \label{ch:Rfun}
  8553. \index{subject}{function}
  8554. This chapter studies the compilation of functions similar to those
  8555. found in the C language. This corresponds to a subset of Typed Racket
  8556. in which only top-level function definitions are allowed. This kind of
  8557. function is an important stepping stone to implementing
  8558. lexically-scoped functions, that is, \key{lambda} abstractions, which
  8559. is the topic of Chapter~\ref{ch:Rlam}.
  8560. \section{The \LangFun{} Language}
  8561. The concrete and abstract syntax for function definitions and function
  8562. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  8563. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  8564. \LangFun{} begin with zero or more function definitions. The function
  8565. names from these definitions are in-scope for the entire program,
  8566. including all other function definitions (so the ordering of function
  8567. definitions does not matter). The concrete syntax for function
  8568. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  8569. where the first expression must
  8570. evaluate to a function and the rest are the arguments.
  8571. The abstract syntax for function application is
  8572. $\APPLY{\Exp}{\Exp\ldots}$.
  8573. %% The syntax for function application does not include an explicit
  8574. %% keyword, which is error prone when using \code{match}. To alleviate
  8575. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  8576. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  8577. Functions are first-class in the sense that a function pointer
  8578. \index{subject}{function pointer} is data and can be stored in memory or passed
  8579. as a parameter to another function. Thus, we introduce a function
  8580. type, written
  8581. \begin{lstlisting}
  8582. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  8583. \end{lstlisting}
  8584. for a function whose $n$ parameters have the types $\Type_1$ through
  8585. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  8586. these functions (with respect to Racket functions) is that they are
  8587. not lexically scoped. That is, the only external entities that can be
  8588. referenced from inside a function body are other globally-defined
  8589. functions. The syntax of \LangFun{} prevents functions from being nested
  8590. inside each other.
  8591. \begin{figure}[tp]
  8592. \centering
  8593. \fbox{
  8594. \begin{minipage}{0.96\textwidth}
  8595. \small
  8596. \[
  8597. \begin{array}{lcl}
  8598. \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  8599. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  8600. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  8601. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  8602. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  8603. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  8604. \MID (\key{and}\;\Exp\;\Exp)
  8605. \MID (\key{or}\;\Exp\;\Exp)
  8606. \MID (\key{not}\;\Exp)} \\
  8607. &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  8608. &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  8609. (\key{vector-ref}\;\Exp\;\Int)} \\
  8610. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  8611. \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  8612. &\MID& \LP\Exp \; \Exp \ldots\RP \\
  8613. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  8614. \LangFunM{} &::=& \Def \ldots \; \Exp
  8615. \end{array}
  8616. \]
  8617. \end{minipage}
  8618. }
  8619. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  8620. \label{fig:Rfun-concrete-syntax}
  8621. \end{figure}
  8622. \begin{figure}[tp]
  8623. \centering
  8624. \fbox{
  8625. \begin{minipage}{0.96\textwidth}
  8626. \small
  8627. \[
  8628. \begin{array}{lcl}
  8629. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  8630. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8631. &\MID& \gray{ \BOOL{\itm{bool}}
  8632. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  8633. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  8634. \MID \APPLY{\Exp}{\Exp\ldots}\\
  8635. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  8636. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  8637. \end{array}
  8638. \]
  8639. \end{minipage}
  8640. }
  8641. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  8642. \label{fig:Rfun-syntax}
  8643. \end{figure}
  8644. The program in Figure~\ref{fig:Rfun-function-example} is a
  8645. representative example of defining and using functions in \LangFun{}. We
  8646. define a function \code{map-vec} that applies some other function
  8647. \code{f} to both elements of a vector and returns a new
  8648. vector containing the results. We also define a function \code{add1}.
  8649. The program applies
  8650. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  8651. \code{(vector 1 42)}, from which we return the \code{42}.
  8652. \begin{figure}[tbp]
  8653. \begin{lstlisting}
  8654. (define (map-vec [f : (Integer -> Integer)]
  8655. [v : (Vector Integer Integer)])
  8656. : (Vector Integer Integer)
  8657. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  8658. (define (add1 [x : Integer]) : Integer
  8659. (+ x 1))
  8660. (vector-ref (map-vec add1 (vector 0 41)) 1)
  8661. \end{lstlisting}
  8662. \caption{Example of using functions in \LangFun{}.}
  8663. \label{fig:Rfun-function-example}
  8664. \end{figure}
  8665. The definitional interpreter for \LangFun{} is in
  8666. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  8667. responsible for setting up the mutual recursion between the top-level
  8668. function definitions. We use the classic back-patching \index{subject}{back-patching}
  8669. approach that uses mutable variables and makes two passes over the function
  8670. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  8671. top-level environment using a mutable cons cell for each function
  8672. definition. Note that the \code{lambda} value for each function is
  8673. incomplete; it does not yet include the environment. Once the
  8674. top-level environment is constructed, we then iterate over it and
  8675. update the \code{lambda} values to use the top-level environment.
  8676. \begin{figure}[tp]
  8677. \begin{lstlisting}
  8678. (define interp-Rfun_class
  8679. (class interp-Rvec_class
  8680. (super-new)
  8681. (define/override ((interp-exp env) e)
  8682. (define recur (interp-exp env))
  8683. (match e
  8684. [(Var x) (unbox (dict-ref env x))]
  8685. [(Let x e body)
  8686. (define new-env (dict-set env x (box (recur e))))
  8687. ((interp-exp new-env) body)]
  8688. [(Apply fun args)
  8689. (define fun-val (recur fun))
  8690. (define arg-vals (for/list ([e args]) (recur e)))
  8691. (match fun-val
  8692. [`(function (,xs ...) ,body ,fun-env)
  8693. (define params-args (for/list ([x xs] [arg arg-vals])
  8694. (cons x (box arg))))
  8695. (define new-env (append params-args fun-env))
  8696. ((interp-exp new-env) body)]
  8697. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  8698. [else ((super interp-exp env) e)]
  8699. ))
  8700. (define/public (interp-def d)
  8701. (match d
  8702. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  8703. (cons f (box `(function ,xs ,body ())))]))
  8704. (define/override (interp-program p)
  8705. (match p
  8706. [(ProgramDefsExp info ds body)
  8707. (let ([top-level (for/list ([d ds]) (interp-def d))])
  8708. (for/list ([f (in-dict-values top-level)])
  8709. (set-box! f (match (unbox f)
  8710. [`(function ,xs ,body ())
  8711. `(function ,xs ,body ,top-level)])))
  8712. ((interp-exp top-level) body))]))
  8713. ))
  8714. (define (interp-Rfun p)
  8715. (send (new interp-Rfun_class) interp-program p))
  8716. \end{lstlisting}
  8717. \caption{Interpreter for the \LangFun{} language.}
  8718. \label{fig:interp-Rfun}
  8719. \end{figure}
  8720. %\margincomment{TODO: explain type checker}
  8721. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  8722. \begin{figure}[tp]
  8723. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8724. (define type-check-Rfun_class
  8725. (class type-check-Rvec_class
  8726. (super-new)
  8727. (inherit check-type-equal?)
  8728. (define/public (type-check-apply env e es)
  8729. (define-values (e^ ty) ((type-check-exp env) e))
  8730. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  8731. ((type-check-exp env) e)))
  8732. (match ty
  8733. [`(,ty^* ... -> ,rt)
  8734. (for ([arg-ty ty*] [param-ty ty^*])
  8735. (check-type-equal? arg-ty param-ty (Apply e es)))
  8736. (values e^ e* rt)]))
  8737. (define/override (type-check-exp env)
  8738. (lambda (e)
  8739. (match e
  8740. [(FunRef f)
  8741. (values (FunRef f) (dict-ref env f))]
  8742. [(Apply e es)
  8743. (define-values (e^ es^ rt) (type-check-apply env e es))
  8744. (values (Apply e^ es^) rt)]
  8745. [(Call e es)
  8746. (define-values (e^ es^ rt) (type-check-apply env e es))
  8747. (values (Call e^ es^) rt)]
  8748. [else ((super type-check-exp env) e)])))
  8749. (define/public (type-check-def env)
  8750. (lambda (e)
  8751. (match e
  8752. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  8753. (define new-env (append (map cons xs ps) env))
  8754. (define-values (body^ ty^) ((type-check-exp new-env) body))
  8755. (check-type-equal? ty^ rt body)
  8756. (Def f p:t* rt info body^)])))
  8757. (define/public (fun-def-type d)
  8758. (match d
  8759. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  8760. (define/override (type-check-program e)
  8761. (match e
  8762. [(ProgramDefsExp info ds body)
  8763. (define new-env (for/list ([d ds])
  8764. (cons (Def-name d) (fun-def-type d))))
  8765. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  8766. (define-values (body^ ty) ((type-check-exp new-env) body))
  8767. (check-type-equal? ty 'Integer body)
  8768. (ProgramDefsExp info ds^ body^)]))))
  8769. (define (type-check-Rfun p)
  8770. (send (new type-check-Rfun_class) type-check-program p))
  8771. \end{lstlisting}
  8772. \caption{Type checker for the \LangFun{} language.}
  8773. \label{fig:type-check-Rfun}
  8774. \end{figure}
  8775. \section{Functions in x86}
  8776. \label{sec:fun-x86}
  8777. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  8778. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  8779. %% \margincomment{\tiny Talk about the return address on the
  8780. %% stack and what callq and retq does.\\ --Jeremy }
  8781. The x86 architecture provides a few features to support the
  8782. implementation of functions. We have already seen that x86 provides
  8783. labels so that one can refer to the location of an instruction, as is
  8784. needed for jump instructions. Labels can also be used to mark the
  8785. beginning of the instructions for a function. Going further, we can
  8786. obtain the address of a label by using the \key{leaq} instruction and
  8787. PC-relative addressing. For example, the following puts the
  8788. address of the \code{add1} label into the \code{rbx} register.
  8789. \begin{lstlisting}
  8790. leaq add1(%rip), %rbx
  8791. \end{lstlisting}
  8792. The instruction pointer register \key{rip} (aka. the program counter
  8793. \index{subject}{program counter}) always points to the next instruction to be
  8794. executed. When combined with an label, as in \code{add1(\%rip)}, the
  8795. linker computes the distance $d$ between the address of \code{add1}
  8796. and where the \code{rip} would be at that moment and then changes
  8797. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  8798. the address of \code{add1}.
  8799. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  8800. jump to a function whose location is given by a label. To support
  8801. function calls in this chapter we instead will be jumping to a
  8802. function whose location is given by an address in a register, that is,
  8803. we need to make an \emph{indirect function call}. The x86 syntax for
  8804. this is a \code{callq} instruction but with an asterisk before the
  8805. register name.\index{subject}{indirect function call}
  8806. \begin{lstlisting}
  8807. callq *%rbx
  8808. \end{lstlisting}
  8809. \subsection{Calling Conventions}
  8810. \index{subject}{calling conventions}
  8811. The \code{callq} instruction provides partial support for implementing
  8812. functions: it pushes the return address on the stack and it jumps to
  8813. the target. However, \code{callq} does not handle
  8814. \begin{enumerate}
  8815. \item parameter passing,
  8816. \item pushing frames on the procedure call stack and popping them off,
  8817. or
  8818. \item determining how registers are shared by different functions.
  8819. \end{enumerate}
  8820. Regarding (1) parameter passing, recall that the following six
  8821. registers are used to pass arguments to a function, in this order.
  8822. \begin{lstlisting}
  8823. rdi rsi rdx rcx r8 r9
  8824. \end{lstlisting}
  8825. If there are
  8826. more than six arguments, then the convention is to use space on the
  8827. frame of the caller for the rest of the arguments. However, to ease
  8828. the implementation of efficient tail calls
  8829. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  8830. arguments.
  8831. %
  8832. Also recall that the register \code{rax} is for the return value of
  8833. the function.
  8834. \index{subject}{prelude}\index{subject}{conclusion}
  8835. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  8836. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  8837. the stack grows down, with each function call using a chunk of space
  8838. called a frame. The caller sets the stack pointer, register
  8839. \code{rsp}, to the last data item in its frame. The callee must not
  8840. change anything in the caller's frame, that is, anything that is at or
  8841. above the stack pointer. The callee is free to use locations that are
  8842. below the stack pointer.
  8843. Recall that we are storing variables of vector type on the root stack.
  8844. So the prelude needs to move the root stack pointer \code{r15} up and
  8845. the conclusion needs to move the root stack pointer back down. Also,
  8846. the prelude must initialize to \code{0} this frame's slots in the root
  8847. stack to signal to the garbage collector that those slots do not yet
  8848. contain a pointer to a vector. Otherwise the garbage collector will
  8849. interpret the garbage bits in those slots as memory addresses and try
  8850. to traverse them, causing serious mayhem!
  8851. Regarding (3) the sharing of registers between different functions,
  8852. recall from Section~\ref{sec:calling-conventions} that the registers
  8853. are divided into two groups, the caller-saved registers and the
  8854. callee-saved registers. The caller should assume that all the
  8855. caller-saved registers get overwritten with arbitrary values by the
  8856. callee. That is why we recommend in
  8857. Section~\ref{sec:calling-conventions} that variables that are live
  8858. during a function call should not be assigned to caller-saved
  8859. registers.
  8860. On the flip side, if the callee wants to use a callee-saved register,
  8861. the callee must save the contents of those registers on their stack
  8862. frame and then put them back prior to returning to the caller. That
  8863. is why we recommended in Section~\ref{sec:calling-conventions} that if
  8864. the register allocator assigns a variable to a callee-saved register,
  8865. then the prelude of the \code{main} function must save that register
  8866. to the stack and the conclusion of \code{main} must restore it. This
  8867. recommendation now generalizes to all functions.
  8868. Also recall that the base pointer, register \code{rbp}, is used as a
  8869. point-of-reference within a frame, so that each local variable can be
  8870. accessed at a fixed offset from the base pointer
  8871. (Section~\ref{sec:x86}).
  8872. %
  8873. Figure~\ref{fig:call-frames} shows the general layout of the caller
  8874. and callee frames.
  8875. \begin{figure}[tbp]
  8876. \centering
  8877. \begin{tabular}{r|r|l|l} \hline
  8878. Caller View & Callee View & Contents & Frame \\ \hline
  8879. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  8880. 0(\key{\%rbp}) & & old \key{rbp} \\
  8881. -8(\key{\%rbp}) & & callee-saved $1$ \\
  8882. \ldots & & \ldots \\
  8883. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  8884. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  8885. \ldots & & \ldots \\
  8886. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  8887. %% & & \\
  8888. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  8889. %% & \ldots & \ldots \\
  8890. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  8891. \hline
  8892. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  8893. & 0(\key{\%rbp}) & old \key{rbp} \\
  8894. & -8(\key{\%rbp}) & callee-saved $1$ \\
  8895. & \ldots & \ldots \\
  8896. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  8897. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  8898. & \ldots & \ldots \\
  8899. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  8900. \end{tabular}
  8901. \caption{Memory layout of caller and callee frames.}
  8902. \label{fig:call-frames}
  8903. \end{figure}
  8904. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  8905. %% local variables and for storing the values of callee-saved registers
  8906. %% (we shall refer to all of these collectively as ``locals''), and that
  8907. %% at the beginning of a function we move the stack pointer \code{rsp}
  8908. %% down to make room for them.
  8909. %% We recommend storing the local variables
  8910. %% first and then the callee-saved registers, so that the local variables
  8911. %% can be accessed using \code{rbp} the same as before the addition of
  8912. %% functions.
  8913. %% To make additional room for passing arguments, we shall
  8914. %% move the stack pointer even further down. We count how many stack
  8915. %% arguments are needed for each function call that occurs inside the
  8916. %% body of the function and find their maximum. Adding this number to the
  8917. %% number of locals gives us how much the \code{rsp} should be moved at
  8918. %% the beginning of the function. In preparation for a function call, we
  8919. %% offset from \code{rsp} to set up the stack arguments. We put the first
  8920. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  8921. %% so on.
  8922. %% Upon calling the function, the stack arguments are retrieved by the
  8923. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  8924. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  8925. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  8926. %% the layout of the caller and callee frames. Notice how important it is
  8927. %% that we correctly compute the maximum number of arguments needed for
  8928. %% function calls; if that number is too small then the arguments and
  8929. %% local variables will smash into each other!
  8930. \subsection{Efficient Tail Calls}
  8931. \label{sec:tail-call}
  8932. In general, the amount of stack space used by a program is determined
  8933. by the longest chain of nested function calls. That is, if function
  8934. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  8935. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  8936. $n$ can grow quite large in the case of recursive or mutually
  8937. recursive functions. However, in some cases we can arrange to use only
  8938. constant space, i.e. $O(1)$, instead of $O(n)$.
  8939. If a function call is the last action in a function body, then that
  8940. call is said to be a \emph{tail call}\index{subject}{tail call}.
  8941. For example, in the following
  8942. program, the recursive call to \code{tail-sum} is a tail call.
  8943. \begin{center}
  8944. \begin{lstlisting}
  8945. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8946. (if (eq? n 0)
  8947. r
  8948. (tail-sum (- n 1) (+ n r))))
  8949. (+ (tail-sum 5 0) 27)
  8950. \end{lstlisting}
  8951. \end{center}
  8952. At a tail call, the frame of the caller is no longer needed, so we
  8953. can pop the caller's frame before making the tail call. With this
  8954. approach, a recursive function that only makes tail calls will only
  8955. use $O(1)$ stack space. Functional languages like Racket typically
  8956. rely heavily on recursive functions, so they typically guarantee that
  8957. all tail calls will be optimized in this way.
  8958. \index{subject}{frame}
  8959. However, some care is needed with regards to argument passing in tail
  8960. calls. As mentioned above, for arguments beyond the sixth, the
  8961. convention is to use space in the caller's frame for passing
  8962. arguments. But for a tail call we pop the caller's frame and can no
  8963. longer use it. Another alternative is to use space in the callee's
  8964. frame for passing arguments. However, this option is also problematic
  8965. because the caller and callee's frame overlap in memory. As we begin
  8966. to copy the arguments from their sources in the caller's frame, the
  8967. target locations in the callee's frame might overlap with the sources
  8968. for later arguments! We solve this problem by using the heap instead
  8969. of the stack for passing more than six arguments, as we describe in
  8970. the Section~\ref{sec:limit-functions-r4}.
  8971. As mentioned above, for a tail call we pop the caller's frame prior to
  8972. making the tail call. The instructions for popping a frame are the
  8973. instructions that we usually place in the conclusion of a
  8974. function. Thus, we also need to place such code immediately before
  8975. each tail call. These instructions include restoring the callee-saved
  8976. registers, so it is good that the argument passing registers are all
  8977. caller-saved registers.
  8978. One last note regarding which instruction to use to make the tail
  8979. call. When the callee is finished, it should not return to the current
  8980. function, but it should return to the function that called the current
  8981. one. Thus, the return address that is already on the stack is the
  8982. right one, and we should not use \key{callq} to make the tail call, as
  8983. that would unnecessarily overwrite the return address. Instead we can
  8984. simply use the \key{jmp} instruction. Like the indirect function call,
  8985. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  8986. prefixed with an asterisk. We recommend using \code{rax} to hold the
  8987. jump target because the preceding conclusion overwrites just about
  8988. everything else.
  8989. \begin{lstlisting}
  8990. jmp *%rax
  8991. \end{lstlisting}
  8992. \section{Shrink \LangFun{}}
  8993. \label{sec:shrink-r4}
  8994. The \code{shrink} pass performs a minor modification to ease the
  8995. later passes. This pass introduces an explicit \code{main} function
  8996. and changes the top \code{ProgramDefsExp} form to
  8997. \code{ProgramDefs} as follows.
  8998. \begin{lstlisting}
  8999. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  9000. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  9001. \end{lstlisting}
  9002. where $\itm{mainDef}$ is
  9003. \begin{lstlisting}
  9004. (Def 'main '() 'Integer '() |$\Exp'$|)
  9005. \end{lstlisting}
  9006. \section{Reveal Functions and the \LangFunRef{} language}
  9007. \label{sec:reveal-functions-r4}
  9008. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  9009. respect: it conflates the use of function names and local
  9010. variables. This is a problem because we need to compile the use of a
  9011. function name differently than the use of a local variable; we need to
  9012. use \code{leaq} to convert the function name (a label in x86) to an
  9013. address in a register. Thus, it is a good idea to create a new pass
  9014. that changes function references from just a symbol $f$ to
  9015. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  9016. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  9017. The concrete syntax for a function reference is $\CFUNREF{f}$.
  9018. \begin{figure}[tp]
  9019. \centering
  9020. \fbox{
  9021. \begin{minipage}{0.96\textwidth}
  9022. \[
  9023. \begin{array}{lcl}
  9024. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  9025. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9026. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  9027. \end{array}
  9028. \]
  9029. \end{minipage}
  9030. }
  9031. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  9032. (Figure~\ref{fig:Rfun-syntax}).}
  9033. \label{fig:f1-syntax}
  9034. \end{figure}
  9035. %% Distinguishing between calls in tail position and non-tail position
  9036. %% requires the pass to have some notion of context. We recommend using
  9037. %% two mutually recursive functions, one for processing expressions in
  9038. %% tail position and another for the rest.
  9039. Placing this pass after \code{uniquify} will make sure that there are
  9040. no local variables and functions that share the same name. On the
  9041. other hand, \code{reveal-functions} needs to come before the
  9042. \code{explicate-control} pass because that pass helps us compile
  9043. \code{FunRef} forms into assignment statements.
  9044. \section{Limit Functions}
  9045. \label{sec:limit-functions-r4}
  9046. Recall that we wish to limit the number of function parameters to six
  9047. so that we do not need to use the stack for argument passing, which
  9048. makes it easier to implement efficient tail calls. However, because
  9049. the input language \LangFun{} supports arbitrary numbers of function
  9050. arguments, we have some work to do!
  9051. This pass transforms functions and function calls that involve more
  9052. than six arguments to pass the first five arguments as usual, but it
  9053. packs the rest of the arguments into a vector and passes it as the
  9054. sixth argument.
  9055. Each function definition with too many parameters is transformed as
  9056. follows.
  9057. \begin{lstlisting}
  9058. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  9059. |$\Rightarrow$|
  9060. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  9061. \end{lstlisting}
  9062. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  9063. the occurrences of the later parameters with vector references.
  9064. \begin{lstlisting}
  9065. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  9066. \end{lstlisting}
  9067. For function calls with too many arguments, the \code{limit-functions}
  9068. pass transforms them in the following way.
  9069. \begin{tabular}{lll}
  9070. \begin{minipage}{0.2\textwidth}
  9071. \begin{lstlisting}
  9072. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  9073. \end{lstlisting}
  9074. \end{minipage}
  9075. &
  9076. $\Rightarrow$
  9077. &
  9078. \begin{minipage}{0.4\textwidth}
  9079. \begin{lstlisting}
  9080. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  9081. \end{lstlisting}
  9082. \end{minipage}
  9083. \end{tabular}
  9084. \section{Remove Complex Operands}
  9085. \label{sec:rco-r4}
  9086. The primary decisions to make for this pass is whether to classify
  9087. \code{FunRef} and \code{Apply} as either atomic or complex
  9088. expressions. Recall that a simple expression will eventually end up as
  9089. just an immediate argument of an x86 instruction. Function
  9090. application will be translated to a sequence of instructions, so
  9091. \code{Apply} must be classified as complex expression.
  9092. On the other hand, the arguments of \code{Apply} should be
  9093. atomic expressions.
  9094. %
  9095. Regarding \code{FunRef}, as discussed above, the function label needs
  9096. to be converted to an address using the \code{leaq} instruction. Thus,
  9097. even though \code{FunRef} seems rather simple, it needs to be
  9098. classified as a complex expression so that we generate an assignment
  9099. statement with a left-hand side that can serve as the target of the
  9100. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  9101. output language \LangFunANF{} of this pass.
  9102. \begin{figure}[tp]
  9103. \centering
  9104. \fbox{
  9105. \begin{minipage}{0.96\textwidth}
  9106. \small
  9107. \[
  9108. \begin{array}{rcl}
  9109. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  9110. \MID \VOID{} } \\
  9111. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  9112. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  9113. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9114. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  9115. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  9116. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  9117. \MID \LP\key{GlobalValue}~\Var\RP }\\
  9118. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  9119. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9120. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9121. \end{array}
  9122. \]
  9123. \end{minipage}
  9124. }
  9125. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  9126. \label{fig:Rfun-anf-syntax}
  9127. \end{figure}
  9128. \section{Explicate Control and the \LangCFun{} language}
  9129. \label{sec:explicate-control-r4}
  9130. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  9131. output of \key{explicate-control}. (The concrete syntax is given in
  9132. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  9133. functions for assignment and tail contexts should be updated with
  9134. cases for \code{Apply} and \code{FunRef} and the function for
  9135. predicate context should be updated for \code{Apply} but not
  9136. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  9137. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  9138. tail position \code{Apply} becomes \code{TailCall}. We recommend
  9139. defining a new auxiliary function for processing function definitions.
  9140. This code is similar to the case for \code{Program} in \LangVec{}. The
  9141. top-level \code{explicate-control} function that handles the
  9142. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  9143. all the function definitions.
  9144. \begin{figure}[tp]
  9145. \fbox{
  9146. \begin{minipage}{0.96\textwidth}
  9147. \small
  9148. \[
  9149. \begin{array}{lcl}
  9150. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  9151. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  9152. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  9153. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  9154. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  9155. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  9156. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  9157. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  9158. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  9159. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  9160. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9161. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  9162. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  9163. \MID \GOTO{\itm{label}} } \\
  9164. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9165. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  9166. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9167. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9168. \end{array}
  9169. \]
  9170. \end{minipage}
  9171. }
  9172. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  9173. \label{fig:c3-syntax}
  9174. \end{figure}
  9175. \section{Select Instructions and the \LangXIndCall{} Language}
  9176. \label{sec:select-r4}
  9177. \index{subject}{instruction selection}
  9178. The output of select instructions is a program in the \LangXIndCall{}
  9179. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  9180. \index{subject}{x86}
  9181. \begin{figure}[tp]
  9182. \fbox{
  9183. \begin{minipage}{0.96\textwidth}
  9184. \small
  9185. \[
  9186. \begin{array}{lcl}
  9187. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  9188. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  9189. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  9190. \Instr &::=& \ldots
  9191. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  9192. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  9193. \Block &::= & \Instr\ldots \\
  9194. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  9195. \LangXIndCallM{} &::= & \Def\ldots
  9196. \end{array}
  9197. \]
  9198. \end{minipage}
  9199. }
  9200. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  9201. \label{fig:x86-3-concrete}
  9202. \end{figure}
  9203. \begin{figure}[tp]
  9204. \fbox{
  9205. \begin{minipage}{0.96\textwidth}
  9206. \small
  9207. \[
  9208. \begin{array}{lcl}
  9209. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  9210. \MID \BYTEREG{\Reg} } \\
  9211. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  9212. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  9213. \MID \TAILJMP{\Arg}{\itm{int}}\\
  9214. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  9215. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  9216. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  9217. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9218. \end{array}
  9219. \]
  9220. \end{minipage}
  9221. }
  9222. \caption{The abstract syntax of \LangXIndCall{} (extends
  9223. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  9224. \label{fig:x86-3}
  9225. \end{figure}
  9226. An assignment of a function reference to a variable becomes a
  9227. load-effective-address instruction as follows: \\
  9228. \begin{tabular}{lcl}
  9229. \begin{minipage}{0.35\textwidth}
  9230. \begin{lstlisting}
  9231. |$\itm{lhs}$| = (fun-ref |$f$|);
  9232. \end{lstlisting}
  9233. \end{minipage}
  9234. &
  9235. $\Rightarrow$\qquad\qquad
  9236. &
  9237. \begin{minipage}{0.3\textwidth}
  9238. \begin{lstlisting}
  9239. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  9240. \end{lstlisting}
  9241. \end{minipage}
  9242. \end{tabular} \\
  9243. Regarding function definitions, we need to remove the parameters and
  9244. instead perform parameter passing using the conventions discussed in
  9245. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  9246. registers. We recommend turning the parameters into local variables
  9247. and generating instructions at the beginning of the function to move
  9248. from the argument passing registers to these local variables.
  9249. \begin{lstlisting}
  9250. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  9251. |$\Rightarrow$|
  9252. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  9253. \end{lstlisting}
  9254. The $G'$ control-flow graph is the same as $G$ except that the
  9255. \code{start} block is modified to add the instructions for moving from
  9256. the argument registers to the parameter variables. So the \code{start}
  9257. block of $G$ shown on the left is changed to the code on the right.
  9258. \begin{center}
  9259. \begin{minipage}{0.3\textwidth}
  9260. \begin{lstlisting}
  9261. start:
  9262. |$\itm{instr}_1$|
  9263. |$\vdots$|
  9264. |$\itm{instr}_n$|
  9265. \end{lstlisting}
  9266. \end{minipage}
  9267. $\Rightarrow$
  9268. \begin{minipage}{0.3\textwidth}
  9269. \begin{lstlisting}
  9270. start:
  9271. movq %rdi, |$x_1$|
  9272. movq %rsi, |$x_2$|
  9273. |$\vdots$|
  9274. |$\itm{instr}_1$|
  9275. |$\vdots$|
  9276. |$\itm{instr}_n$|
  9277. \end{lstlisting}
  9278. \end{minipage}
  9279. \end{center}
  9280. By changing the parameters to local variables, we are giving the
  9281. register allocator control over which registers or stack locations to
  9282. use for them. If you implemented the move-biasing challenge
  9283. (Section~\ref{sec:move-biasing}), the register allocator will try to
  9284. assign the parameter variables to the corresponding argument register,
  9285. in which case the \code{patch-instructions} pass will remove the
  9286. \code{movq} instruction. This happens in the example translation in
  9287. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  9288. the \code{add} function.
  9289. %
  9290. Also, note that the register allocator will perform liveness analysis
  9291. on this sequence of move instructions and build the interference
  9292. graph. So, for example, $x_1$ will be marked as interfering with
  9293. \code{rsi} and that will prevent the assignment of $x_1$ to
  9294. \code{rsi}, which is good, because that would overwrite the argument
  9295. that needs to move into $x_2$.
  9296. Next, consider the compilation of function calls. In the mirror image
  9297. of handling the parameters of function definitions, the arguments need
  9298. to be moved to the argument passing registers. The function call
  9299. itself is performed with an indirect function call. The return value
  9300. from the function is stored in \code{rax}, so it needs to be moved
  9301. into the \itm{lhs}.
  9302. \begin{lstlisting}
  9303. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  9304. |$\Rightarrow$|
  9305. movq |$\itm{arg}_1$|, %rdi
  9306. movq |$\itm{arg}_2$|, %rsi
  9307. |$\vdots$|
  9308. callq *|\itm{fun}|
  9309. movq %rax, |\itm{lhs}|
  9310. \end{lstlisting}
  9311. The \code{IndirectCallq} AST node includes an integer for the arity of
  9312. the function, i.e., the number of parameters. That information is
  9313. useful in the \code{uncover-live} pass for determining which
  9314. argument-passing registers are potentially read during the call.
  9315. For tail calls, the parameter passing is the same as non-tail calls:
  9316. generate instructions to move the arguments into to the argument
  9317. passing registers. After that we need to pop the frame from the
  9318. procedure call stack. However, we do not yet know how big the frame
  9319. is; that gets determined during register allocation. So instead of
  9320. generating those instructions here, we invent a new instruction that
  9321. means ``pop the frame and then do an indirect jump'', which we name
  9322. \code{TailJmp}. The abstract syntax for this instruction includes an
  9323. argument that specifies where to jump and an integer that represents
  9324. the arity of the function being called.
  9325. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  9326. using the label \code{start} for the initial block of a program, and
  9327. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  9328. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  9329. can be compiled to an assignment to \code{rax} followed by a jump to
  9330. \code{conclusion}. With the addition of function definitions, we will
  9331. have a starting block and conclusion for each function, but their
  9332. labels need to be unique. We recommend prepending the function's name
  9333. to \code{start} and \code{conclusion}, respectively, to obtain unique
  9334. labels. (Alternatively, one could \code{gensym} labels for the start
  9335. and conclusion and store them in the $\itm{info}$ field of the
  9336. function definition.)
  9337. \section{Register Allocation}
  9338. \label{sec:register-allocation-r4}
  9339. \subsection{Liveness Analysis}
  9340. \label{sec:liveness-analysis-r4}
  9341. \index{subject}{liveness analysis}
  9342. %% The rest of the passes need only minor modifications to handle the new
  9343. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  9344. %% \code{leaq}.
  9345. The \code{IndirectCallq} instruction should be treated like
  9346. \code{Callq} regarding its written locations $W$, in that they should
  9347. include all the caller-saved registers. Recall that the reason for
  9348. that is to force call-live variables to be assigned to callee-saved
  9349. registers or to be spilled to the stack.
  9350. Regarding the set of read locations $R$ the arity field of
  9351. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  9352. argument-passing registers should be considered as read by those
  9353. instructions.
  9354. \subsection{Build Interference Graph}
  9355. \label{sec:build-interference-r4}
  9356. With the addition of function definitions, we compute an interference
  9357. graph for each function (not just one for the whole program).
  9358. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  9359. spill vector-typed variables that are live during a call to the
  9360. \code{collect}. With the addition of functions to our language, we
  9361. need to revisit this issue. Many functions perform allocation and
  9362. therefore have calls to the collector inside of them. Thus, we should
  9363. not only spill a vector-typed variable when it is live during a call
  9364. to \code{collect}, but we should spill the variable if it is live
  9365. during any function call. Thus, in the \code{build-interference} pass,
  9366. we recommend adding interference edges between call-live vector-typed
  9367. variables and the callee-saved registers (in addition to the usual
  9368. addition of edges between call-live variables and the caller-saved
  9369. registers).
  9370. \subsection{Allocate Registers}
  9371. The primary change to the \code{allocate-registers} pass is adding an
  9372. auxiliary function for handling definitions (the \Def{} non-terminal
  9373. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  9374. logic is the same as described in
  9375. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  9376. allocation is performed many times, once for each function definition,
  9377. instead of just once for the whole program.
  9378. \section{Patch Instructions}
  9379. In \code{patch-instructions}, you should deal with the x86
  9380. idiosyncrasy that the destination argument of \code{leaq} must be a
  9381. register. Additionally, you should ensure that the argument of
  9382. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  9383. code generation more convenient, because we trample many registers
  9384. before the tail call (as explained in the next section).
  9385. \section{Print x86}
  9386. For the \code{print\_x86} pass, the cases for \code{FunRef} and
  9387. \code{IndirectCallq} are straightforward: output their concrete
  9388. syntax.
  9389. \begin{lstlisting}
  9390. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  9391. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  9392. \end{lstlisting}
  9393. The \code{TailJmp} node requires a bit work. A straightforward
  9394. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  9395. before the jump we need to pop the current frame. This sequence of
  9396. instructions is the same as the code for the conclusion of a function,
  9397. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  9398. Regarding function definitions, you will need to generate a prelude
  9399. and conclusion for each one. This code is similar to the prelude and
  9400. conclusion that you generated for the \code{main} function in
  9401. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  9402. should carry out the following steps.
  9403. \begin{enumerate}
  9404. \item Start with \code{.global} and \code{.align} directives followed
  9405. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  9406. example.)
  9407. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  9408. pointer.
  9409. \item Push to the stack all of the callee-saved registers that were
  9410. used for register allocation.
  9411. \item Move the stack pointer \code{rsp} down by the size of the stack
  9412. frame for this function, which depends on the number of regular
  9413. spills. (Aligned to 16 bytes.)
  9414. \item Move the root stack pointer \code{r15} up by the size of the
  9415. root-stack frame for this function, which depends on the number of
  9416. spilled vectors. \label{root-stack-init}
  9417. \item Initialize to zero all of the entries in the root-stack frame.
  9418. \item Jump to the start block.
  9419. \end{enumerate}
  9420. The prelude of the \code{main} function has one additional task: call
  9421. the \code{initialize} function to set up the garbage collector and
  9422. move the value of the global \code{rootstack\_begin} in
  9423. \code{r15}. This should happen before step \ref{root-stack-init}
  9424. above, which depends on \code{r15}.
  9425. The conclusion of every function should do the following.
  9426. \begin{enumerate}
  9427. \item Move the stack pointer back up by the size of the stack frame
  9428. for this function.
  9429. \item Restore the callee-saved registers by popping them from the
  9430. stack.
  9431. \item Move the root stack pointer back down by the size of the
  9432. root-stack frame for this function.
  9433. \item Restore \code{rbp} by popping it from the stack.
  9434. \item Return to the caller with the \code{retq} instruction.
  9435. \end{enumerate}
  9436. \begin{exercise}\normalfont
  9437. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  9438. Create 5 new programs that use functions, including examples that pass
  9439. functions and return functions from other functions, recursive
  9440. functions, functions that create vectors, and functions that make tail
  9441. calls. Test your compiler on these new programs and all of your
  9442. previously created test programs.
  9443. \end{exercise}
  9444. \begin{figure}[tbp]
  9445. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9446. \node (Rfun) at (0,2) {\large \LangFun{}};
  9447. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  9448. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  9449. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  9450. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  9451. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  9452. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  9453. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  9454. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9455. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9456. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9457. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9458. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9459. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9460. \path[->,bend left=15] (Rfun) edge [above] node
  9461. {\ttfamily\footnotesize shrink} (Rfun-1);
  9462. \path[->,bend left=15] (Rfun-1) edge [above] node
  9463. {\ttfamily\footnotesize uniquify} (Rfun-2);
  9464. \path[->,bend left=15] (Rfun-2) edge [right] node
  9465. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  9466. \path[->,bend left=15] (F1-1) edge [below] node
  9467. {\ttfamily\footnotesize limit-functions} (F1-2);
  9468. \path[->,bend right=15] (F1-2) edge [above] node
  9469. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  9470. \path[->,bend right=15] (F1-3) edge [above] node
  9471. {\ttfamily\footnotesize remove-complex.} (F1-4);
  9472. \path[->,bend left=15] (F1-4) edge [right] node
  9473. {\ttfamily\footnotesize explicate-control} (C3-2);
  9474. \path[->,bend right=15] (C3-2) edge [left] node
  9475. {\ttfamily\footnotesize select-instr.} (x86-2);
  9476. \path[->,bend left=15] (x86-2) edge [left] node
  9477. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9478. \path[->,bend right=15] (x86-2-1) edge [below] node
  9479. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9480. \path[->,bend right=15] (x86-2-2) edge [left] node
  9481. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9482. \path[->,bend left=15] (x86-3) edge [above] node
  9483. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9484. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  9485. \end{tikzpicture}
  9486. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  9487. \label{fig:Rfun-passes}
  9488. \end{figure}
  9489. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  9490. compiling \LangFun{} to x86.
  9491. \section{An Example Translation}
  9492. \label{sec:functions-example}
  9493. Figure~\ref{fig:add-fun} shows an example translation of a simple
  9494. function in \LangFun{} to x86. The figure also includes the results of the
  9495. \code{explicate-control} and \code{select-instructions} passes.
  9496. \begin{figure}[htbp]
  9497. \begin{tabular}{ll}
  9498. \begin{minipage}{0.5\textwidth}
  9499. % s3_2.rkt
  9500. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9501. (define (add [x : Integer] [y : Integer])
  9502. : Integer
  9503. (+ x y))
  9504. (add 40 2)
  9505. \end{lstlisting}
  9506. $\Downarrow$
  9507. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9508. (define (add86 [x87 : Integer]
  9509. [y88 : Integer]) : Integer
  9510. add86start:
  9511. return (+ x87 y88);
  9512. )
  9513. (define (main) : Integer ()
  9514. mainstart:
  9515. tmp89 = (fun-ref add86);
  9516. (tail-call tmp89 40 2)
  9517. )
  9518. \end{lstlisting}
  9519. \end{minipage}
  9520. &
  9521. $\Rightarrow$
  9522. \begin{minipage}{0.5\textwidth}
  9523. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9524. (define (add86) : Integer
  9525. add86start:
  9526. movq %rdi, x87
  9527. movq %rsi, y88
  9528. movq x87, %rax
  9529. addq y88, %rax
  9530. jmp add11389conclusion
  9531. )
  9532. (define (main) : Integer
  9533. mainstart:
  9534. leaq (fun-ref add86), tmp89
  9535. movq $40, %rdi
  9536. movq $2, %rsi
  9537. tail-jmp tmp89
  9538. )
  9539. \end{lstlisting}
  9540. $\Downarrow$
  9541. \end{minipage}
  9542. \end{tabular}
  9543. \begin{tabular}{ll}
  9544. \begin{minipage}{0.3\textwidth}
  9545. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9546. .globl add86
  9547. .align 16
  9548. add86:
  9549. pushq %rbp
  9550. movq %rsp, %rbp
  9551. jmp add86start
  9552. add86start:
  9553. movq %rdi, %rax
  9554. addq %rsi, %rax
  9555. jmp add86conclusion
  9556. add86conclusion:
  9557. popq %rbp
  9558. retq
  9559. \end{lstlisting}
  9560. \end{minipage}
  9561. &
  9562. \begin{minipage}{0.5\textwidth}
  9563. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9564. .globl main
  9565. .align 16
  9566. main:
  9567. pushq %rbp
  9568. movq %rsp, %rbp
  9569. movq $16384, %rdi
  9570. movq $16384, %rsi
  9571. callq initialize
  9572. movq rootstack_begin(%rip), %r15
  9573. jmp mainstart
  9574. mainstart:
  9575. leaq add86(%rip), %rcx
  9576. movq $40, %rdi
  9577. movq $2, %rsi
  9578. movq %rcx, %rax
  9579. popq %rbp
  9580. jmp *%rax
  9581. mainconclusion:
  9582. popq %rbp
  9583. retq
  9584. \end{lstlisting}
  9585. \end{minipage}
  9586. \end{tabular}
  9587. \caption{Example compilation of a simple function to x86.}
  9588. \label{fig:add-fun}
  9589. \end{figure}
  9590. % Challenge idea: inlining! (simple version)
  9591. % Further Reading
  9592. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9593. \chapter{Lexically Scoped Functions}
  9594. \label{ch:Rlam}
  9595. \index{subject}{lambda}
  9596. \index{subject}{lexical scoping}
  9597. This chapter studies lexically scoped functions as they appear in
  9598. functional languages such as Racket. By lexical scoping we mean that a
  9599. function's body may refer to variables whose binding site is outside
  9600. of the function, in an enclosing scope.
  9601. %
  9602. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  9603. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  9604. \key{lambda} form. The body of the \key{lambda}, refers to three
  9605. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  9606. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  9607. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  9608. parameter of function \code{f}. The \key{lambda} is returned from the
  9609. function \code{f}. The main expression of the program includes two
  9610. calls to \code{f} with different arguments for \code{x}, first
  9611. \code{5} then \code{3}. The functions returned from \code{f} are bound
  9612. to variables \code{g} and \code{h}. Even though these two functions
  9613. were created by the same \code{lambda}, they are really different
  9614. functions because they use different values for \code{x}. Applying
  9615. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  9616. \code{15} produces \code{22}. The result of this program is \code{42}.
  9617. \begin{figure}[btp]
  9618. % s4_6.rkt
  9619. \begin{lstlisting}
  9620. (define (f [x : Integer]) : (Integer -> Integer)
  9621. (let ([y 4])
  9622. (lambda: ([z : Integer]) : Integer
  9623. (+ x (+ y z)))))
  9624. (let ([g (f 5)])
  9625. (let ([h (f 3)])
  9626. (+ (g 11) (h 15))))
  9627. \end{lstlisting}
  9628. \caption{Example of a lexically scoped function.}
  9629. \label{fig:lexical-scoping}
  9630. \end{figure}
  9631. The approach that we take for implementing lexically scoped
  9632. functions is to compile them into top-level function definitions,
  9633. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  9634. provide special treatment for variable occurrences such as \code{x}
  9635. and \code{y} in the body of the \code{lambda} of
  9636. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  9637. refer to variables defined outside of it. To identify such variable
  9638. occurrences, we review the standard notion of free variable.
  9639. \begin{definition}
  9640. A variable is \emph{free in expression} $e$ if the variable occurs
  9641. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  9642. variable}
  9643. \end{definition}
  9644. For example, in the expression \code{(+ x (+ y z))} the variables
  9645. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  9646. only \code{x} and \code{y} are free in the following expression
  9647. because \code{z} is bound by the \code{lambda}.
  9648. \begin{lstlisting}
  9649. (lambda: ([z : Integer]) : Integer
  9650. (+ x (+ y z)))
  9651. \end{lstlisting}
  9652. So the free variables of a \code{lambda} are the ones that will need
  9653. special treatment. We need to arrange for some way to transport, at
  9654. runtime, the values of those variables from the point where the
  9655. \code{lambda} was created to the point where the \code{lambda} is
  9656. applied. An efficient solution to the problem, due to
  9657. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  9658. free variables together with the function pointer for the lambda's
  9659. code, an arrangement called a \emph{flat closure} (which we shorten to
  9660. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  9661. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  9662. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  9663. pointers. The function pointer resides at index $0$ and the
  9664. values for the free variables will fill in the rest of the vector.
  9665. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  9666. how closures work. It's a three-step dance. The program first calls
  9667. function \code{f}, which creates a closure for the \code{lambda}. The
  9668. closure is a vector whose first element is a pointer to the top-level
  9669. function that we will generate for the \code{lambda}, the second
  9670. element is the value of \code{x}, which is \code{5}, and the third
  9671. element is \code{4}, the value of \code{y}. The closure does not
  9672. contain an element for \code{z} because \code{z} is not a free
  9673. variable of the \code{lambda}. Creating the closure is step 1 of the
  9674. dance. The closure is returned from \code{f} and bound to \code{g}, as
  9675. shown in Figure~\ref{fig:closures}.
  9676. %
  9677. The second call to \code{f} creates another closure, this time with
  9678. \code{3} in the second slot (for \code{x}). This closure is also
  9679. returned from \code{f} but bound to \code{h}, which is also shown in
  9680. Figure~\ref{fig:closures}.
  9681. \begin{figure}[tbp]
  9682. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  9683. \caption{Example closure representation for the \key{lambda}'s
  9684. in Figure~\ref{fig:lexical-scoping}.}
  9685. \label{fig:closures}
  9686. \end{figure}
  9687. Continuing with the example, consider the application of \code{g} to
  9688. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  9689. obtain the function pointer in the first element of the closure and
  9690. call it, passing in the closure itself and then the regular arguments,
  9691. in this case \code{11}. This technique for applying a closure is step
  9692. 2 of the dance.
  9693. %
  9694. But doesn't this \code{lambda} only take 1 argument, for parameter
  9695. \code{z}? The third and final step of the dance is generating a
  9696. top-level function for a \code{lambda}. We add an additional
  9697. parameter for the closure and we insert a \code{let} at the beginning
  9698. of the function for each free variable, to bind those variables to the
  9699. appropriate elements from the closure parameter.
  9700. %
  9701. This three-step dance is known as \emph{closure conversion}. We
  9702. discuss the details of closure conversion in
  9703. Section~\ref{sec:closure-conversion} and the code generated from the
  9704. example in Section~\ref{sec:example-lambda}. But first we define the
  9705. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  9706. \section{The \LangLam{} Language}
  9707. \label{sec:r5}
  9708. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  9709. functions and lexical scoping, is defined in
  9710. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  9711. the \key{lambda} form to the grammar for \LangFun{}, which already has
  9712. syntax for function application.
  9713. \begin{figure}[tp]
  9714. \centering
  9715. \fbox{
  9716. \begin{minipage}{0.96\textwidth}
  9717. \small
  9718. \[
  9719. \begin{array}{lcl}
  9720. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  9721. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  9722. \MID (\Type\ldots \; \key{->}\; \Type)} \\
  9723. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  9724. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  9725. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  9726. &\MID& \gray{\key{\#t} \MID \key{\#f}
  9727. \MID (\key{and}\;\Exp\;\Exp)
  9728. \MID (\key{or}\;\Exp\;\Exp)
  9729. \MID (\key{not}\;\Exp) } \\
  9730. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  9731. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  9732. (\key{vector-ref}\;\Exp\;\Int)} \\
  9733. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  9734. \MID (\Exp \; \Exp\ldots) } \\
  9735. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  9736. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  9737. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9738. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  9739. \end{array}
  9740. \]
  9741. \end{minipage}
  9742. }
  9743. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  9744. with \key{lambda}.}
  9745. \label{fig:Rlam-concrete-syntax}
  9746. \end{figure}
  9747. \begin{figure}[tp]
  9748. \centering
  9749. \fbox{
  9750. \begin{minipage}{0.96\textwidth}
  9751. \small
  9752. \[
  9753. \begin{array}{lcl}
  9754. \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  9755. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  9756. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9757. &\MID& \gray{ \BOOL{\itm{bool}}
  9758. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  9759. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  9760. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  9761. &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  9762. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9763. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9764. \end{array}
  9765. \]
  9766. \end{minipage}
  9767. }
  9768. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  9769. \label{fig:Rlam-syntax}
  9770. \end{figure}
  9771. \index{subject}{interpreter}
  9772. \label{sec:interp-Rlambda}
  9773. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  9774. \LangLam{}. The case for \key{lambda} saves the current environment
  9775. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  9776. the environment from the \key{lambda}, the \code{lam-env}, when
  9777. interpreting the body of the \key{lambda}. The \code{lam-env}
  9778. environment is extended with the mapping of parameters to argument
  9779. values.
  9780. \begin{figure}[tbp]
  9781. \begin{lstlisting}
  9782. (define interp-Rlambda_class
  9783. (class interp-Rfun_class
  9784. (super-new)
  9785. (define/override (interp-op op)
  9786. (match op
  9787. ['procedure-arity
  9788. (lambda (v)
  9789. (match v
  9790. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  9791. [else (error 'interp-op "expected a function, not ~a" v)]))]
  9792. [else (super interp-op op)]))
  9793. (define/override ((interp-exp env) e)
  9794. (define recur (interp-exp env))
  9795. (match e
  9796. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  9797. `(function ,xs ,body ,env)]
  9798. [else ((super interp-exp env) e)]))
  9799. ))
  9800. (define (interp-Rlambda p)
  9801. (send (new interp-Rlambda_class) interp-program p))
  9802. \end{lstlisting}
  9803. \caption{Interpreter for \LangLam{}.}
  9804. \label{fig:interp-Rlambda}
  9805. \end{figure}
  9806. \label{sec:type-check-r5}
  9807. \index{subject}{type checking}
  9808. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  9809. \key{lambda} form. The body of the \key{lambda} is checked in an
  9810. environment that includes the current environment (because it is
  9811. lexically scoped) and also includes the \key{lambda}'s parameters. We
  9812. require the body's type to match the declared return type.
  9813. \begin{figure}[tbp]
  9814. \begin{lstlisting}
  9815. (define (type-check-Rlambda env)
  9816. (lambda (e)
  9817. (match e
  9818. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  9819. (define-values (new-body bodyT)
  9820. ((type-check-exp (append (map cons xs Ts) env)) body))
  9821. (define ty `(,@Ts -> ,rT))
  9822. (cond
  9823. [(equal? rT bodyT)
  9824. (values (HasType (Lambda params rT new-body) ty) ty)]
  9825. [else
  9826. (error "mismatch in return type" bodyT rT)])]
  9827. ...
  9828. )))
  9829. \end{lstlisting}
  9830. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  9831. \label{fig:type-check-Rlambda}
  9832. \end{figure}
  9833. \section{Reveal Functions and the $F_2$ language}
  9834. \label{sec:reveal-functions-r5}
  9835. To support the \code{procedure-arity} operator we need to communicate
  9836. the arity of a function to the point of closure creation. We can
  9837. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  9838. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  9839. output of this pass is the language $F_2$, whose syntax is defined in
  9840. Figure~\ref{fig:f2-syntax}.
  9841. \begin{figure}[tp]
  9842. \centering
  9843. \fbox{
  9844. \begin{minipage}{0.96\textwidth}
  9845. \[
  9846. \begin{array}{lcl}
  9847. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  9848. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9849. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  9850. \end{array}
  9851. \]
  9852. \end{minipage}
  9853. }
  9854. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  9855. (Figure~\ref{fig:Rlam-syntax}).}
  9856. \label{fig:f2-syntax}
  9857. \end{figure}
  9858. \section{Closure Conversion}
  9859. \label{sec:closure-conversion}
  9860. \index{subject}{closure conversion}
  9861. The compiling of lexically-scoped functions into top-level function
  9862. definitions is accomplished in the pass \code{convert-to-closures}
  9863. that comes after \code{reveal-functions} and before
  9864. \code{limit-functions}.
  9865. As usual, we implement the pass as a recursive function over the
  9866. AST. All of the action is in the cases for \key{Lambda} and
  9867. \key{Apply}. We transform a \key{Lambda} expression into an expression
  9868. that creates a closure, that is, a vector whose first element is a
  9869. function pointer and the rest of the elements are the free variables
  9870. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  9871. using \code{vector} so that we can distinguish closures from vectors
  9872. in Section~\ref{sec:optimize-closures} and to record the arity. In
  9873. the generated code below, the \itm{name} is a unique symbol generated
  9874. to identify the function and the \itm{arity} is the number of
  9875. parameters (the length of \itm{ps}).
  9876. \begin{lstlisting}
  9877. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  9878. |$\Rightarrow$|
  9879. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  9880. \end{lstlisting}
  9881. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  9882. create a top-level function definition for each \key{Lambda}, as
  9883. shown below.\\
  9884. \begin{minipage}{0.8\textwidth}
  9885. \begin{lstlisting}
  9886. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  9887. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  9888. ...
  9889. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  9890. |\itm{body'}|)...))
  9891. \end{lstlisting}
  9892. \end{minipage}\\
  9893. The \code{clos} parameter refers to the closure. Translate the type
  9894. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  9895. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  9896. $\itm{fvts}$ are the types of the free variables in the lambda and the
  9897. underscore \code{\_} is a dummy type that we use because it is rather
  9898. difficult to give a type to the function in the closure's
  9899. type.\footnote{To give an accurate type to a closure, we would need to
  9900. add existential types to the type checker~\citep{Minamide:1996ys}.}
  9901. The dummy type is considered to be equal to any other type during type
  9902. checking. The sequence of \key{Let} forms bind the free variables to
  9903. their values obtained from the closure.
  9904. Closure conversion turns functions into vectors, so the type
  9905. annotations in the program must also be translated. We recommend
  9906. defining a auxiliary recursive function for this purpose. Function
  9907. types should be translated as follows.
  9908. \begin{lstlisting}
  9909. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  9910. |$\Rightarrow$|
  9911. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  9912. \end{lstlisting}
  9913. The above type says that the first thing in the vector is a function
  9914. pointer. The first parameter of the function pointer is a vector (a
  9915. closure) and the rest of the parameters are the ones from the original
  9916. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  9917. the closure omits the types of the free variables because 1) those
  9918. types are not available in this context and 2) we do not need them in
  9919. the code that is generated for function application.
  9920. We transform function application into code that retrieves the
  9921. function pointer from the closure and then calls the function, passing
  9922. in the closure as the first argument. We bind $e'$ to a temporary
  9923. variable to avoid code duplication.
  9924. \begin{lstlisting}
  9925. (Apply |$e$| |\itm{es}|)
  9926. |$\Rightarrow$|
  9927. (Let |\itm{tmp}| |$e'$|
  9928. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  9929. \end{lstlisting}
  9930. There is also the question of what to do with references top-level
  9931. function definitions. To maintain a uniform translation of function
  9932. application, we turn function references into closures.
  9933. \begin{tabular}{lll}
  9934. \begin{minipage}{0.3\textwidth}
  9935. \begin{lstlisting}
  9936. (FunRefArity |$f$| |$n$|)
  9937. \end{lstlisting}
  9938. \end{minipage}
  9939. &
  9940. $\Rightarrow$
  9941. &
  9942. \begin{minipage}{0.5\textwidth}
  9943. \begin{lstlisting}
  9944. (Closure |$n$| (FunRef |$f$|) '())
  9945. \end{lstlisting}
  9946. \end{minipage}
  9947. \end{tabular} \\
  9948. %
  9949. The top-level function definitions need to be updated as well to take
  9950. an extra closure parameter.
  9951. \section{An Example Translation}
  9952. \label{sec:example-lambda}
  9953. Figure~\ref{fig:lexical-functions-example} shows the result of
  9954. \code{reveal-functions} and \code{convert-to-closures} for the example
  9955. program demonstrating lexical scoping that we discussed at the
  9956. beginning of this chapter.
  9957. \begin{figure}[tbp]
  9958. \begin{minipage}{0.8\textwidth}
  9959. % tests/lambda_test_6.rkt
  9960. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9961. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  9962. (let ([y8 4])
  9963. (lambda: ([z9 : Integer]) : Integer
  9964. (+ x7 (+ y8 z9)))))
  9965. (define (main) : Integer
  9966. (let ([g0 ((fun-ref-arity f6 1) 5)])
  9967. (let ([h1 ((fun-ref-arity f6 1) 3)])
  9968. (+ (g0 11) (h1 15)))))
  9969. \end{lstlisting}
  9970. $\Rightarrow$
  9971. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9972. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  9973. (let ([y8 4])
  9974. (closure 1 (list (fun-ref lambda2) x7 y8))))
  9975. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  9976. (let ([x7 (vector-ref fvs3 1)])
  9977. (let ([y8 (vector-ref fvs3 2)])
  9978. (+ x7 (+ y8 z9)))))
  9979. (define (main) : Integer
  9980. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  9981. ((vector-ref clos5 0) clos5 5))])
  9982. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  9983. ((vector-ref clos6 0) clos6 3))])
  9984. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  9985. \end{lstlisting}
  9986. \end{minipage}
  9987. \caption{Example of closure conversion.}
  9988. \label{fig:lexical-functions-example}
  9989. \end{figure}
  9990. \begin{exercise}\normalfont
  9991. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  9992. Create 5 new programs that use \key{lambda} functions and make use of
  9993. lexical scoping. Test your compiler on these new programs and all of
  9994. your previously created test programs.
  9995. \end{exercise}
  9996. \section{Expose Allocation}
  9997. \label{sec:expose-allocation-r5}
  9998. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  9999. that allocates and initializes a vector, similar to the translation of
  10000. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  10001. The only difference is replacing the use of
  10002. \ALLOC{\itm{len}}{\itm{type}} with
  10003. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  10004. \section{Explicate Control and \LangCLam{}}
  10005. \label{sec:explicate-r5}
  10006. The output language of \code{explicate-control} is \LangCLam{} whose
  10007. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  10008. difference with respect to \LangCFun{} is the addition of the
  10009. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  10010. of \code{AllocateClosure} in the \code{explicate-control} pass is
  10011. similar to the handling of other expressions such as primitive
  10012. operators.
  10013. \begin{figure}[tp]
  10014. \fbox{
  10015. \begin{minipage}{0.96\textwidth}
  10016. \small
  10017. \[
  10018. \begin{array}{lcl}
  10019. \Exp &::= & \ldots
  10020. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  10021. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10022. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  10023. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10024. \MID \GOTO{\itm{label}} } \\
  10025. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10026. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  10027. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  10028. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  10029. \end{array}
  10030. \]
  10031. \end{minipage}
  10032. }
  10033. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  10034. \label{fig:c4-syntax}
  10035. \end{figure}
  10036. \section{Select Instructions}
  10037. \label{sec:select-instructions-Rlambda}
  10038. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  10039. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  10040. (Section~\ref{sec:select-instructions-gc}). The only difference is
  10041. that you should place the \itm{arity} in the tag that is stored at
  10042. position $0$ of the vector. Recall that in
  10043. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  10044. was not used. We store the arity in the $5$ bits starting at position
  10045. $58$.
  10046. Compile the \code{procedure-arity} operator into a sequence of
  10047. instructions that access the tag from position $0$ of the vector and
  10048. extract the $5$-bits starting at position $58$ from the tag.
  10049. \begin{figure}[p]
  10050. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10051. \node (Rfun) at (0,2) {\large \LangFun{}};
  10052. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  10053. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  10054. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  10055. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  10056. \node (F1-3) at (6,0) {\large $F_1$};
  10057. \node (F1-4) at (3,0) {\large $F_1$};
  10058. \node (F1-5) at (0,0) {\large $F_1$};
  10059. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  10060. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10061. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10062. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10063. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10064. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10065. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10066. \path[->,bend left=15] (Rfun) edge [above] node
  10067. {\ttfamily\footnotesize shrink} (Rfun-2);
  10068. \path[->,bend left=15] (Rfun-2) edge [above] node
  10069. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10070. \path[->,bend left=15] (Rfun-3) edge [right] node
  10071. {\ttfamily\footnotesize reveal-functions} (F1-1);
  10072. \path[->,bend left=15] (F1-1) edge [below] node
  10073. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10074. \path[->,bend right=15] (F1-2) edge [above] node
  10075. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10076. \path[->,bend right=15] (F1-3) edge [above] node
  10077. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10078. \path[->,bend right=15] (F1-4) edge [above] node
  10079. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10080. \path[->,bend right=15] (F1-5) edge [right] node
  10081. {\ttfamily\footnotesize explicate-control} (C3-2);
  10082. \path[->,bend left=15] (C3-2) edge [left] node
  10083. {\ttfamily\footnotesize select-instr.} (x86-2);
  10084. \path[->,bend right=15] (x86-2) edge [left] node
  10085. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10086. \path[->,bend right=15] (x86-2-1) edge [below] node
  10087. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10088. \path[->,bend right=15] (x86-2-2) edge [left] node
  10089. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10090. \path[->,bend left=15] (x86-3) edge [above] node
  10091. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10092. \path[->,bend left=15] (x86-4) edge [right] node
  10093. {\ttfamily\footnotesize print-x86} (x86-5);
  10094. \end{tikzpicture}
  10095. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  10096. functions.}
  10097. \label{fig:Rlambda-passes}
  10098. \end{figure}
  10099. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  10100. for the compilation of \LangLam{}.
  10101. \clearpage
  10102. \section{Challenge: Optimize Closures}
  10103. \label{sec:optimize-closures}
  10104. In this chapter we compiled lexically-scoped functions into a
  10105. relatively efficient representation: flat closures. However, even this
  10106. representation comes with some overhead. For example, consider the
  10107. following program with a function \code{tail-sum} that does not have
  10108. any free variables and where all the uses of \code{tail-sum} are in
  10109. applications where we know that only \code{tail-sum} is being applied
  10110. (and not any other functions).
  10111. \begin{center}
  10112. \begin{minipage}{0.95\textwidth}
  10113. \begin{lstlisting}
  10114. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  10115. (if (eq? n 0)
  10116. r
  10117. (tail-sum (- n 1) (+ n r))))
  10118. (+ (tail-sum 5 0) 27)
  10119. \end{lstlisting}
  10120. \end{minipage}
  10121. \end{center}
  10122. As described in this chapter, we uniformly apply closure conversion to
  10123. all functions, obtaining the following output for this program.
  10124. \begin{center}
  10125. \begin{minipage}{0.95\textwidth}
  10126. \begin{lstlisting}
  10127. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  10128. (if (eq? n2 0)
  10129. r3
  10130. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  10131. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  10132. (define (main) : Integer
  10133. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  10134. ((vector-ref clos6 0) clos6 5 0)) 27))
  10135. \end{lstlisting}
  10136. \end{minipage}
  10137. \end{center}
  10138. In the previous Chapter, there would be no allocation in the program
  10139. and the calls to \code{tail-sum} would be direct calls. In contrast,
  10140. the above program allocates memory for each \code{closure} and the
  10141. calls to \code{tail-sum} are indirect. These two differences incur
  10142. considerable overhead in a program such as this one, where the
  10143. allocations and indirect calls occur inside a tight loop.
  10144. One might think that this problem is trivial to solve: can't we just
  10145. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  10146. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  10147. e'_n$)} instead of treating it like a call to a closure? We would
  10148. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  10149. %
  10150. However, this problem is not so trivial because a global function may
  10151. ``escape'' and become involved in applications that also involve
  10152. closures. Consider the following example in which the application
  10153. \code{(f 41)} needs to be compiled into a closure application, because
  10154. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  10155. function might also get bound to \code{f}.
  10156. \begin{lstlisting}
  10157. (define (add1 [x : Integer]) : Integer
  10158. (+ x 1))
  10159. (let ([y (read)])
  10160. (let ([f (if (eq? (read) 0)
  10161. add1
  10162. (lambda: ([x : Integer]) : Integer (- x y)))])
  10163. (f 41)))
  10164. \end{lstlisting}
  10165. If a global function name is used in any way other than as the
  10166. operator in a direct call, then we say that the function
  10167. \emph{escapes}. If a global function does not escape, then we do not
  10168. need to perform closure conversion on the function.
  10169. \begin{exercise}\normalfont
  10170. Implement an auxiliary function for detecting which global
  10171. functions escape. Using that function, implement an improved version
  10172. of closure conversion that does not apply closure conversion to
  10173. global functions that do not escape but instead compiles them as
  10174. regular functions. Create several new test cases that check whether
  10175. you properly detect whether global functions escape or not.
  10176. \end{exercise}
  10177. So far we have reduced the overhead of calling global functions, but
  10178. it would also be nice to reduce the overhead of calling a
  10179. \code{lambda} when we can determine at compile time which
  10180. \code{lambda} will be called. We refer to such calls as \emph{known
  10181. calls}. Consider the following example in which a \code{lambda} is
  10182. bound to \code{f} and then applied.
  10183. \begin{lstlisting}
  10184. (let ([y (read)])
  10185. (let ([f (lambda: ([x : Integer]) : Integer
  10186. (+ x y))])
  10187. (f 21)))
  10188. \end{lstlisting}
  10189. Closure conversion compiles \code{(f 21)} into an indirect call:
  10190. \begin{lstlisting}
  10191. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  10192. (let ([y2 (vector-ref fvs6 1)])
  10193. (+ x3 y2)))
  10194. (define (main) : Integer
  10195. (let ([y2 (read)])
  10196. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  10197. ((vector-ref f4 0) f4 21))))
  10198. \end{lstlisting}
  10199. but we can instead compile the application \code{(f 21)} into a direct call
  10200. to \code{lambda5}:
  10201. \begin{lstlisting}
  10202. (define (main) : Integer
  10203. (let ([y2 (read)])
  10204. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  10205. ((fun-ref lambda5) f4 21))))
  10206. \end{lstlisting}
  10207. The problem of determining which lambda will be called from a
  10208. particular application is quite challenging in general and the topic
  10209. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  10210. following exercise we recommend that you compile an application to a
  10211. direct call when the operator is a variable and the variable is
  10212. \code{let}-bound to a closure. This can be accomplished by maintaining
  10213. an environment mapping \code{let}-bound variables to function names.
  10214. Extend the environment whenever you encounter a closure on the
  10215. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  10216. to the name of the global function for the closure. This pass should
  10217. come after closure conversion.
  10218. \begin{exercise}\normalfont
  10219. Implement a compiler pass, named \code{optimize-known-calls}, that
  10220. compiles known calls into direct calls. Verify that your compiler is
  10221. successful in this regard on several example programs.
  10222. \end{exercise}
  10223. These exercises only scratches the surface of optimizing of
  10224. closures. A good next step for the interested reader is to look at the
  10225. work of \citet{Keep:2012ab}.
  10226. \section{Further Reading}
  10227. The notion of lexically scoped anonymous functions predates modern
  10228. computers by about a decade. They were invented by
  10229. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  10230. foundation for logic. Anonymous functions were included in the
  10231. LISP~\citep{McCarthy:1960dz} programming language but were initially
  10232. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  10233. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  10234. compile Scheme programs. However, environments were represented as
  10235. linked lists, so variable lookup was linear in the size of the
  10236. environment. In this chapter we represent environments using flat
  10237. closures, which were invented by
  10238. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  10239. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  10240. closures, variable lookup is constant time but the time to create a
  10241. closure is proportional to the number of its free variables. Flat
  10242. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  10243. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  10244. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10245. \chapter{Dynamic Typing}
  10246. \label{ch:Rdyn}
  10247. \index{subject}{dynamic typing}
  10248. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  10249. typed language that is a subset of Racket. This is in contrast to the
  10250. previous chapters, which have studied the compilation of Typed
  10251. Racket. In dynamically typed languages such as \LangDyn{}, a given
  10252. expression may produce a value of a different type each time it is
  10253. executed. Consider the following example with a conditional \code{if}
  10254. expression that may return a Boolean or an integer depending on the
  10255. input to the program.
  10256. % part of dynamic_test_25.rkt
  10257. \begin{lstlisting}
  10258. (not (if (eq? (read) 1) #f 0))
  10259. \end{lstlisting}
  10260. Languages that allow expressions to produce different kinds of values
  10261. are called \emph{polymorphic}, a word composed of the Greek roots
  10262. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  10263. are several kinds of polymorphism in programming languages, such as
  10264. subtype polymorphism and parametric
  10265. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  10266. study in this chapter does not have a special name but it is the kind
  10267. that arises in dynamically typed languages.
  10268. Another characteristic of dynamically typed languages is that
  10269. primitive operations, such as \code{not}, are often defined to operate
  10270. on many different types of values. In fact, in Racket, the \code{not}
  10271. operator produces a result for any kind of value: given \code{\#f} it
  10272. returns \code{\#t} and given anything else it returns \code{\#f}.
  10273. Furthermore, even when primitive operations restrict their inputs to
  10274. values of a certain type, this restriction is enforced at runtime
  10275. instead of during compilation. For example, the following vector
  10276. reference results in a run-time contract violation because the index
  10277. must be in integer, not a Boolean such as \code{\#t}.
  10278. \begin{lstlisting}
  10279. (vector-ref (vector 42) #t)
  10280. \end{lstlisting}
  10281. \begin{figure}[tp]
  10282. \centering
  10283. \fbox{
  10284. \begin{minipage}{0.97\textwidth}
  10285. \[
  10286. \begin{array}{rcl}
  10287. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  10288. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  10289. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  10290. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  10291. &\MID& \key{\#t} \MID \key{\#f}
  10292. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  10293. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  10294. \MID \CUNIOP{\key{not}}{\Exp} \\
  10295. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  10296. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  10297. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  10298. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  10299. &\MID& \LP\Exp \; \Exp\ldots\RP
  10300. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  10301. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  10302. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  10303. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  10304. \LangDynM{} &::=& \Def\ldots\; \Exp
  10305. \end{array}
  10306. \]
  10307. \end{minipage}
  10308. }
  10309. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  10310. \label{fig:r7-concrete-syntax}
  10311. \end{figure}
  10312. \begin{figure}[tp]
  10313. \centering
  10314. \fbox{
  10315. \begin{minipage}{0.96\textwidth}
  10316. \small
  10317. \[
  10318. \begin{array}{lcl}
  10319. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  10320. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  10321. &\MID& \BOOL{\itm{bool}}
  10322. \MID \IF{\Exp}{\Exp}{\Exp} \\
  10323. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  10324. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  10325. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  10326. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  10327. \end{array}
  10328. \]
  10329. \end{minipage}
  10330. }
  10331. \caption{The abstract syntax of \LangDyn{}.}
  10332. \label{fig:r7-syntax}
  10333. \end{figure}
  10334. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  10335. defined in Figures~\ref{fig:r7-concrete-syntax} and
  10336. \ref{fig:r7-syntax}.
  10337. %
  10338. There is no type checker for \LangDyn{} because it is not a statically
  10339. typed language (it's dynamically typed!).
  10340. The definitional interpreter for \LangDyn{} is presented in
  10341. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  10342. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  10343. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  10344. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  10345. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  10346. value} that combines an underlying value with a tag that identifies
  10347. what kind of value it is. We define the following struct
  10348. to represented tagged values.
  10349. \begin{lstlisting}
  10350. (struct Tagged (value tag) #:transparent)
  10351. \end{lstlisting}
  10352. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  10353. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  10354. but don't always capture all the information that a type does. For
  10355. example, a vector of type \code{(Vector Any Any)} is tagged with
  10356. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  10357. is tagged with \code{Procedure}.
  10358. Next consider the match case for \code{vector-ref}. The
  10359. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  10360. is used to ensure that the first argument is a vector and the second
  10361. is an integer. If they are not, a \code{trapped-error} is raised.
  10362. Recall from Section~\ref{sec:interp_Rint} that when a definition
  10363. interpreter raises a \code{trapped-error} error, the compiled code
  10364. must also signal an error by exiting with return code \code{255}. A
  10365. \code{trapped-error} is also raised if the index is not less than
  10366. length of the vector.
  10367. \begin{figure}[tbp]
  10368. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10369. (define ((interp-Rdyn-exp env) ast)
  10370. (define recur (interp-Rdyn-exp env))
  10371. (match ast
  10372. [(Var x) (lookup x env)]
  10373. [(Int n) (Tagged n 'Integer)]
  10374. [(Bool b) (Tagged b 'Boolean)]
  10375. [(Lambda xs rt body)
  10376. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  10377. [(Prim 'vector es)
  10378. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  10379. [(Prim 'vector-ref (list e1 e2))
  10380. (define vec (recur e1)) (define i (recur e2))
  10381. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  10382. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  10383. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  10384. (vector-ref (Tagged-value vec) (Tagged-value i))]
  10385. [(Prim 'vector-set! (list e1 e2 e3))
  10386. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  10387. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  10388. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  10389. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  10390. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  10391. (Tagged (void) 'Void)]
  10392. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  10393. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  10394. [(Prim 'or (list e1 e2))
  10395. (define v1 (recur e1))
  10396. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  10397. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  10398. [(Prim op (list e1))
  10399. #:when (set-member? type-predicates op)
  10400. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  10401. [(Prim op es)
  10402. (define args (map recur es))
  10403. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  10404. (unless (for/or ([expected-tags (op-tags op)])
  10405. (equal? expected-tags tags))
  10406. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  10407. (tag-value
  10408. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  10409. [(If q t f)
  10410. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  10411. [(Apply f es)
  10412. (define new-f (recur f)) (define args (map recur es))
  10413. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  10414. (match f-val
  10415. [`(function ,xs ,body ,lam-env)
  10416. (unless (eq? (length xs) (length args))
  10417. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  10418. (define new-env (append (map cons xs args) lam-env))
  10419. ((interp-Rdyn-exp new-env) body)]
  10420. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  10421. \end{lstlisting}
  10422. \caption{Interpreter for the \LangDyn{} language.}
  10423. \label{fig:interp-Rdyn}
  10424. \end{figure}
  10425. \begin{figure}[tbp]
  10426. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10427. (define (interp-op op)
  10428. (match op
  10429. ['+ fx+]
  10430. ['- fx-]
  10431. ['read read-fixnum]
  10432. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  10433. ['< (lambda (v1 v2)
  10434. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  10435. ['<= (lambda (v1 v2)
  10436. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  10437. ['> (lambda (v1 v2)
  10438. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  10439. ['>= (lambda (v1 v2)
  10440. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  10441. ['boolean? boolean?]
  10442. ['integer? fixnum?]
  10443. ['void? void?]
  10444. ['vector? vector?]
  10445. ['vector-length vector-length]
  10446. ['procedure? (match-lambda
  10447. [`(functions ,xs ,body ,env) #t] [else #f])]
  10448. [else (error 'interp-op "unknown operator" op)]))
  10449. (define (op-tags op)
  10450. (match op
  10451. ['+ '((Integer Integer))]
  10452. ['- '((Integer Integer) (Integer))]
  10453. ['read '(())]
  10454. ['not '((Boolean))]
  10455. ['< '((Integer Integer))]
  10456. ['<= '((Integer Integer))]
  10457. ['> '((Integer Integer))]
  10458. ['>= '((Integer Integer))]
  10459. ['vector-length '((Vector))]))
  10460. (define type-predicates
  10461. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  10462. (define (tag-value v)
  10463. (cond [(boolean? v) (Tagged v 'Boolean)]
  10464. [(fixnum? v) (Tagged v 'Integer)]
  10465. [(procedure? v) (Tagged v 'Procedure)]
  10466. [(vector? v) (Tagged v 'Vector)]
  10467. [(void? v) (Tagged v 'Void)]
  10468. [else (error 'tag-value "unidentified value ~a" v)]))
  10469. (define (check-tag val expected ast)
  10470. (define tag (Tagged-tag val))
  10471. (unless (eq? tag expected)
  10472. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  10473. \end{lstlisting}
  10474. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  10475. \label{fig:interp-Rdyn-aux}
  10476. \end{figure}
  10477. \clearpage
  10478. \section{Representation of Tagged Values}
  10479. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  10480. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  10481. values at the bit level. Because almost every operation in \LangDyn{}
  10482. involves manipulating tagged values, the representation must be
  10483. efficient. Recall that all of our values are 64 bits. We shall steal
  10484. the 3 right-most bits to encode the tag. We use $001$ to identify
  10485. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  10486. and $101$ for the void value. We define the following auxiliary
  10487. function for mapping types to tag codes.
  10488. \begin{align*}
  10489. \itm{tagof}(\key{Integer}) &= 001 \\
  10490. \itm{tagof}(\key{Boolean}) &= 100 \\
  10491. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  10492. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  10493. \itm{tagof}(\key{Void}) &= 101
  10494. \end{align*}
  10495. This stealing of 3 bits comes at some price: our integers are reduced
  10496. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  10497. affect vectors and procedures because those values are addresses, and
  10498. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  10499. they are always $000$. Thus, we do not lose information by overwriting
  10500. the rightmost 3 bits with the tag and we can simply zero-out the tag
  10501. to recover the original address.
  10502. To make tagged values into first-class entities, we can give them a
  10503. type, called \code{Any}, and define operations such as \code{Inject}
  10504. and \code{Project} for creating and using them, yielding the \LangAny{}
  10505. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  10506. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  10507. in greater detail.
  10508. \section{The \LangAny{} Language}
  10509. \label{sec:Rany-lang}
  10510. \begin{figure}[tp]
  10511. \centering
  10512. \fbox{
  10513. \begin{minipage}{0.96\textwidth}
  10514. \small
  10515. \[
  10516. \begin{array}{lcl}
  10517. \Type &::= & \ldots \MID \key{Any} \\
  10518. \itm{op} &::= & \ldots \MID \code{any-vector-length}
  10519. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  10520. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  10521. \MID \code{procedure?} \MID \code{void?} \\
  10522. \Exp &::=& \ldots
  10523. \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  10524. &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  10525. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  10526. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10527. \end{array}
  10528. \]
  10529. \end{minipage}
  10530. }
  10531. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  10532. \label{fig:Rany-syntax}
  10533. \end{figure}
  10534. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  10535. (The concrete syntax of \LangAny{} is in the Appendix,
  10536. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  10537. converts the value produced by expression $e$ of type $T$ into a
  10538. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  10539. produced by expression $e$ into a value of type $T$ or else halts the
  10540. program if the type tag is not equivalent to $T$.
  10541. %
  10542. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  10543. restricted to a flat type $\FType$, which simplifies the
  10544. implementation and corresponds with what is needed for compiling \LangDyn{}.
  10545. The \code{any-vector} operators adapt the vector operations so that
  10546. they can be applied to a value of type \code{Any}. They also
  10547. generalize the vector operations in that the index is not restricted
  10548. to be a literal integer in the grammar but is allowed to be any
  10549. expression.
  10550. The type predicates such as \key{boolean?} expect their argument to
  10551. produce a tagged value; they return \key{\#t} if the tag corresponds
  10552. to the predicate and they return \key{\#f} otherwise.
  10553. The type checker for \LangAny{} is shown in
  10554. Figures~\ref{fig:type-check-Rany-part-1} and
  10555. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  10556. Figure~\ref{fig:type-check-Rany-aux}.
  10557. %
  10558. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  10559. auxiliary functions \code{apply-inject} and \code{apply-project} are
  10560. in Figure~\ref{fig:apply-project}.
  10561. \begin{figure}[btp]
  10562. \begin{lstlisting}[basicstyle=\ttfamily\small]
  10563. (define type-check-Rany_class
  10564. (class type-check-Rlambda_class
  10565. (super-new)
  10566. (inherit check-type-equal?)
  10567. (define/override (type-check-exp env)
  10568. (lambda (e)
  10569. (define recur (type-check-exp env))
  10570. (match e
  10571. [(Inject e1 ty)
  10572. (unless (flat-ty? ty)
  10573. (error 'type-check "may only inject from flat type, not ~a" ty))
  10574. (define-values (new-e1 e-ty) (recur e1))
  10575. (check-type-equal? e-ty ty e)
  10576. (values (Inject new-e1 ty) 'Any)]
  10577. [(Project e1 ty)
  10578. (unless (flat-ty? ty)
  10579. (error 'type-check "may only project to flat type, not ~a" ty))
  10580. (define-values (new-e1 e-ty) (recur e1))
  10581. (check-type-equal? e-ty 'Any e)
  10582. (values (Project new-e1 ty) ty)]
  10583. [(Prim 'any-vector-length (list e1))
  10584. (define-values (e1^ t1) (recur e1))
  10585. (check-type-equal? t1 'Any e)
  10586. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  10587. [(Prim 'any-vector-ref (list e1 e2))
  10588. (define-values (e1^ t1) (recur e1))
  10589. (define-values (e2^ t2) (recur e2))
  10590. (check-type-equal? t1 'Any e)
  10591. (check-type-equal? t2 'Integer e)
  10592. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  10593. [(Prim 'any-vector-set! (list e1 e2 e3))
  10594. (define-values (e1^ t1) (recur e1))
  10595. (define-values (e2^ t2) (recur e2))
  10596. (define-values (e3^ t3) (recur e3))
  10597. (check-type-equal? t1 'Any e)
  10598. (check-type-equal? t2 'Integer e)
  10599. (check-type-equal? t3 'Any e)
  10600. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  10601. \end{lstlisting}
  10602. \caption{Type checker for the \LangAny{} language, part 1.}
  10603. \label{fig:type-check-Rany-part-1}
  10604. \end{figure}
  10605. \begin{figure}[btp]
  10606. \begin{lstlisting}[basicstyle=\ttfamily\small]
  10607. [(ValueOf e ty)
  10608. (define-values (new-e e-ty) (recur e))
  10609. (values (ValueOf new-e ty) ty)]
  10610. [(Prim pred (list e1))
  10611. #:when (set-member? (type-predicates) pred)
  10612. (define-values (new-e1 e-ty) (recur e1))
  10613. (check-type-equal? e-ty 'Any e)
  10614. (values (Prim pred (list new-e1)) 'Boolean)]
  10615. [(If cnd thn els)
  10616. (define-values (cnd^ Tc) (recur cnd))
  10617. (define-values (thn^ Tt) (recur thn))
  10618. (define-values (els^ Te) (recur els))
  10619. (check-type-equal? Tc 'Boolean cnd)
  10620. (check-type-equal? Tt Te e)
  10621. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  10622. [(Exit) (values (Exit) '_)]
  10623. [(Prim 'eq? (list arg1 arg2))
  10624. (define-values (e1 t1) (recur arg1))
  10625. (define-values (e2 t2) (recur arg2))
  10626. (match* (t1 t2)
  10627. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10628. [(other wise) (check-type-equal? t1 t2 e)])
  10629. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10630. [else ((super type-check-exp env) e)])))
  10631. ))
  10632. \end{lstlisting}
  10633. \caption{Type checker for the \LangAny{} language, part 2.}
  10634. \label{fig:type-check-Rany-part-2}
  10635. \end{figure}
  10636. \begin{figure}[tbp]
  10637. \begin{lstlisting}
  10638. (define/override (operator-types)
  10639. (append
  10640. '((integer? . ((Any) . Boolean))
  10641. (vector? . ((Any) . Boolean))
  10642. (procedure? . ((Any) . Boolean))
  10643. (void? . ((Any) . Boolean))
  10644. (tag-of-any . ((Any) . Integer))
  10645. (make-any . ((_ Integer) . Any))
  10646. )
  10647. (super operator-types)))
  10648. (define/public (type-predicates)
  10649. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  10650. (define/public (combine-types t1 t2)
  10651. (match (list t1 t2)
  10652. [(list '_ t2) t2]
  10653. [(list t1 '_) t1]
  10654. [(list `(Vector ,ts1 ...)
  10655. `(Vector ,ts2 ...))
  10656. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  10657. (combine-types t1 t2)))]
  10658. [(list `(,ts1 ... -> ,rt1)
  10659. `(,ts2 ... -> ,rt2))
  10660. `(,@(for/list ([t1 ts1] [t2 ts2])
  10661. (combine-types t1 t2))
  10662. -> ,(combine-types rt1 rt2))]
  10663. [else t1]))
  10664. (define/public (flat-ty? ty)
  10665. (match ty
  10666. [(or `Integer `Boolean '_ `Void) #t]
  10667. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  10668. [`(,ts ... -> ,rt)
  10669. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  10670. [else #f]))
  10671. \end{lstlisting}
  10672. \caption{Auxiliary methods for type checking \LangAny{}.}
  10673. \label{fig:type-check-Rany-aux}
  10674. \end{figure}
  10675. \begin{figure}[btp]
  10676. \begin{lstlisting}
  10677. (define interp-Rany_class
  10678. (class interp-Rlambda_class
  10679. (super-new)
  10680. (define/override (interp-op op)
  10681. (match op
  10682. ['boolean? (match-lambda
  10683. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  10684. [else #f])]
  10685. ['integer? (match-lambda
  10686. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  10687. [else #f])]
  10688. ['vector? (match-lambda
  10689. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  10690. [else #f])]
  10691. ['procedure? (match-lambda
  10692. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  10693. [else #f])]
  10694. ['eq? (match-lambda*
  10695. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  10696. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  10697. [ls (apply (super interp-op op) ls)])]
  10698. ['any-vector-ref (lambda (v i)
  10699. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  10700. ['any-vector-set! (lambda (v i a)
  10701. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  10702. ['any-vector-length (lambda (v)
  10703. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  10704. [else (super interp-op op)]))
  10705. (define/override ((interp-exp env) e)
  10706. (define recur (interp-exp env))
  10707. (match e
  10708. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  10709. [(Project e ty2) (apply-project (recur e) ty2)]
  10710. [else ((super interp-exp env) e)]))
  10711. ))
  10712. (define (interp-Rany p)
  10713. (send (new interp-Rany_class) interp-program p))
  10714. \end{lstlisting}
  10715. \caption{Interpreter for \LangAny{}.}
  10716. \label{fig:interp-Rany}
  10717. \end{figure}
  10718. \begin{figure}[tbp]
  10719. \begin{lstlisting}
  10720. (define/public (apply-inject v tg) (Tagged v tg))
  10721. (define/public (apply-project v ty2)
  10722. (define tag2 (any-tag ty2))
  10723. (match v
  10724. [(Tagged v1 tag1)
  10725. (cond
  10726. [(eq? tag1 tag2)
  10727. (match ty2
  10728. [`(Vector ,ts ...)
  10729. (define l1 ((interp-op 'vector-length) v1))
  10730. (cond
  10731. [(eq? l1 (length ts)) v1]
  10732. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  10733. l1 (length ts))])]
  10734. [`(,ts ... -> ,rt)
  10735. (match v1
  10736. [`(function ,xs ,body ,env)
  10737. (cond [(eq? (length xs) (length ts)) v1]
  10738. [else
  10739. (error 'apply-project "arity mismatch ~a != ~a"
  10740. (length xs) (length ts))])]
  10741. [else (error 'apply-project "expected function not ~a" v1)])]
  10742. [else v1])]
  10743. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  10744. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  10745. \end{lstlisting}
  10746. \caption{Auxiliary functions for injection and projection.}
  10747. \label{fig:apply-project}
  10748. \end{figure}
  10749. \clearpage
  10750. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  10751. \label{sec:compile-r7}
  10752. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  10753. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  10754. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  10755. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  10756. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  10757. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  10758. the Boolean \code{\#t}, which must be injected to produce an
  10759. expression of type \key{Any}.
  10760. %
  10761. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  10762. addition, is representative of compilation for many primitive
  10763. operations: the arguments have type \key{Any} and must be projected to
  10764. \key{Integer} before the addition can be performed.
  10765. The compilation of \key{lambda} (third row of
  10766. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  10767. produce type annotations: we simply use \key{Any}.
  10768. %
  10769. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  10770. has to account for some differences in behavior between \LangDyn{} and
  10771. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  10772. kind of values can be used in various places. For example, the
  10773. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  10774. the arguments need not be of the same type (in that case the
  10775. result is \code{\#f}).
  10776. \begin{figure}[btp]
  10777. \centering
  10778. \begin{tabular}{|lll|} \hline
  10779. \begin{minipage}{0.27\textwidth}
  10780. \begin{lstlisting}
  10781. #t
  10782. \end{lstlisting}
  10783. \end{minipage}
  10784. &
  10785. $\Rightarrow$
  10786. &
  10787. \begin{minipage}{0.65\textwidth}
  10788. \begin{lstlisting}
  10789. (inject #t Boolean)
  10790. \end{lstlisting}
  10791. \end{minipage}
  10792. \\[2ex]\hline
  10793. \begin{minipage}{0.27\textwidth}
  10794. \begin{lstlisting}
  10795. (+ |$e_1$| |$e_2$|)
  10796. \end{lstlisting}
  10797. \end{minipage}
  10798. &
  10799. $\Rightarrow$
  10800. &
  10801. \begin{minipage}{0.65\textwidth}
  10802. \begin{lstlisting}
  10803. (inject
  10804. (+ (project |$e'_1$| Integer)
  10805. (project |$e'_2$| Integer))
  10806. Integer)
  10807. \end{lstlisting}
  10808. \end{minipage}
  10809. \\[2ex]\hline
  10810. \begin{minipage}{0.27\textwidth}
  10811. \begin{lstlisting}
  10812. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  10813. \end{lstlisting}
  10814. \end{minipage}
  10815. &
  10816. $\Rightarrow$
  10817. &
  10818. \begin{minipage}{0.65\textwidth}
  10819. \begin{lstlisting}
  10820. (inject
  10821. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  10822. (Any|$\ldots$|Any -> Any))
  10823. \end{lstlisting}
  10824. \end{minipage}
  10825. \\[2ex]\hline
  10826. \begin{minipage}{0.27\textwidth}
  10827. \begin{lstlisting}
  10828. (|$e_0$| |$e_1 \ldots e_n$|)
  10829. \end{lstlisting}
  10830. \end{minipage}
  10831. &
  10832. $\Rightarrow$
  10833. &
  10834. \begin{minipage}{0.65\textwidth}
  10835. \begin{lstlisting}
  10836. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  10837. \end{lstlisting}
  10838. \end{minipage}
  10839. \\[2ex]\hline
  10840. \begin{minipage}{0.27\textwidth}
  10841. \begin{lstlisting}
  10842. (vector-ref |$e_1$| |$e_2$|)
  10843. \end{lstlisting}
  10844. \end{minipage}
  10845. &
  10846. $\Rightarrow$
  10847. &
  10848. \begin{minipage}{0.65\textwidth}
  10849. \begin{lstlisting}
  10850. (any-vector-ref |$e_1'$| |$e_2'$|)
  10851. \end{lstlisting}
  10852. \end{minipage}
  10853. \\[2ex]\hline
  10854. \begin{minipage}{0.27\textwidth}
  10855. \begin{lstlisting}
  10856. (if |$e_1$| |$e_2$| |$e_3$|)
  10857. \end{lstlisting}
  10858. \end{minipage}
  10859. &
  10860. $\Rightarrow$
  10861. &
  10862. \begin{minipage}{0.65\textwidth}
  10863. \begin{lstlisting}
  10864. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  10865. \end{lstlisting}
  10866. \end{minipage}
  10867. \\[2ex]\hline
  10868. \begin{minipage}{0.27\textwidth}
  10869. \begin{lstlisting}
  10870. (eq? |$e_1$| |$e_2$|)
  10871. \end{lstlisting}
  10872. \end{minipage}
  10873. &
  10874. $\Rightarrow$
  10875. &
  10876. \begin{minipage}{0.65\textwidth}
  10877. \begin{lstlisting}
  10878. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  10879. \end{lstlisting}
  10880. \end{minipage}
  10881. \\[2ex]\hline
  10882. \begin{minipage}{0.27\textwidth}
  10883. \begin{lstlisting}
  10884. (not |$e_1$|)
  10885. \end{lstlisting}
  10886. \end{minipage}
  10887. &
  10888. $\Rightarrow$
  10889. &
  10890. \begin{minipage}{0.65\textwidth}
  10891. \begin{lstlisting}
  10892. (if (eq? |$e'_1$| (inject #f Boolean))
  10893. (inject #t Boolean) (inject #f Boolean))
  10894. \end{lstlisting}
  10895. \end{minipage}
  10896. \\[2ex]\hline
  10897. \end{tabular}
  10898. \caption{Cast Insertion}
  10899. \label{fig:compile-r7-Rany}
  10900. \end{figure}
  10901. \section{Reveal Casts}
  10902. \label{sec:reveal-casts-Rany}
  10903. % TODO: define R'_6
  10904. In the \code{reveal-casts} pass we recommend compiling \code{project}
  10905. into an \code{if} expression that checks whether the value's tag
  10906. matches the target type; if it does, the value is converted to a value
  10907. of the target type by removing the tag; if it does not, the program
  10908. exits. To perform these actions we need a new primitive operation,
  10909. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  10910. The \code{tag-of-any} operation retrieves the type tag from a tagged
  10911. value of type \code{Any}. The \code{ValueOf} form retrieves the
  10912. underlying value from a tagged value. The \code{ValueOf} form
  10913. includes the type for the underlying value which is used by the type
  10914. checker. Finally, the \code{Exit} form ends the execution of the
  10915. program.
  10916. If the target type of the projection is \code{Boolean} or
  10917. \code{Integer}, then \code{Project} can be translated as follows.
  10918. \begin{center}
  10919. \begin{minipage}{1.0\textwidth}
  10920. \begin{lstlisting}
  10921. (Project |$e$| |$\FType$|)
  10922. |$\Rightarrow$|
  10923. (Let |$\itm{tmp}$| |$e'$|
  10924. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  10925. (Int |$\itm{tagof}(\FType)$|)))
  10926. (ValueOf |$\itm{tmp}$| |$\FType$|)
  10927. (Exit)))
  10928. \end{lstlisting}
  10929. \end{minipage}
  10930. \end{center}
  10931. If the target type of the projection is a vector or function type,
  10932. then there is a bit more work to do. For vectors, check that the
  10933. length of the vector type matches the length of the vector (using the
  10934. \code{vector-length} primitive). For functions, check that the number
  10935. of parameters in the function type matches the function's arity (using
  10936. \code{procedure-arity}).
  10937. Regarding \code{inject}, we recommend compiling it to a slightly
  10938. lower-level primitive operation named \code{make-any}. This operation
  10939. takes a tag instead of a type.
  10940. \begin{center}
  10941. \begin{minipage}{1.0\textwidth}
  10942. \begin{lstlisting}
  10943. (Inject |$e$| |$\FType$|)
  10944. |$\Rightarrow$|
  10945. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  10946. \end{lstlisting}
  10947. \end{minipage}
  10948. \end{center}
  10949. The type predicates (\code{boolean?}, etc.) can be translated into
  10950. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  10951. translation of \code{Project}.
  10952. The \code{any-vector-ref} and \code{any-vector-set!} operations
  10953. combine the projection action with the vector operation. Also, the
  10954. read and write operations allow arbitrary expressions for the index so
  10955. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  10956. cannot guarantee that the index is within bounds. Thus, we insert code
  10957. to perform bounds checking at runtime. The translation for
  10958. \code{any-vector-ref} is as follows and the other two operations are
  10959. translated in a similar way.
  10960. \begin{lstlisting}
  10961. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  10962. |$\Rightarrow$|
  10963. (Let |$v$| |$e'_1$|
  10964. (Let |$i$| |$e'_2$|
  10965. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  10966. (If (Prim '< (list (Var |$i$|)
  10967. (Prim 'any-vector-length (list (Var |$v$|)))))
  10968. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  10969. (Exit))))
  10970. \end{lstlisting}
  10971. \section{Remove Complex Operands}
  10972. \label{sec:rco-Rany}
  10973. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  10974. The subexpression of \code{ValueOf} must be atomic.
  10975. \section{Explicate Control and \LangCAny{}}
  10976. \label{sec:explicate-Rany}
  10977. The output of \code{explicate-control} is the \LangCAny{} language whose
  10978. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  10979. form that we added to \LangAny{} remains an expression and the \code{Exit}
  10980. expression becomes a $\Tail$. Also, note that the index argument of
  10981. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  10982. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  10983. \begin{figure}[tp]
  10984. \fbox{
  10985. \begin{minipage}{0.96\textwidth}
  10986. \small
  10987. \[
  10988. \begin{array}{lcl}
  10989. \Exp &::= & \ldots
  10990. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  10991. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  10992. &\MID& \VALUEOF{\Exp}{\FType} \\
  10993. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10994. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  10995. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10996. \MID \GOTO{\itm{label}} } \\
  10997. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10998. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  10999. \MID \LP\key{Exit}\RP \\
  11000. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  11001. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  11002. \end{array}
  11003. \]
  11004. \end{minipage}
  11005. }
  11006. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  11007. \label{fig:c5-syntax}
  11008. \end{figure}
  11009. \section{Select Instructions}
  11010. \label{sec:select-Rany}
  11011. In the \code{select-instructions} pass we translate the primitive
  11012. operations on the \code{Any} type to x86 instructions that involve
  11013. manipulating the 3 tag bits of the tagged value.
  11014. \paragraph{Make-any}
  11015. We recommend compiling the \key{make-any} primitive as follows if the
  11016. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  11017. shifts the destination to the left by the number of bits specified its
  11018. source argument (in this case $3$, the length of the tag) and it
  11019. preserves the sign of the integer. We use the \key{orq} instruction to
  11020. combine the tag and the value to form the tagged value. \\
  11021. \begin{lstlisting}
  11022. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  11023. |$\Rightarrow$|
  11024. movq |$e'$|, |\itm{lhs'}|
  11025. salq $3, |\itm{lhs'}|
  11026. orq $|$\itm{tag}$|, |\itm{lhs'}|
  11027. \end{lstlisting}
  11028. The instruction selection for vectors and procedures is different
  11029. because their is no need to shift them to the left. The rightmost 3
  11030. bits are already zeros as described at the beginning of this
  11031. chapter. So we just combine the value and the tag using \key{orq}. \\
  11032. \begin{lstlisting}
  11033. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  11034. |$\Rightarrow$|
  11035. movq |$e'$|, |\itm{lhs'}|
  11036. orq $|$\itm{tag}$|, |\itm{lhs'}|
  11037. \end{lstlisting}
  11038. \paragraph{Tag-of-any}
  11039. Recall that the \code{tag-of-any} operation extracts the type tag from
  11040. a value of type \code{Any}. The type tag is the bottom three bits, so
  11041. we obtain the tag by taking the bitwise-and of the value with $111$
  11042. ($7$ in decimal).
  11043. \begin{lstlisting}
  11044. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  11045. |$\Rightarrow$|
  11046. movq |$e'$|, |\itm{lhs'}|
  11047. andq $7, |\itm{lhs'}|
  11048. \end{lstlisting}
  11049. \paragraph{ValueOf}
  11050. Like \key{make-any}, the instructions for \key{ValueOf} are different
  11051. depending on whether the type $T$ is a pointer (vector or procedure)
  11052. or not (Integer or Boolean). The following shows the instruction
  11053. selection for Integer and Boolean. We produce an untagged value by
  11054. shifting it to the right by 3 bits.
  11055. \begin{lstlisting}
  11056. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  11057. |$\Rightarrow$|
  11058. movq |$e'$|, |\itm{lhs'}|
  11059. sarq $3, |\itm{lhs'}|
  11060. \end{lstlisting}
  11061. %
  11062. In the case for vectors and procedures, there is no need to
  11063. shift. Instead we just need to zero-out the rightmost 3 bits. We
  11064. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  11065. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  11066. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  11067. then apply \code{andq} with the tagged value to get the desired
  11068. result. \\
  11069. \begin{lstlisting}
  11070. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  11071. |$\Rightarrow$|
  11072. movq $|$-8$|, |\itm{lhs'}|
  11073. andq |$e'$|, |\itm{lhs'}|
  11074. \end{lstlisting}
  11075. %% \paragraph{Type Predicates} We leave it to the reader to
  11076. %% devise a sequence of instructions to implement the type predicates
  11077. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  11078. \paragraph{Any-vector-length}
  11079. \begin{lstlisting}
  11080. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  11081. |$\Longrightarrow$|
  11082. movq |$\neg 111$|, %r11
  11083. andq |$a_1'$|, %r11
  11084. movq 0(%r11), %r11
  11085. andq $126, %r11
  11086. sarq $1, %r11
  11087. movq %r11, |$\itm{lhs'}$|
  11088. \end{lstlisting}
  11089. \paragraph{Any-vector-ref}
  11090. The index may be an arbitrary atom so instead of computing the offset
  11091. at compile time, instructions need to be generated to compute the
  11092. offset at runtime as follows. Note the use of the new instruction
  11093. \code{imulq}.
  11094. \begin{center}
  11095. \begin{minipage}{0.96\textwidth}
  11096. \begin{lstlisting}
  11097. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  11098. |$\Longrightarrow$|
  11099. movq |$\neg 111$|, %r11
  11100. andq |$a_1'$|, %r11
  11101. movq |$a_2'$|, %rax
  11102. addq $1, %rax
  11103. imulq $8, %rax
  11104. addq %rax, %r11
  11105. movq 0(%r11) |$\itm{lhs'}$|
  11106. \end{lstlisting}
  11107. \end{minipage}
  11108. \end{center}
  11109. \paragraph{Any-vector-set!}
  11110. The code generation for \code{any-vector-set!} is similar to the other
  11111. \code{any-vector} operations.
  11112. \section{Register Allocation for \LangAny{}}
  11113. \label{sec:register-allocation-Rany}
  11114. \index{subject}{register allocation}
  11115. There is an interesting interaction between tagged values and garbage
  11116. collection that has an impact on register allocation. A variable of
  11117. type \code{Any} might refer to a vector and therefore it might be a
  11118. root that needs to be inspected and copied during garbage
  11119. collection. Thus, we need to treat variables of type \code{Any} in a
  11120. similar way to variables of type \code{Vector} for purposes of
  11121. register allocation. In particular,
  11122. \begin{itemize}
  11123. \item If a variable of type \code{Any} is live during a function call,
  11124. then it must be spilled. This can be accomplished by changing
  11125. \code{build-interference} to mark all variables of type \code{Any}
  11126. that are live after a \code{callq} as interfering with all the
  11127. registers.
  11128. \item If a variable of type \code{Any} is spilled, it must be spilled
  11129. to the root stack instead of the normal procedure call stack.
  11130. \end{itemize}
  11131. Another concern regarding the root stack is that the garbage collector
  11132. needs to differentiate between (1) plain old pointers to tuples, (2) a
  11133. tagged value that points to a tuple, and (3) a tagged value that is
  11134. not a tuple. We enable this differentiation by choosing not to use the
  11135. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  11136. reserved for identifying plain old pointers to tuples. That way, if
  11137. one of the first three bits is set, then we have a tagged value and
  11138. inspecting the tag can differentiation between vectors ($010$) and the
  11139. other kinds of values.
  11140. \begin{exercise}\normalfont
  11141. Expand your compiler to handle \LangAny{} as discussed in the last few
  11142. sections. Create 5 new programs that use the \code{Any} type and the
  11143. new operations (\code{inject}, \code{project}, \code{boolean?},
  11144. etc.). Test your compiler on these new programs and all of your
  11145. previously created test programs.
  11146. \end{exercise}
  11147. \begin{exercise}\normalfont
  11148. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  11149. Create tests for \LangDyn{} by adapting ten of your previous test programs
  11150. by removing type annotations. Add 5 more tests programs that
  11151. specifically rely on the language being dynamically typed. That is,
  11152. they should not be legal programs in a statically typed language, but
  11153. nevertheless, they should be valid \LangDyn{} programs that run to
  11154. completion without error.
  11155. \end{exercise}
  11156. \begin{figure}[p]
  11157. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11158. \node (Rfun) at (0,4) {\large \LangDyn{}};
  11159. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  11160. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  11161. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  11162. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  11163. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  11164. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  11165. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  11166. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  11167. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  11168. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  11169. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  11170. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11171. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11172. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11173. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11174. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11175. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11176. \path[->,bend left=15] (Rfun) edge [above] node
  11177. {\ttfamily\footnotesize shrink} (Rfun-2);
  11178. \path[->,bend left=15] (Rfun-2) edge [above] node
  11179. {\ttfamily\footnotesize uniquify} (Rfun-3);
  11180. \path[->,bend left=15] (Rfun-3) edge [above] node
  11181. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  11182. \path[->,bend right=15] (Rfun-4) edge [left] node
  11183. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  11184. \path[->,bend left=15] (Rfun-5) edge [above] node
  11185. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  11186. \path[->,bend left=15] (Rfun-6) edge [left] node
  11187. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  11188. \path[->,bend left=15] (Rfun-7) edge [below] node
  11189. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11190. \path[->,bend right=15] (F1-2) edge [above] node
  11191. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11192. \path[->,bend right=15] (F1-3) edge [above] node
  11193. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11194. \path[->,bend right=15] (F1-4) edge [above] node
  11195. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11196. \path[->,bend right=15] (F1-5) edge [right] node
  11197. {\ttfamily\footnotesize explicate-control} (C3-2);
  11198. \path[->,bend left=15] (C3-2) edge [left] node
  11199. {\ttfamily\footnotesize select-instr.} (x86-2);
  11200. \path[->,bend right=15] (x86-2) edge [left] node
  11201. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11202. \path[->,bend right=15] (x86-2-1) edge [below] node
  11203. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11204. \path[->,bend right=15] (x86-2-2) edge [left] node
  11205. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11206. \path[->,bend left=15] (x86-3) edge [above] node
  11207. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11208. \path[->,bend left=15] (x86-4) edge [right] node
  11209. {\ttfamily\footnotesize print-x86} (x86-5);
  11210. \end{tikzpicture}
  11211. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  11212. \label{fig:Rdyn-passes}
  11213. \end{figure}
  11214. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  11215. for the compilation of \LangDyn{}.
  11216. % Further Reading
  11217. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11218. \chapter{Loops and Assignment}
  11219. \label{ch:Rwhile}
  11220. % TODO: define R'_8
  11221. % TODO: multi-graph
  11222. In this chapter we study two features that are the hallmarks of
  11223. imperative programming languages: loops and assignments to local
  11224. variables. The following example demonstrates these new features by
  11225. computing the sum of the first five positive integers.
  11226. % similar to loop_test_1.rkt
  11227. \begin{lstlisting}
  11228. (let ([sum 0])
  11229. (let ([i 5])
  11230. (begin
  11231. (while (> i 0)
  11232. (begin
  11233. (set! sum (+ sum i))
  11234. (set! i (- i 1))))
  11235. sum)))
  11236. \end{lstlisting}
  11237. The \code{while} loop consists of a condition and a body.
  11238. %
  11239. The \code{set!} consists of a variable and a right-hand-side expression.
  11240. %
  11241. The primary purpose of both the \code{while} loop and \code{set!} is
  11242. to cause side effects, so it is convenient to also include in a
  11243. language feature for sequencing side effects: the \code{begin}
  11244. expression. It consists of one or more subexpressions that are
  11245. evaluated left-to-right.
  11246. \section{The \LangLoop{} Language}
  11247. \begin{figure}[tp]
  11248. \centering
  11249. \fbox{
  11250. \begin{minipage}{0.96\textwidth}
  11251. \small
  11252. \[
  11253. \begin{array}{lcl}
  11254. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11255. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11256. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11257. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11258. \MID (\key{and}\;\Exp\;\Exp)
  11259. \MID (\key{or}\;\Exp\;\Exp)
  11260. \MID (\key{not}\;\Exp) } \\
  11261. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11262. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  11263. (\key{vector-ref}\;\Exp\;\Int)} \\
  11264. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11265. \MID (\Exp \; \Exp\ldots) } \\
  11266. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11267. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11268. &\MID& \CSETBANG{\Var}{\Exp}
  11269. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11270. \MID \CWHILE{\Exp}{\Exp} \\
  11271. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11272. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  11273. \end{array}
  11274. \]
  11275. \end{minipage}
  11276. }
  11277. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  11278. \label{fig:Rwhile-concrete-syntax}
  11279. \end{figure}
  11280. \begin{figure}[tp]
  11281. \centering
  11282. \fbox{
  11283. \begin{minipage}{0.96\textwidth}
  11284. \small
  11285. \[
  11286. \begin{array}{lcl}
  11287. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11288. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11289. &\MID& \gray{ \BOOL{\itm{bool}}
  11290. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11291. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  11292. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  11293. &\MID& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  11294. &\MID& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  11295. \MID \WHILE{\Exp}{\Exp} \\
  11296. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  11297. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11298. \end{array}
  11299. \]
  11300. \end{minipage}
  11301. }
  11302. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  11303. \label{fig:Rwhile-syntax}
  11304. \end{figure}
  11305. The concrete syntax of \LangLoop{} is defined in
  11306. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  11307. in Figure~\ref{fig:Rwhile-syntax}.
  11308. %
  11309. The definitional interpreter for \LangLoop{} is shown in
  11310. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  11311. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  11312. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  11313. support assignment to variables and to make their lifetimes indefinite
  11314. (see the second example in Section~\ref{sec:assignment-scoping}), we
  11315. box the value that is bound to each variable (in \code{Let}) and
  11316. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  11317. the value.
  11318. %
  11319. Now to discuss the new cases. For \code{SetBang}, we lookup the
  11320. variable in the environment to obtain a boxed value and then we change
  11321. it using \code{set-box!} to the result of evaluating the right-hand
  11322. side. The result value of a \code{SetBang} is \code{void}.
  11323. %
  11324. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  11325. if the result is true, 2) evaluate the body.
  11326. The result value of a \code{while} loop is also \code{void}.
  11327. %
  11328. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  11329. subexpressions \itm{es} for their effects and then evaluates
  11330. and returns the result from \itm{body}.
  11331. \begin{figure}[tbp]
  11332. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11333. (define interp-Rwhile_class
  11334. (class interp-Rany_class
  11335. (super-new)
  11336. (define/override ((interp-exp env) e)
  11337. (define recur (interp-exp env))
  11338. (match e
  11339. [(SetBang x rhs)
  11340. (set-box! (lookup x env) (recur rhs))]
  11341. [(WhileLoop cnd body)
  11342. (define (loop)
  11343. (cond [(recur cnd) (recur body) (loop)]
  11344. [else (void)]))
  11345. (loop)]
  11346. [(Begin es body)
  11347. (for ([e es]) (recur e))
  11348. (recur body)]
  11349. [else ((super interp-exp env) e)]))
  11350. ))
  11351. (define (interp-Rwhile p)
  11352. (send (new interp-Rwhile_class) interp-program p))
  11353. \end{lstlisting}
  11354. \caption{Interpreter for \LangLoop{}.}
  11355. \label{fig:interp-Rwhile}
  11356. \end{figure}
  11357. The type checker for \LangLoop{} is define in
  11358. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  11359. variable and the right-hand-side must agree. The result type is
  11360. \code{Void}. For the \code{WhileLoop}, the condition must be a
  11361. \code{Boolean}. The result type is also \code{Void}. For
  11362. \code{Begin}, the result type is the type of its last subexpression.
  11363. \begin{figure}[tbp]
  11364. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11365. (define type-check-Rwhile_class
  11366. (class type-check-Rany_class
  11367. (super-new)
  11368. (inherit check-type-equal?)
  11369. (define/override (type-check-exp env)
  11370. (lambda (e)
  11371. (define recur (type-check-exp env))
  11372. (match e
  11373. [(SetBang x rhs)
  11374. (define-values (rhs^ rhsT) (recur rhs))
  11375. (define varT (dict-ref env x))
  11376. (check-type-equal? rhsT varT e)
  11377. (values (SetBang x rhs^) 'Void)]
  11378. [(WhileLoop cnd body)
  11379. (define-values (cnd^ Tc) (recur cnd))
  11380. (check-type-equal? Tc 'Boolean e)
  11381. (define-values (body^ Tbody) ((type-check-exp env) body))
  11382. (values (WhileLoop cnd^ body^) 'Void)]
  11383. [(Begin es body)
  11384. (define-values (es^ ts)
  11385. (for/lists (l1 l2) ([e es]) (recur e)))
  11386. (define-values (body^ Tbody) (recur body))
  11387. (values (Begin es^ body^) Tbody)]
  11388. [else ((super type-check-exp env) e)])))
  11389. ))
  11390. (define (type-check-Rwhile p)
  11391. (send (new type-check-Rwhile_class) type-check-program p))
  11392. \end{lstlisting}
  11393. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  11394. and \code{Begin} in \LangLoop{}.}
  11395. \label{fig:type-check-Rwhile}
  11396. \end{figure}
  11397. At first glance, the translation of these language features to x86
  11398. seems straightforward because the \LangCFun{} intermediate language already
  11399. supports all of the ingredients that we need: assignment, \code{goto},
  11400. conditional branching, and sequencing. However, there are two
  11401. complications that arise which we discuss in the next two
  11402. sections. After that we introduce one new compiler pass and the
  11403. changes necessary to the existing passes.
  11404. \section{Assignment and Lexically Scoped Functions}
  11405. \label{sec:assignment-scoping}
  11406. The addition of assignment raises a problem with our approach to
  11407. implementing lexically-scoped functions. Consider the following
  11408. example in which function \code{f} has a free variable \code{x} that
  11409. is changed after \code{f} is created but before the call to \code{f}.
  11410. % loop_test_11.rkt
  11411. \begin{lstlisting}
  11412. (let ([x 0])
  11413. (let ([y 0])
  11414. (let ([z 20])
  11415. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  11416. (begin
  11417. (set! x 10)
  11418. (set! y 12)
  11419. (f y))))))
  11420. \end{lstlisting}
  11421. The correct output for this example is \code{42} because the call to
  11422. \code{f} is required to use the current value of \code{x} (which is
  11423. \code{10}). Unfortunately, the closure conversion pass
  11424. (Section~\ref{sec:closure-conversion}) generates code for the
  11425. \code{lambda} that copies the old value of \code{x} into a
  11426. closure. Thus, if we naively add support for assignment to our current
  11427. compiler, the output of this program would be \code{32}.
  11428. A first attempt at solving this problem would be to save a pointer to
  11429. \code{x} in the closure and change the occurrences of \code{x} inside
  11430. the lambda to dereference the pointer. Of course, this would require
  11431. assigning \code{x} to the stack and not to a register. However, the
  11432. problem goes a bit deeper. Consider the following example in which we
  11433. create a counter abstraction by creating a pair of functions that
  11434. share the free variable \code{x}.
  11435. % similar to loop_test_10.rkt
  11436. \begin{lstlisting}
  11437. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  11438. (vector
  11439. (lambda: () : Integer x)
  11440. (lambda: () : Void (set! x (+ 1 x)))))
  11441. (let ([counter (f 0)])
  11442. (let ([get (vector-ref counter 0)])
  11443. (let ([inc (vector-ref counter 1)])
  11444. (begin
  11445. (inc)
  11446. (get)))))
  11447. \end{lstlisting}
  11448. In this example, the lifetime of \code{x} extends beyond the lifetime
  11449. of the call to \code{f}. Thus, if we were to store \code{x} on the
  11450. stack frame for the call to \code{f}, it would be gone by the time we
  11451. call \code{inc} and \code{get}, leaving us with dangling pointers for
  11452. \code{x}. This example demonstrates that when a variable occurs free
  11453. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  11454. value of the variable needs to live on the heap. The verb ``box'' is
  11455. often used for allocating a single value on the heap, producing a
  11456. pointer, and ``unbox'' for dereferencing the pointer.
  11457. We recommend solving these problems by ``boxing'' the local variables
  11458. that are in the intersection of 1) variables that appear on the
  11459. left-hand-side of a \code{set!} and 2) variables that occur free
  11460. inside a \code{lambda}. We shall introduce a new pass named
  11461. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  11462. perform this translation. But before diving into the compiler passes,
  11463. we one more problem to discuss.
  11464. \section{Cyclic Control Flow and Dataflow Analysis}
  11465. \label{sec:dataflow-analysis}
  11466. Up until this point the control-flow graphs generated in
  11467. \code{explicate-control} were guaranteed to be acyclic. However, each
  11468. \code{while} loop introduces a cycle in the control-flow graph.
  11469. But does that matter?
  11470. %
  11471. Indeed it does. Recall that for register allocation, the compiler
  11472. performs liveness analysis to determine which variables can share the
  11473. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  11474. the control-flow graph in reverse topological order, but topological
  11475. order is only well-defined for acyclic graphs.
  11476. Let us return to the example of computing the sum of the first five
  11477. positive integers. Here is the program after instruction selection but
  11478. before register allocation.
  11479. \begin{center}
  11480. \begin{minipage}{0.45\textwidth}
  11481. \begin{lstlisting}
  11482. (define (main) : Integer
  11483. mainstart:
  11484. movq $0, sum1
  11485. movq $5, i2
  11486. jmp block5
  11487. block5:
  11488. movq i2, tmp3
  11489. cmpq tmp3, $0
  11490. jl block7
  11491. jmp block8
  11492. \end{lstlisting}
  11493. \end{minipage}
  11494. \begin{minipage}{0.45\textwidth}
  11495. \begin{lstlisting}
  11496. block7:
  11497. addq i2, sum1
  11498. movq $1, tmp4
  11499. negq tmp4
  11500. addq tmp4, i2
  11501. jmp block5
  11502. block8:
  11503. movq $27, %rax
  11504. addq sum1, %rax
  11505. jmp mainconclusion
  11506. )
  11507. \end{lstlisting}
  11508. \end{minipage}
  11509. \end{center}
  11510. Recall that liveness analysis works backwards, starting at the end
  11511. of each function. For this example we could start with \code{block8}
  11512. because we know what is live at the beginning of the conclusion,
  11513. just \code{rax} and \code{rsp}. So the live-before set
  11514. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  11515. %
  11516. Next we might try to analyze \code{block5} or \code{block7}, but
  11517. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  11518. we are stuck.
  11519. The way out of this impasse comes from the realization that one can
  11520. perform liveness analysis starting with an empty live-after set to
  11521. compute an under-approximation of the live-before set. By
  11522. \emph{under-approximation}, we mean that the set only contains
  11523. variables that are really live, but it may be missing some. Next, the
  11524. under-approximations for each block can be improved by 1) updating the
  11525. live-after set for each block using the approximate live-before sets
  11526. from the other blocks and 2) perform liveness analysis again on each
  11527. block. In fact, by iterating this process, the under-approximations
  11528. eventually become the correct solutions!
  11529. %
  11530. This approach of iteratively analyzing a control-flow graph is
  11531. applicable to many static analysis problems and goes by the name
  11532. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  11533. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  11534. Washington.
  11535. Let us apply this approach to the above example. We use the empty set
  11536. for the initial live-before set for each block. Let $m_0$ be the
  11537. following mapping from label names to sets of locations (variables and
  11538. registers).
  11539. \begin{center}
  11540. \begin{lstlisting}
  11541. mainstart: {}
  11542. block5: {}
  11543. block7: {}
  11544. block8: {}
  11545. \end{lstlisting}
  11546. \end{center}
  11547. Using the above live-before approximations, we determine the
  11548. live-after for each block and then apply liveness analysis to each
  11549. block. This produces our next approximation $m_1$ of the live-before
  11550. sets.
  11551. \begin{center}
  11552. \begin{lstlisting}
  11553. mainstart: {}
  11554. block5: {i2}
  11555. block7: {i2, sum1}
  11556. block8: {rsp, sum1}
  11557. \end{lstlisting}
  11558. \end{center}
  11559. For the second round, the live-after for \code{mainstart} is the
  11560. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  11561. liveness analysis for \code{mainstart} computes the empty set. The
  11562. live-after for \code{block5} is the union of the live-before sets for
  11563. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  11564. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  11565. sum1\}}. The live-after for \code{block7} is the live-before for
  11566. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  11567. So the liveness analysis for \code{block7} remains \code{\{i2,
  11568. sum1\}}. Together these yield the following approximation $m_2$ of
  11569. the live-before sets.
  11570. \begin{center}
  11571. \begin{lstlisting}
  11572. mainstart: {}
  11573. block5: {i2, rsp, sum1}
  11574. block7: {i2, sum1}
  11575. block8: {rsp, sum1}
  11576. \end{lstlisting}
  11577. \end{center}
  11578. In the preceding iteration, only \code{block5} changed, so we can
  11579. limit our attention to \code{mainstart} and \code{block7}, the two
  11580. blocks that jump to \code{block5}. As a result, the live-before sets
  11581. for \code{mainstart} and \code{block7} are updated to include
  11582. \code{rsp}, yielding the following approximation $m_3$.
  11583. \begin{center}
  11584. \begin{lstlisting}
  11585. mainstart: {rsp}
  11586. block5: {i2, rsp, sum1}
  11587. block7: {i2, rsp, sum1}
  11588. block8: {rsp, sum1}
  11589. \end{lstlisting}
  11590. \end{center}
  11591. Because \code{block7} changed, we analyze \code{block5} once more, but
  11592. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  11593. our approximations have converged, so $m_3$ is the solution.
  11594. This iteration process is guaranteed to converge to a solution by the
  11595. Kleene Fixed-Point Theorem, a general theorem about functions on
  11596. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  11597. any collection that comes with a partial ordering $\sqsubseteq$ on its
  11598. elements, a least element $\bot$ (pronounced bottom), and a join
  11599. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  11600. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  11601. working with join semi-lattices.} When two elements are ordered $m_i
  11602. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  11603. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  11604. approximation than $m_i$. The bottom element $\bot$ represents the
  11605. complete lack of information, i.e., the worst approximation. The join
  11606. operator takes two lattice elements and combines their information,
  11607. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  11608. bound}
  11609. A dataflow analysis typically involves two lattices: one lattice to
  11610. represent abstract states and another lattice that aggregates the
  11611. abstract states of all the blocks in the control-flow graph. For
  11612. liveness analysis, an abstract state is a set of locations. We form
  11613. the lattice $L$ by taking its elements to be sets of locations, the
  11614. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  11615. set, and the join operator to be set union.
  11616. %
  11617. We form a second lattice $M$ by taking its elements to be mappings
  11618. from the block labels to sets of locations (elements of $L$). We
  11619. order the mappings point-wise, using the ordering of $L$. So given any
  11620. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  11621. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  11622. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  11623. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  11624. We can think of one iteration of liveness analysis as being a function
  11625. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  11626. mapping.
  11627. \[
  11628. f(m_i) = m_{i+1}
  11629. \]
  11630. Next let us think for a moment about what a final solution $m_s$
  11631. should look like. If we perform liveness analysis using the solution
  11632. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  11633. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  11634. \[
  11635. f(m_s) = m_s
  11636. \]
  11637. Furthermore, the solution should only include locations that are
  11638. forced to be there by performing liveness analysis on the program, so
  11639. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  11640. The Kleene Fixed-Point Theorem states that if a function $f$ is
  11641. monotone (better inputs produce better outputs), then the least fixed
  11642. point of $f$ is the least upper bound of the \emph{ascending Kleene
  11643. chain} obtained by starting at $\bot$ and iterating $f$ as
  11644. follows.\index{subject}{Kleene Fixed-Point Theorem}
  11645. \[
  11646. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  11647. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  11648. \]
  11649. When a lattice contains only finitely-long ascending chains, then
  11650. every Kleene chain tops out at some fixed point after a number of
  11651. iterations of $f$. So that fixed point is also a least upper
  11652. bound of the chain.
  11653. \[
  11654. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  11655. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  11656. \]
  11657. The liveness analysis is indeed a monotone function and the lattice
  11658. $M$ only has finitely-long ascending chains because there are only a
  11659. finite number of variables and blocks in the program. Thus we are
  11660. guaranteed that iteratively applying liveness analysis to all blocks
  11661. in the program will eventually produce the least fixed point solution.
  11662. Next let us consider dataflow analysis in general and discuss the
  11663. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  11664. %
  11665. The algorithm has four parameters: the control-flow graph \code{G}, a
  11666. function \code{transfer} that applies the analysis to one block, the
  11667. \code{bottom} and \code{join} operator for the lattice of abstract
  11668. states. The algorithm begins by creating the bottom mapping,
  11669. represented by a hash table. It then pushes all of the nodes in the
  11670. control-flow graph onto the work list (a queue). The algorithm repeats
  11671. the \code{while} loop as long as there are items in the work list. In
  11672. each iteration, a node is popped from the work list and processed. The
  11673. \code{input} for the node is computed by taking the join of the
  11674. abstract states of all the predecessor nodes. The \code{transfer}
  11675. function is then applied to obtain the \code{output} abstract
  11676. state. If the output differs from the previous state for this block,
  11677. the mapping for this block is updated and its successor nodes are
  11678. pushed onto the work list.
  11679. \begin{figure}[tb]
  11680. \begin{lstlisting}
  11681. (define (analyze-dataflow G transfer bottom join)
  11682. (define mapping (make-hash))
  11683. (for ([v (in-vertices G)])
  11684. (dict-set! mapping v bottom))
  11685. (define worklist (make-queue))
  11686. (for ([v (in-vertices G)])
  11687. (enqueue! worklist v))
  11688. (define trans-G (transpose G))
  11689. (while (not (queue-empty? worklist))
  11690. (define node (dequeue! worklist))
  11691. (define input (for/fold ([state bottom])
  11692. ([pred (in-neighbors trans-G node)])
  11693. (join state (dict-ref mapping pred))))
  11694. (define output (transfer node input))
  11695. (cond [(not (equal? output (dict-ref mapping node)))
  11696. (dict-set! mapping node output)
  11697. (for ([v (in-neighbors G node)])
  11698. (enqueue! worklist v))]))
  11699. mapping)
  11700. \end{lstlisting}
  11701. \caption{Generic work list algorithm for dataflow analysis}
  11702. \label{fig:generic-dataflow}
  11703. \end{figure}
  11704. Having discussed the two complications that arise from adding support
  11705. for assignment and loops, we turn to discussing the one new compiler
  11706. pass and the significant changes to existing passes.
  11707. \section{Convert Assignments}
  11708. \label{sec:convert-assignments}
  11709. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  11710. the combination of assignments and lexically-scoped functions requires
  11711. that we box those variables that are both assigned-to and that appear
  11712. free inside a \code{lambda}. The purpose of the
  11713. \code{convert-assignments} pass is to carry out that transformation.
  11714. We recommend placing this pass after \code{uniquify} but before
  11715. \code{reveal-functions}.
  11716. Consider again the first example from
  11717. Section~\ref{sec:assignment-scoping}:
  11718. \begin{lstlisting}
  11719. (let ([x 0])
  11720. (let ([y 0])
  11721. (let ([z 20])
  11722. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  11723. (begin
  11724. (set! x 10)
  11725. (set! y 12)
  11726. (f y))))))
  11727. \end{lstlisting}
  11728. The variables \code{x} and \code{y} are assigned-to. The variables
  11729. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  11730. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  11731. The boxing of \code{x} consists of three transformations: initialize
  11732. \code{x} with a vector, replace reads from \code{x} with
  11733. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  11734. \code{vector-set!}. The output of \code{convert-assignments} for this
  11735. example is as follows.
  11736. \begin{lstlisting}
  11737. (define (main) : Integer
  11738. (let ([x0 (vector 0)])
  11739. (let ([y1 0])
  11740. (let ([z2 20])
  11741. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  11742. (+ a3 (+ (vector-ref x0 0) z2)))])
  11743. (begin
  11744. (vector-set! x0 0 10)
  11745. (set! y1 12)
  11746. (f4 y1)))))))
  11747. \end{lstlisting}
  11748. \paragraph{Assigned \& Free}
  11749. We recommend defining an auxiliary function named
  11750. \code{assigned\&free} that takes an expression and simultaneously
  11751. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  11752. that occur free within lambda's, and 3) a new version of the
  11753. expression that records which bound variables occurred in the
  11754. intersection of $A$ and $F$. You can use the struct
  11755. \code{AssignedFree} to do this. Consider the case for
  11756. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  11757. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  11758. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  11759. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  11760. \begin{lstlisting}
  11761. (Let |$x$| |$rhs$| |$body$|)
  11762. |$\Rightarrow$|
  11763. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  11764. \end{lstlisting}
  11765. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  11766. The set of assigned variables for this \code{Let} is
  11767. $A_r \cup (A_b - \{x\})$
  11768. and the set of variables free in lambda's is
  11769. $F_r \cup (F_b - \{x\})$.
  11770. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  11771. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  11772. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  11773. and $F_r$.
  11774. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  11775. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  11776. recursively processing \itm{body}. Wrap each of parameter that occurs
  11777. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  11778. Let $P$ be the set of parameter names in \itm{params}. The result is
  11779. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  11780. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  11781. variables of an expression (see Chapter~\ref{ch:Rlam}).
  11782. \paragraph{Convert Assignments}
  11783. Next we discuss the \code{convert-assignment} pass with its auxiliary
  11784. functions for expressions and definitions. The function for
  11785. expressions, \code{cnvt-assign-exp}, should take an expression and a
  11786. set of assigned-and-free variables (obtained from the result of
  11787. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  11788. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  11789. \code{vector-ref}.
  11790. \begin{lstlisting}
  11791. (Var |$x$|)
  11792. |$\Rightarrow$|
  11793. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  11794. \end{lstlisting}
  11795. %
  11796. In the case for $\LET{\LP\code{AssignedFree}\,
  11797. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  11798. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  11799. \itm{body'} but with $x$ added to the set of assigned-and-free
  11800. variables. Translate the let-expression as follows to bind $x$ to a
  11801. boxed value.
  11802. \begin{lstlisting}
  11803. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  11804. |$\Rightarrow$|
  11805. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  11806. \end{lstlisting}
  11807. %
  11808. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  11809. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  11810. variables, translate the \code{set!} into a \code{vector-set!}
  11811. as follows.
  11812. \begin{lstlisting}
  11813. (SetBang |$x$| |$\itm{rhs}$|)
  11814. |$\Rightarrow$|
  11815. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  11816. \end{lstlisting}
  11817. %
  11818. The case for \code{Lambda} is non-trivial, but it is similar to the
  11819. case for function definitions, which we discuss next.
  11820. The auxiliary function for definitions, \code{cnvt-assign-def},
  11821. applies assignment conversion to function definitions.
  11822. We translate a function definition as follows.
  11823. \begin{lstlisting}
  11824. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  11825. |$\Rightarrow$|
  11826. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  11827. \end{lstlisting}
  11828. So it remains to explain \itm{params'} and $\itm{body}_4$.
  11829. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  11830. \code{assigned\&free} on $\itm{body_1}$.
  11831. Let $P$ be the parameter names in \itm{params}.
  11832. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  11833. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  11834. as the set of assigned-and-free variables.
  11835. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  11836. in a sequence of let-expressions that box the parameters
  11837. that are in $A_b \cap F_b$.
  11838. %
  11839. Regarding \itm{params'}, change the names of the parameters that are
  11840. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  11841. variables can retain the original names). Recall the second example in
  11842. Section~\ref{sec:assignment-scoping} involving a counter
  11843. abstraction. The following is the output of assignment version for
  11844. function \code{f}.
  11845. \begin{lstlisting}
  11846. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  11847. (vector
  11848. (lambda: () : Integer x1)
  11849. (lambda: () : Void (set! x1 (+ 1 x1)))))
  11850. |$\Rightarrow$|
  11851. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  11852. (let ([x1 (vector param_x1)])
  11853. (vector (lambda: () : Integer (vector-ref x1 0))
  11854. (lambda: () : Void
  11855. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  11856. \end{lstlisting}
  11857. \section{Remove Complex Operands}
  11858. \label{sec:rco-loop}
  11859. The three new language forms, \code{while}, \code{set!}, and
  11860. \code{begin} are all complex expressions and their subexpressions are
  11861. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  11862. output language \LangFunANF{} of this pass.
  11863. \begin{figure}[tp]
  11864. \centering
  11865. \fbox{
  11866. \begin{minipage}{0.96\textwidth}
  11867. \small
  11868. \[
  11869. \begin{array}{rcl}
  11870. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  11871. \MID \VOID{} } \\
  11872. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  11873. &\MID& \WHILE{\Exp}{\Exp} \MID \SETBANG{\Var}{\Exp}
  11874. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  11875. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11876. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  11877. \end{array}
  11878. \]
  11879. \end{minipage}
  11880. }
  11881. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  11882. \label{fig:Rwhile-anf-syntax}
  11883. \end{figure}
  11884. As usual, when a complex expression appears in a grammar position that
  11885. needs to be atomic, such as the argument of a primitive operator, we
  11886. must introduce a temporary variable and bind it to the complex
  11887. expression. This approach applies, unchanged, to handle the new
  11888. language forms. For example, in the following code there are two
  11889. \code{begin} expressions appearing as arguments to \code{+}. The
  11890. output of \code{rco-exp} is shown below, in which the \code{begin}
  11891. expressions have been bound to temporary variables. Recall that
  11892. \code{let} expressions in \LangLoopANF{} are allowed to have
  11893. arbitrary expressions in their right-hand-side expression, so it is
  11894. fine to place \code{begin} there.
  11895. \begin{lstlisting}
  11896. (let ([x0 10])
  11897. (let ([y1 0])
  11898. (+ (+ (begin (set! y1 (read)) x0)
  11899. (begin (set! x0 (read)) y1))
  11900. x0)))
  11901. |$\Rightarrow$|
  11902. (let ([x0 10])
  11903. (let ([y1 0])
  11904. (let ([tmp2 (begin (set! y1 (read)) x0)])
  11905. (let ([tmp3 (begin (set! x0 (read)) y1)])
  11906. (let ([tmp4 (+ tmp2 tmp3)])
  11907. (+ tmp4 x0))))))
  11908. \end{lstlisting}
  11909. \section{Explicate Control and \LangCLoop{}}
  11910. \label{sec:explicate-loop}
  11911. Recall that in the \code{explicate-control} pass we define one helper
  11912. function for each kind of position in the program. For the \LangVar{}
  11913. language of integers and variables we needed kinds of positions:
  11914. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  11915. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  11916. yet another kind of position: effect position. Except for the last
  11917. subexpression, the subexpressions inside a \code{begin} are evaluated
  11918. only for their effect. Their result values are discarded. We can
  11919. generate better code by taking this fact into account.
  11920. The output language of \code{explicate-control} is \LangCLoop{}
  11921. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  11922. \LangCLam{}. The only syntactic difference is that \code{Call},
  11923. \code{vector-set!}, and \code{read} may also appear as statements.
  11924. The most significant difference between \LangCLam{} and \LangCLoop{}
  11925. is that the control-flow graphs of the later may contain cycles.
  11926. \begin{figure}[tp]
  11927. \fbox{
  11928. \begin{minipage}{0.96\textwidth}
  11929. \small
  11930. \[
  11931. \begin{array}{lcl}
  11932. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  11933. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  11934. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  11935. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  11936. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  11937. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  11938. \end{array}
  11939. \]
  11940. \end{minipage}
  11941. }
  11942. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  11943. \label{fig:c7-syntax}
  11944. \end{figure}
  11945. The new auxiliary function \code{explicate-effect} takes an expression
  11946. (in an effect position) and a promise of a continuation block. The
  11947. function returns a promise for a $\Tail$ that includes the generated
  11948. code for the input expression followed by the continuation block. If
  11949. the expression is obviously pure, that is, never causes side effects,
  11950. then the expression can be removed, so the result is just the
  11951. continuation block.
  11952. %
  11953. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  11954. case. First, you will need a fresh label $\itm{loop}$ for the top of
  11955. the loop. Recursively process the \itm{body} (in effect position)
  11956. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  11957. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  11958. \itm{body'} as the then-branch and the continuation block as the
  11959. else-branch. The result should be added to the control-flow graph with
  11960. the label \itm{loop}. The result for the whole \code{while} loop is a
  11961. \code{goto} to the \itm{loop} label. Note that the loop should only be
  11962. added to the control-flow graph if the loop is indeed used, which can
  11963. be accomplished using \code{delay}.
  11964. The auxiliary functions for tail, assignment, and predicate positions
  11965. need to be updated. The three new language forms, \code{while},
  11966. \code{set!}, and \code{begin}, can appear in assignment and tail
  11967. positions. Only \code{begin} may appear in predicate positions; the
  11968. other two have result type \code{Void}.
  11969. \section{Select Instructions}
  11970. \label{sec:select-instructions-loop}
  11971. Only three small additions are needed in the
  11972. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  11973. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  11974. stand-alone statements instead of only appearing on the right-hand
  11975. side of an assignment statement. The code generation is nearly
  11976. identical; just leave off the instruction for moving the result into
  11977. the left-hand side.
  11978. \section{Register Allocation}
  11979. \label{sec:register-allocation-loop}
  11980. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  11981. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11982. which complicates the liveness analysis needed for register
  11983. allocation.
  11984. \subsection{Liveness Analysis}
  11985. \label{sec:liveness-analysis-r8}
  11986. We recommend using the generic \code{analyze-dataflow} function that
  11987. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  11988. perform liveness analysis, replacing the code in
  11989. \code{uncover-live-CFG} that processed the basic blocks in topological
  11990. order (Section~\ref{sec:liveness-analysis-Rif}).
  11991. The \code{analyze-dataflow} function has four parameters.
  11992. \begin{enumerate}
  11993. \item The first parameter \code{G} should be a directed graph from the
  11994. \code{racket/graph} package (see the sidebar in
  11995. Section~\ref{sec:build-interference}) that represents the
  11996. control-flow graph.
  11997. \item The second parameter \code{transfer} is a function that applies
  11998. liveness analysis to a basic block. It takes two parameters: the
  11999. label for the block to analyze and the live-after set for that
  12000. block. The transfer function should return the live-before set for
  12001. the block. Also, as a side-effect, it should update the block's
  12002. $\itm{info}$ with the liveness information for each instruction. To
  12003. implement the \code{transfer} function, you should be able to reuse
  12004. the code you already have for analyzing basic blocks.
  12005. \item The third and fourth parameters of \code{analyze-dataflow} are
  12006. \code{bottom} and \code{join} for the lattice of abstract states,
  12007. i.e. sets of locations. The bottom of the lattice is the empty set
  12008. \code{(set)} and the join operator is \code{set-union}.
  12009. \end{enumerate}
  12010. \begin{figure}[p]
  12011. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12012. \node (Rfun) at (0,2) {\large \LangLoop{}};
  12013. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  12014. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  12015. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  12016. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  12017. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  12018. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  12019. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  12020. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  12021. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  12022. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12023. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12024. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12025. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12026. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12027. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12028. %% \path[->,bend left=15] (Rfun) edge [above] node
  12029. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  12030. \path[->,bend left=15] (Rfun) edge [above] node
  12031. {\ttfamily\footnotesize shrink} (Rfun-2);
  12032. \path[->,bend left=15] (Rfun-2) edge [above] node
  12033. {\ttfamily\footnotesize uniquify} (Rfun-3);
  12034. \path[->,bend left=15] (Rfun-3) edge [above] node
  12035. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  12036. \path[->,bend left=15] (Rfun-4) edge [right] node
  12037. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12038. \path[->,bend left=15] (F1-1) edge [below] node
  12039. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12040. \path[->,bend right=15] (F1-2) edge [above] node
  12041. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12042. \path[->,bend right=15] (F1-3) edge [above] node
  12043. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12044. \path[->,bend right=15] (F1-4) edge [above] node
  12045. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12046. \path[->,bend right=15] (F1-5) edge [right] node
  12047. {\ttfamily\footnotesize explicate-control} (C3-2);
  12048. \path[->,bend left=15] (C3-2) edge [left] node
  12049. {\ttfamily\footnotesize select-instr.} (x86-2);
  12050. \path[->,bend right=15] (x86-2) edge [left] node
  12051. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12052. \path[->,bend right=15] (x86-2-1) edge [below] node
  12053. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12054. \path[->,bend right=15] (x86-2-2) edge [left] node
  12055. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12056. \path[->,bend left=15] (x86-3) edge [above] node
  12057. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12058. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12059. \end{tikzpicture}
  12060. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  12061. \label{fig:Rwhile-passes}
  12062. \end{figure}
  12063. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  12064. for the compilation of \LangLoop{}.
  12065. \section{Challenge: Arrays}
  12066. \label{sec:arrays}
  12067. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  12068. elements whose length is determined at compile-time and where each
  12069. element of a tuple may have a different type (they are
  12070. heterogeous). This challenge is also about sequences, but this time
  12071. the length is determined at run-time and all the elements have the same
  12072. type (they are homogeneous). We use the term ``array'' for this later
  12073. kind of sequence.
  12074. The Racket language does not distinguish between tuples and arrays,
  12075. they are both represented by vectors. However, Typed Racket
  12076. distinguishes between tuples and arrays: the \code{Vector} type is for
  12077. tuples and the \code{Vectorof} type is for arrays.
  12078. %
  12079. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  12080. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  12081. and the \code{make-vector} primitive operator for creating an array,
  12082. whose arguments are the length of the array and an initial value for
  12083. all the elements in the array. The \code{vector-length},
  12084. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12085. for tuples become overloaded for use with arrays.
  12086. %
  12087. We also include integer multiplication in \LangArray{}, as it is
  12088. useful in many examples involving arrays such as computing the
  12089. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  12090. \begin{figure}[tp]
  12091. \centering
  12092. \fbox{
  12093. \begin{minipage}{0.96\textwidth}
  12094. \small
  12095. \[
  12096. \begin{array}{lcl}
  12097. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  12098. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12099. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  12100. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  12101. &\MID& \gray{\key{\#t} \MID \key{\#f}
  12102. \MID \LP\key{and}\;\Exp\;\Exp\RP
  12103. \MID \LP\key{or}\;\Exp\;\Exp\RP
  12104. \MID \LP\key{not}\;\Exp\RP } \\
  12105. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  12106. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  12107. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  12108. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  12109. \MID \LP\Exp \; \Exp\ldots\RP } \\
  12110. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  12111. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  12112. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  12113. \MID \CBEGIN{\Exp\ldots}{\Exp}
  12114. \MID \CWHILE{\Exp}{\Exp} } \\
  12115. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  12116. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12117. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  12118. \end{array}
  12119. \]
  12120. \end{minipage}
  12121. }
  12122. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  12123. \label{fig:Rvecof-concrete-syntax}
  12124. \end{figure}
  12125. \begin{figure}[tp]
  12126. \begin{lstlisting}
  12127. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  12128. [n : Integer]) : Integer
  12129. (let ([i 0])
  12130. (let ([prod 0])
  12131. (begin
  12132. (while (< i n)
  12133. (begin
  12134. (set! prod (+ prod (* (vector-ref A i)
  12135. (vector-ref B i))))
  12136. (set! i (+ i 1))
  12137. ))
  12138. prod))))
  12139. (let ([A (make-vector 2 2)])
  12140. (let ([B (make-vector 2 3)])
  12141. (+ (inner-product A B 2)
  12142. 30)))
  12143. \end{lstlisting}
  12144. \caption{Example program that computes the inner-product.}
  12145. \label{fig:inner-product}
  12146. \end{figure}
  12147. The type checker for \LangArray{} is define in
  12148. Figure~\ref{fig:type-check-Rvecof}. The result type of
  12149. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  12150. of the intializing expression. The length expression is required to
  12151. have type \code{Integer}. The type checking of the operators
  12152. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12153. updated to handle the situation where the vector has type
  12154. \code{Vectorof}. In these cases we translate the operators to their
  12155. \code{vectorof} form so that later passes can easily distinguish
  12156. between operations on tuples versus arrays. We override the
  12157. \code{operator-types} method to provide the type signature for
  12158. multiplication: it takes two integers and returns an integer. To
  12159. support injection and projection of arrays to the \code{Any} type
  12160. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  12161. predicate.
  12162. \begin{figure}[tbp]
  12163. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12164. (define type-check-Rvecof_class
  12165. (class type-check-Rwhile_class
  12166. (super-new)
  12167. (inherit check-type-equal?)
  12168. (define/override (flat-ty? ty)
  12169. (match ty
  12170. ['(Vectorof Any) #t]
  12171. [else (super flat-ty? ty)]))
  12172. (define/override (operator-types)
  12173. (append '((* . ((Integer Integer) . Integer)))
  12174. (super operator-types)))
  12175. (define/override (type-check-exp env)
  12176. (lambda (e)
  12177. (define recur (type-check-exp env))
  12178. (match e
  12179. [(Prim 'make-vector (list e1 e2))
  12180. (define-values (e1^ t1) (recur e1))
  12181. (define-values (e2^ elt-type) (recur e2))
  12182. (define vec-type `(Vectorof ,elt-type))
  12183. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  12184. vec-type)]
  12185. [(Prim 'vector-ref (list e1 e2))
  12186. (define-values (e1^ t1) (recur e1))
  12187. (define-values (e2^ t2) (recur e2))
  12188. (match* (t1 t2)
  12189. [(`(Vectorof ,elt-type) 'Integer)
  12190. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12191. [(other wise) ((super type-check-exp env) e)])]
  12192. [(Prim 'vector-set! (list e1 e2 e3) )
  12193. (define-values (e-vec t-vec) (recur e1))
  12194. (define-values (e2^ t2) (recur e2))
  12195. (define-values (e-arg^ t-arg) (recur e3))
  12196. (match t-vec
  12197. [`(Vectorof ,elt-type)
  12198. (check-type-equal? elt-type t-arg e)
  12199. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12200. [else ((super type-check-exp env) e)])]
  12201. [(Prim 'vector-length (list e1))
  12202. (define-values (e1^ t1) (recur e1))
  12203. (match t1
  12204. [`(Vectorof ,t)
  12205. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12206. [else ((super type-check-exp env) e)])]
  12207. [else ((super type-check-exp env) e)])))
  12208. ))
  12209. (define (type-check-Rvecof p)
  12210. (send (new type-check-Rvecof_class) type-check-program p))
  12211. \end{lstlisting}
  12212. \caption{Type checker for the \LangArray{} language.}
  12213. \label{fig:type-check-Rvecof}
  12214. \end{figure}
  12215. The interpreter for \LangArray{} is defined in
  12216. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  12217. implemented with Racket's \code{make-vector} function and
  12218. multiplication is \code{fx*}, multiplication for \code{fixnum}
  12219. integers.
  12220. \begin{figure}[tbp]
  12221. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12222. (define interp-Rvecof_class
  12223. (class interp-Rwhile_class
  12224. (super-new)
  12225. (define/override (interp-op op)
  12226. (verbose "Rvecof/interp-op" op)
  12227. (match op
  12228. ['make-vector make-vector]
  12229. ['* fx*]
  12230. [else (super interp-op op)]))
  12231. ))
  12232. (define (interp-Rvecof p)
  12233. (send (new interp-Rvecof_class) interp-program p))
  12234. \end{lstlisting}
  12235. \caption{Interpreter for \LangArray{}.}
  12236. \label{fig:interp-Rvecof}
  12237. \end{figure}
  12238. \subsection{Data Representation}
  12239. \label{sec:array-rep}
  12240. Just like tuples, we store arrays on the heap which means that the
  12241. garbage collector will need to inspect arrays. An immediate thought is
  12242. to use the same representation for arrays that we use for tuples.
  12243. However, we limit tuples to a length of $50$ so that their length and
  12244. pointer mask can fit into the 64-bit tag at the beginning of each
  12245. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12246. millions of elements, so we need more bits to store the length.
  12247. However, because arrays are homogeneous, we only need $1$ bit for the
  12248. pointer mask instead of one bit per array elements. Finally, the
  12249. garbage collector will need to be able to distinguish between tuples
  12250. and arrays, so we need to reserve $1$ bit for that purpose. So we
  12251. arrive at the following layout for the 64-bit tag at the beginning of
  12252. an array:
  12253. \begin{itemize}
  12254. \item The right-most bit is the forwarding bit, just like in a tuple.
  12255. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  12256. it is not.
  12257. \item The next bit to the left is the pointer mask. A $0$ indicates
  12258. that none of the elements are pointers to the heap and a $1$
  12259. indicates that all of the elements are pointers.
  12260. \item The next $61$ bits store the length of the array.
  12261. \item The left-most bit distinguishes between a tuple ($0$) versus an
  12262. array ($1$).
  12263. \end{itemize}
  12264. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  12265. differentiate the kinds of values that have been injected into the
  12266. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12267. to indicate that the value is an array.
  12268. In the following subsections we provide hints regarding how to update
  12269. the passes to handle arrays.
  12270. \subsection{Reveal Casts}
  12271. The array-access operators \code{vectorof-ref} and
  12272. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12273. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  12274. that the type checker cannot tell whether the index will be in bounds,
  12275. so the bounds check must be performed at run time. Recall that the
  12276. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  12277. an \code{If} arround a vector reference for update to check whether
  12278. the index is less than the length. You should do the same for
  12279. \code{vectorof-ref} and \code{vectorof-set!} .
  12280. In addition, the handling of the \code{any-vector} operators in
  12281. \code{reveal-casts} needs to be updated to account for arrays that are
  12282. injected to \code{Any}. For the \code{any-vector-length} operator, the
  12283. generated code should test whether the tag is for tuples (\code{010})
  12284. or arrays (\code{110}) and then dispatch to either
  12285. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12286. we add a case in \code{select-instructions} to generate the
  12287. appropriate instructions for accessing the array length from the
  12288. header of an array.
  12289. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12290. the generated code needs to check that the index is less than the
  12291. vector length, so like the code for \code{any-vector-length}, check
  12292. the tag to determine whether to use \code{any-vector-length} or
  12293. \code{any-vectorof-length} for this purpose. Once the bounds checking
  12294. is complete, the generated code can use \code{any-vector-ref} and
  12295. \code{any-vector-set!} for both tuples and arrays because the
  12296. instructions used for those operators do not look at the tag at the
  12297. front of the tuple or array.
  12298. \subsection{Expose Allocation}
  12299. This pass should translate the \code{make-vector} operator into
  12300. lower-level operations. In particular, the new AST node
  12301. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  12302. length specified by the $\Exp$, but does not initialize the elements
  12303. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  12304. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  12305. element type for the array. Regarding the initialization of the array,
  12306. we recommend generated a \code{while} loop that uses
  12307. \code{vector-set!} to put the initializing value into every element of
  12308. the array.
  12309. \subsection{Remove Complex Operands}
  12310. Add cases in the \code{rco-atom} and \code{rco-exp} for
  12311. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12312. complex and its subexpression must be atomic.
  12313. \subsection{Explicate Control}
  12314. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  12315. \code{explicate-assign}.
  12316. \subsection{Select Instructions}
  12317. Generate instructions for \code{AllocateArray} similar to those for
  12318. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  12319. that the tag at the front of the array should instead use the
  12320. representation discussed in Section~\ref{sec:array-rep}.
  12321. Regarding \code{vectorof-length}, extract the length from the tag
  12322. according to the representation discussed in
  12323. Section~\ref{sec:array-rep}.
  12324. The instructions generated for \code{vectorof-ref} differ from those
  12325. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  12326. that the index is not a constant so the offset must be computed at
  12327. runtime, similar to the instructions generated for
  12328. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  12329. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  12330. appear in an assignment and as a stand-alone statement, so make sure
  12331. to handle both situations in this pass.
  12332. Finally, the instructions for \code{any-vectorof-length} should be
  12333. similar to those for \code{vectorof-length}, except that one must
  12334. first project the array by writing zeroes into the $3$-bit tag
  12335. \begin{exercise}\normalfont
  12336. Implement a compiler for the \LangArray{} language by extending your
  12337. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12338. programs, including the one in Figure~\ref{fig:inner-product} and also
  12339. a program that multiplies two matrices. Note that matrices are
  12340. 2-dimensional arrays, but those can be encoded into 1-dimensional
  12341. arrays by laying out each row in the array, one after the next.
  12342. \end{exercise}
  12343. % Further Reading: dataflow analysis
  12344. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12345. \chapter{Gradual Typing}
  12346. \label{ch:Rgrad}
  12347. \index{subject}{gradual typing}
  12348. This chapter studies a language, \LangGrad{}, in which the programmer
  12349. can choose between static and dynamic type checking in different parts
  12350. of a program, thereby mixing the statically typed \LangLoop{} language
  12351. with the dynamically typed \LangDyn{}. There are several approaches to
  12352. mixing static and dynamic typing, including multi-language
  12353. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  12354. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  12355. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  12356. programmer controls the amount of static versus dynamic checking by
  12357. adding or removing type annotations on parameters and
  12358. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  12359. %
  12360. The concrete syntax of \LangGrad{} is defined in
  12361. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  12362. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  12363. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  12364. non-terminals that make type annotations optional. The return types
  12365. are not optional in the abstract syntax; the parser fills in
  12366. \code{Any} when the return type is not specified in the concrete
  12367. syntax.
  12368. \begin{figure}[tp]
  12369. \centering
  12370. \fbox{
  12371. \begin{minipage}{0.96\textwidth}
  12372. \small
  12373. \[
  12374. \begin{array}{lcl}
  12375. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  12376. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  12377. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12378. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  12379. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  12380. &\MID& \gray{\key{\#t} \MID \key{\#f}
  12381. \MID (\key{and}\;\Exp\;\Exp)
  12382. \MID (\key{or}\;\Exp\;\Exp)
  12383. \MID (\key{not}\;\Exp) } \\
  12384. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  12385. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  12386. (\key{vector-ref}\;\Exp\;\Int)} \\
  12387. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  12388. \MID (\Exp \; \Exp\ldots) } \\
  12389. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  12390. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  12391. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  12392. \MID \CBEGIN{\Exp\ldots}{\Exp}
  12393. \MID \CWHILE{\Exp}{\Exp} } \\
  12394. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  12395. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  12396. \end{array}
  12397. \]
  12398. \end{minipage}
  12399. }
  12400. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  12401. \label{fig:Rgrad-concrete-syntax}
  12402. \end{figure}
  12403. \begin{figure}[tp]
  12404. \centering
  12405. \fbox{
  12406. \begin{minipage}{0.96\textwidth}
  12407. \small
  12408. \[
  12409. \begin{array}{lcl}
  12410. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  12411. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  12412. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  12413. &\MID& \gray{ \BOOL{\itm{bool}}
  12414. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  12415. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  12416. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  12417. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  12418. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  12419. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  12420. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  12421. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12422. \end{array}
  12423. \]
  12424. \end{minipage}
  12425. }
  12426. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  12427. \label{fig:Rgrad-syntax}
  12428. \end{figure}
  12429. Both the type checker and the interpreter for \LangGrad{} require some
  12430. interesting changes to enable gradual typing, which we discuss in the
  12431. next two sections in the context of the \code{map-vec} example from
  12432. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  12433. revised the \code{map-vec} example, omitting the type annotations from
  12434. the \code{add1} function.
  12435. \begin{figure}[btp]
  12436. % gradual_test_9.rkt
  12437. \begin{lstlisting}
  12438. (define (map-vec [f : (Integer -> Integer)]
  12439. [v : (Vector Integer Integer)])
  12440. : (Vector Integer Integer)
  12441. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12442. (define (add1 x) (+ x 1))
  12443. (vector-ref (map-vec add1 (vector 0 41)) 1)
  12444. \end{lstlisting}
  12445. \caption{A partially-typed version of the \code{map-vec} example.}
  12446. \label{fig:gradual-map-vec}
  12447. \end{figure}
  12448. \section{Type Checking \LangGrad{} and \LangCast{}}
  12449. \label{sec:gradual-type-check}
  12450. The type checker for \LangGrad{} uses the \code{Any} type for missing
  12451. parameter and return types. For example, the \code{x} parameter of
  12452. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  12453. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  12454. consider the \code{+} operator inside \code{add1}. It expects both
  12455. arguments to have type \code{Integer}, but its first argument \code{x}
  12456. has type \code{Any}. In a gradually typed language, such differences
  12457. are allowed so long as the types are \emph{consistent}, that is, they
  12458. are equal except in places where there is an \code{Any} type. The type
  12459. \code{Any} is consistent with every other type.
  12460. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  12461. \begin{figure}[tbp]
  12462. \begin{lstlisting}
  12463. (define/public (consistent? t1 t2)
  12464. (match* (t1 t2)
  12465. [('Integer 'Integer) #t]
  12466. [('Boolean 'Boolean) #t]
  12467. [('Void 'Void) #t]
  12468. [('Any t2) #t]
  12469. [(t1 'Any) #t]
  12470. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  12471. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  12472. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  12473. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  12474. (consistent? rt1 rt2))]
  12475. [(other wise) #f]))
  12476. \end{lstlisting}
  12477. \caption{The consistency predicate on types.}
  12478. \label{fig:consistent}
  12479. \end{figure}
  12480. Returning to the \code{map-vec} example of
  12481. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  12482. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  12483. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  12484. because the two types are consistent. In particular, \code{->} is
  12485. equal to \code{->} and because \code{Any} is consistent with
  12486. \code{Integer}.
  12487. Next consider a program with an error, such as applying the
  12488. \code{map-vec} to a function that sometimes returns a Boolean, as
  12489. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  12490. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  12491. consistent with the type of parameter \code{f} of \code{map-vec}, that
  12492. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  12493. Integer)}. One might say that a gradual type checker is optimistic
  12494. in that it accepts programs that might execute without a runtime type
  12495. error.
  12496. %
  12497. Unfortunately, running this program with input \code{1} triggers an
  12498. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  12499. performs checking at runtime to ensure the integrity of the static
  12500. types, such as the \code{(Integer -> Integer)} annotation on parameter
  12501. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  12502. new \code{Cast} form that is inserted by the type checker. Thus, the
  12503. output of the type checker is a program in the \LangCast{} language, which
  12504. adds \code{Cast} to \LangLoop{}, as shown in
  12505. Figure~\ref{fig:Rgrad-prime-syntax}.
  12506. \begin{figure}[tp]
  12507. \centering
  12508. \fbox{
  12509. \begin{minipage}{0.96\textwidth}
  12510. \small
  12511. \[
  12512. \begin{array}{lcl}
  12513. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  12514. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12515. \end{array}
  12516. \]
  12517. \end{minipage}
  12518. }
  12519. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  12520. \label{fig:Rgrad-prime-syntax}
  12521. \end{figure}
  12522. \begin{figure}[tbp]
  12523. \begin{lstlisting}
  12524. (define (map-vec [f : (Integer -> Integer)]
  12525. [v : (Vector Integer Integer)])
  12526. : (Vector Integer Integer)
  12527. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12528. (define (add1 x) (+ x 1))
  12529. (define (true) #t)
  12530. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  12531. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  12532. \end{lstlisting}
  12533. \caption{A variant of the \code{map-vec} example with an error.}
  12534. \label{fig:map-vec-maybe-add1}
  12535. \end{figure}
  12536. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  12537. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  12538. inserted every time the type checker sees two types that are
  12539. consistent but not equal. In the \code{add1} function, \code{x} is
  12540. cast to \code{Integer} and the result of the \code{+} is cast to
  12541. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  12542. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  12543. \begin{figure}[btp]
  12544. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12545. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12546. : (Vector Integer Integer)
  12547. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12548. (define (add1 [x : Any]) : Any
  12549. (cast (+ (cast x Any Integer) 1) Integer Any))
  12550. (define (true) : Any (cast #t Boolean Any))
  12551. (define (maybe-add1 [x : Any]) : Any
  12552. (if (eq? 0 (read)) (add1 x) (true)))
  12553. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  12554. (vector 0 41)) 0)
  12555. \end{lstlisting}
  12556. \caption{Output of type checking \code{map-vec}
  12557. and \code{maybe-add1}.}
  12558. \label{fig:map-vec-cast}
  12559. \end{figure}
  12560. The type checker for \LangGrad{} is defined in
  12561. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  12562. and \ref{fig:type-check-Rgradual-3}.
  12563. \begin{figure}[tbp]
  12564. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12565. (define type-check-gradual_class
  12566. (class type-check-Rwhile_class
  12567. (super-new)
  12568. (inherit operator-types type-predicates)
  12569. (define/override (type-check-exp env)
  12570. (lambda (e)
  12571. (define recur (type-check-exp env))
  12572. (match e
  12573. [(Prim 'vector-length (list e1))
  12574. (define-values (e1^ t) (recur e1))
  12575. (match t
  12576. [`(Vector ,ts ...)
  12577. (values (Prim 'vector-length (list e1^)) 'Integer)]
  12578. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  12579. [(Prim 'vector-ref (list e1 e2))
  12580. (define-values (e1^ t1) (recur e1))
  12581. (define-values (e2^ t2) (recur e2))
  12582. (check-consistent? t2 'Integer e)
  12583. (match t1
  12584. [`(Vector ,ts ...)
  12585. (match e2^
  12586. [(Int i)
  12587. (unless (and (0 . <= . i) (i . < . (length ts)))
  12588. (error 'type-check "invalid index ~a in ~a" i e))
  12589. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  12590. [else (define e1^^ (make-cast e1^ t1 'Any))
  12591. (define e2^^ (make-cast e2^ t2 'Integer))
  12592. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  12593. ['Any
  12594. (define e2^^ (make-cast e2^ t2 'Integer))
  12595. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  12596. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  12597. [(Prim 'vector-set! (list e1 e2 e3) )
  12598. (define-values (e1^ t1) (recur e1))
  12599. (define-values (e2^ t2) (recur e2))
  12600. (define-values (e3^ t3) (recur e3))
  12601. (check-consistent? t2 'Integer e)
  12602. (match t1
  12603. [`(Vector ,ts ...)
  12604. (match e2^
  12605. [(Int i)
  12606. (unless (and (0 . <= . i) (i . < . (length ts)))
  12607. (error 'type-check "invalid index ~a in ~a" i e))
  12608. (check-consistent? (list-ref ts i) t3 e)
  12609. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  12610. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  12611. [else
  12612. (define e1^^ (make-cast e1^ t1 'Any))
  12613. (define e2^^ (make-cast e2^ t2 'Integer))
  12614. (define e3^^ (make-cast e3^ t3 'Any))
  12615. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  12616. ['Any
  12617. (define e2^^ (make-cast e2^ t2 'Integer))
  12618. (define e3^^ (make-cast e3^ t3 'Any))
  12619. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  12620. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  12621. \end{lstlisting}
  12622. \caption{Type checker for the \LangGrad{} language, part 1.}
  12623. \label{fig:type-check-Rgradual-1}
  12624. \end{figure}
  12625. \begin{figure}[tbp]
  12626. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12627. [(Prim 'eq? (list e1 e2))
  12628. (define-values (e1^ t1) (recur e1))
  12629. (define-values (e2^ t2) (recur e2))
  12630. (check-consistent? t1 t2 e)
  12631. (define T (meet t1 t2))
  12632. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  12633. 'Boolean)]
  12634. [(Prim 'not (list e1))
  12635. (define-values (e1^ t1) (recur e1))
  12636. (match t1
  12637. ['Any
  12638. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  12639. (Bool #t) (Bool #f)))]
  12640. [else
  12641. (define-values (t-ret new-es^)
  12642. (type-check-op 'not (list t1) (list e1^) e))
  12643. (values (Prim 'not new-es^) t-ret)])]
  12644. [(Prim 'and (list e1 e2))
  12645. (recur (If e1 e2 (Bool #f)))]
  12646. [(Prim 'or (list e1 e2))
  12647. (define tmp (gensym 'tmp))
  12648. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  12649. [(Prim op es)
  12650. #:when (not (set-member? explicit-prim-ops op))
  12651. (define-values (new-es ts)
  12652. (for/lists (exprs types) ([e es])
  12653. (recur e)))
  12654. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  12655. (values (Prim op new-es^) t-ret)]
  12656. [(If e1 e2 e3)
  12657. (define-values (e1^ T1) (recur e1))
  12658. (define-values (e2^ T2) (recur e2))
  12659. (define-values (e3^ T3) (recur e3))
  12660. (check-consistent? T2 T3 e)
  12661. (match T1
  12662. ['Boolean
  12663. (define Tif (join T2 T3))
  12664. (values (If e1^ (make-cast e2^ T2 Tif)
  12665. (make-cast e3^ T3 Tif)) Tif)]
  12666. ['Any
  12667. (define Tif (meet T2 T3))
  12668. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  12669. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  12670. Tif)]
  12671. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  12672. [(HasType e1 T)
  12673. (define-values (e1^ T1) (recur e1))
  12674. (check-consistent? T1 T)
  12675. (values (make-cast e1^ T1 T) T)]
  12676. [(SetBang x e1)
  12677. (define-values (e1^ T1) (recur e1))
  12678. (define varT (dict-ref env x))
  12679. (check-consistent? T1 varT e)
  12680. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  12681. [(WhileLoop e1 e2)
  12682. (define-values (e1^ T1) (recur e1))
  12683. (check-consistent? T1 'Boolean e)
  12684. (define-values (e2^ T2) ((type-check-exp env) e2))
  12685. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  12686. \end{lstlisting}
  12687. \caption{Type checker for the \LangGrad{} language, part 2.}
  12688. \label{fig:type-check-Rgradual-2}
  12689. \end{figure}
  12690. \begin{figure}[tbp]
  12691. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12692. [(Apply e1 e2s)
  12693. (define-values (e1^ T1) (recur e1))
  12694. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  12695. (match T1
  12696. [`(,T1ps ... -> ,T1rt)
  12697. (for ([T2 T2s] [Tp T1ps])
  12698. (check-consistent? T2 Tp e))
  12699. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  12700. (make-cast e2 src tgt)))
  12701. (values (Apply e1^ e2s^^) T1rt)]
  12702. [`Any
  12703. (define e1^^ (make-cast e1^ 'Any
  12704. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  12705. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  12706. (make-cast e2 src 'Any)))
  12707. (values (Apply e1^^ e2s^^) 'Any)]
  12708. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  12709. [(Lambda params Tr e1)
  12710. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  12711. (match p
  12712. [`[,x : ,T] (values x T)]
  12713. [(? symbol? x) (values x 'Any)])))
  12714. (define-values (e1^ T1)
  12715. ((type-check-exp (append (map cons xs Ts) env)) e1))
  12716. (check-consistent? Tr T1 e)
  12717. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  12718. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  12719. [else ((super type-check-exp env) e)]
  12720. )))
  12721. \end{lstlisting}
  12722. \caption{Type checker for the \LangGrad{} language, part 3.}
  12723. \label{fig:type-check-Rgradual-3}
  12724. \end{figure}
  12725. \begin{figure}[tbp]
  12726. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12727. (define/public (join t1 t2)
  12728. (match* (t1 t2)
  12729. [('Integer 'Integer) 'Integer]
  12730. [('Boolean 'Boolean) 'Boolean]
  12731. [('Void 'Void) 'Void]
  12732. [('Any t2) t2]
  12733. [(t1 'Any) t1]
  12734. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  12735. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  12736. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  12737. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  12738. -> ,(join rt1 rt2))]))
  12739. (define/public (meet t1 t2)
  12740. (match* (t1 t2)
  12741. [('Integer 'Integer) 'Integer]
  12742. [('Boolean 'Boolean) 'Boolean]
  12743. [('Void 'Void) 'Void]
  12744. [('Any t2) 'Any]
  12745. [(t1 'Any) 'Any]
  12746. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  12747. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  12748. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  12749. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  12750. -> ,(meet rt1 rt2))]))
  12751. (define/public (make-cast e src tgt)
  12752. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  12753. (define/public (check-consistent? t1 t2 e)
  12754. (unless (consistent? t1 t2)
  12755. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  12756. (define/override (type-check-op op arg-types args e)
  12757. (match (dict-ref (operator-types) op)
  12758. [`(,param-types . ,return-type)
  12759. (for ([at arg-types] [pt param-types])
  12760. (check-consistent? at pt e))
  12761. (values return-type
  12762. (for/list ([e args] [s arg-types] [t param-types])
  12763. (make-cast e s t)))]
  12764. [else (error 'type-check-op "unrecognized ~a" op)]))
  12765. (define explicit-prim-ops
  12766. (set-union
  12767. (type-predicates)
  12768. (set 'procedure-arity 'eq?
  12769. 'vector 'vector-length 'vector-ref 'vector-set!
  12770. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  12771. (define/override (fun-def-type d)
  12772. (match d
  12773. [(Def f params rt info body)
  12774. (define ps
  12775. (for/list ([p params])
  12776. (match p
  12777. [`[,x : ,T] T]
  12778. [(? symbol?) 'Any]
  12779. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  12780. `(,@ps -> ,rt)]
  12781. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  12782. \end{lstlisting}
  12783. \caption{Auxiliary functions for type checking \LangGrad{}.}
  12784. \label{fig:type-check-Rgradual-aux}
  12785. \end{figure}
  12786. \clearpage
  12787. \section{Interpreting \LangCast{}}
  12788. \label{sec:interp-casts}
  12789. The runtime behavior of first-order casts is straightforward, that is,
  12790. casts involving simple types such as \code{Integer} and
  12791. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  12792. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  12793. puts the integer into a tagged value
  12794. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  12795. \code{Integer} is accomplished with the \code{Project} operator, that
  12796. is, by checking the value's tag and either retrieving the underlying
  12797. integer or signaling an error if it the tag is not the one for
  12798. integers (Figure~\ref{fig:apply-project}).
  12799. %
  12800. Things get more interesting for higher-order casts, that is, casts
  12801. involving function or vector types.
  12802. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  12803. Any)} to \code{(Integer -> Integer)}. When a function flows through
  12804. this cast at runtime, we can't know in general whether the function
  12805. will always return an integer.\footnote{Predicting the return value of
  12806. a function is equivalent to the halting problem, which is
  12807. undecidable.} The \LangCast{} interpreter therefore delays the checking
  12808. of the cast until the function is applied. This is accomplished by
  12809. wrapping \code{maybe-add1} in a new function that casts its parameter
  12810. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  12811. casts the return value from \code{Any} to \code{Integer}.
  12812. Turning our attention to casts involving vector types, we consider the
  12813. example in Figure~\ref{fig:map-vec-bang} that defines a
  12814. partially-typed version of \code{map-vec} whose parameter \code{v} has
  12815. type \code{(Vector Any Any)} and that updates \code{v} in place
  12816. instead of returning a new vector. So we name this function
  12817. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  12818. the type checker inserts a cast from \code{(Vector Integer Integer)}
  12819. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  12820. cast between vector types would be a build a new vector whose elements
  12821. are the result of casting each of the original elements to the
  12822. appropriate target type. However, this approach is only valid for
  12823. immutable vectors; and our vectors are mutable. In the example of
  12824. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  12825. the updates inside of \code{map-vec!} would happen to the new vector
  12826. and not the original one.
  12827. \begin{figure}[tbp]
  12828. % gradual_test_11.rkt
  12829. \begin{lstlisting}
  12830. (define (map-vec! [f : (Any -> Any)]
  12831. [v : (Vector Any Any)]) : Void
  12832. (begin
  12833. (vector-set! v 0 (f (vector-ref v 0)))
  12834. (vector-set! v 1 (f (vector-ref v 1)))))
  12835. (define (add1 x) (+ x 1))
  12836. (let ([v (vector 0 41)])
  12837. (begin (map-vec! add1 v) (vector-ref v 1)))
  12838. \end{lstlisting}
  12839. \caption{An example involving casts on vectors.}
  12840. \label{fig:map-vec-bang}
  12841. \end{figure}
  12842. Instead the interpreter needs to create a new kind of value, a
  12843. \emph{vector proxy}, that intercepts every vector operation. On a
  12844. read, the proxy reads from the underlying vector and then applies a
  12845. cast to the resulting value. On a write, the proxy casts the argument
  12846. value and then performs the write to the underlying vector. For the
  12847. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  12848. \code{0} from \code{Integer} to \code{Any}. For the first
  12849. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  12850. to \code{Integer}.
  12851. The final category of cast that we need to consider are casts between
  12852. the \code{Any} type and either a function or a vector
  12853. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  12854. in which parameter \code{v} does not have a type annotation, so it is
  12855. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  12856. type \code{(Vector Integer Integer)} so the type checker inserts a
  12857. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  12858. thought is to use \code{Inject}, but that doesn't work because
  12859. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  12860. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  12861. to \code{Any}.
  12862. \begin{figure}[tbp]
  12863. \begin{lstlisting}
  12864. (define (map-vec! [f : (Any -> Any)] v) : Void
  12865. (begin
  12866. (vector-set! v 0 (f (vector-ref v 0)))
  12867. (vector-set! v 1 (f (vector-ref v 1)))))
  12868. (define (add1 x) (+ x 1))
  12869. (let ([v (vector 0 41)])
  12870. (begin (map-vec! add1 v) (vector-ref v 1)))
  12871. \end{lstlisting}
  12872. \caption{Casting a vector to \code{Any}.}
  12873. \label{fig:map-vec-any}
  12874. \end{figure}
  12875. The \LangCast{} interpreter uses an auxiliary function named
  12876. \code{apply-cast} to cast a value from a source type to a target type,
  12877. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  12878. of the kinds of casts that we've discussed in this section.
  12879. \begin{figure}[tbp]
  12880. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12881. (define/public (apply-cast v s t)
  12882. (match* (s t)
  12883. [(t1 t2) #:when (equal? t1 t2) v]
  12884. [('Any t2)
  12885. (match t2
  12886. [`(,ts ... -> ,rt)
  12887. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  12888. (define v^ (apply-project v any->any))
  12889. (apply-cast v^ any->any `(,@ts -> ,rt))]
  12890. [`(Vector ,ts ...)
  12891. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  12892. (define v^ (apply-project v vec-any))
  12893. (apply-cast v^ vec-any `(Vector ,@ts))]
  12894. [else (apply-project v t2)])]
  12895. [(t1 'Any)
  12896. (match t1
  12897. [`(,ts ... -> ,rt)
  12898. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  12899. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  12900. (apply-inject v^ (any-tag any->any))]
  12901. [`(Vector ,ts ...)
  12902. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  12903. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  12904. (apply-inject v^ (any-tag vec-any))]
  12905. [else (apply-inject v (any-tag t1))])]
  12906. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  12907. (define x (gensym 'x))
  12908. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  12909. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  12910. (define cast-writes
  12911. (for/list ([t1 ts1] [t2 ts2])
  12912. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  12913. `(vector-proxy ,(vector v (apply vector cast-reads)
  12914. (apply vector cast-writes)))]
  12915. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  12916. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  12917. `(function ,xs ,(Cast
  12918. (Apply (Value v)
  12919. (for/list ([x xs][t1 ts1][t2 ts2])
  12920. (Cast (Var x) t2 t1)))
  12921. rt1 rt2) ())]
  12922. ))
  12923. \end{lstlisting}
  12924. \caption{The \code{apply-cast} auxiliary method.}
  12925. \label{fig:apply-cast}
  12926. \end{figure}
  12927. The interpreter for \LangCast{} is defined in
  12928. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  12929. dispatching to \code{apply-cast}. To handle the addition of vector
  12930. proxies, we update the vector primitives in \code{interp-op} using the
  12931. functions in Figure~\ref{fig:guarded-vector}.
  12932. \begin{figure}[tbp]
  12933. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12934. (define interp-Rcast_class
  12935. (class interp-Rwhile_class
  12936. (super-new)
  12937. (inherit apply-fun apply-inject apply-project)
  12938. (define/override (interp-op op)
  12939. (match op
  12940. ['vector-length guarded-vector-length]
  12941. ['vector-ref guarded-vector-ref]
  12942. ['vector-set! guarded-vector-set!]
  12943. ['any-vector-ref (lambda (v i)
  12944. (match v [`(tagged ,v^ ,tg)
  12945. (guarded-vector-ref v^ i)]))]
  12946. ['any-vector-set! (lambda (v i a)
  12947. (match v [`(tagged ,v^ ,tg)
  12948. (guarded-vector-set! v^ i a)]))]
  12949. ['any-vector-length (lambda (v)
  12950. (match v [`(tagged ,v^ ,tg)
  12951. (guarded-vector-length v^)]))]
  12952. [else (super interp-op op)]
  12953. ))
  12954. (define/override ((interp-exp env) e)
  12955. (define (recur e) ((interp-exp env) e))
  12956. (match e
  12957. [(Value v) v]
  12958. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  12959. [else ((super interp-exp env) e)]))
  12960. ))
  12961. (define (interp-Rcast p)
  12962. (send (new interp-Rcast_class) interp-program p))
  12963. \end{lstlisting}
  12964. \caption{The interpreter for \LangCast{}.}
  12965. \label{fig:interp-Rcast}
  12966. \end{figure}
  12967. \begin{figure}[tbp]
  12968. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12969. (define (guarded-vector-ref vec i)
  12970. (match vec
  12971. [`(vector-proxy ,proxy)
  12972. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  12973. (define rd (vector-ref (vector-ref proxy 1) i))
  12974. (apply-fun rd (list val) 'guarded-vector-ref)]
  12975. [else (vector-ref vec i)]))
  12976. (define (guarded-vector-set! vec i arg)
  12977. (match vec
  12978. [`(vector-proxy ,proxy)
  12979. (define wr (vector-ref (vector-ref proxy 2) i))
  12980. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  12981. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  12982. [else (vector-set! vec i arg)]))
  12983. (define (guarded-vector-length vec)
  12984. (match vec
  12985. [`(vector-proxy ,proxy)
  12986. (guarded-vector-length (vector-ref proxy 0))]
  12987. [else (vector-length vec)]))
  12988. \end{lstlisting}
  12989. \caption{The guarded-vector auxiliary functions.}
  12990. \label{fig:guarded-vector}
  12991. \end{figure}
  12992. \section{Lower Casts}
  12993. \label{sec:lower-casts}
  12994. The next step in the journey towards x86 is the \code{lower-casts}
  12995. pass that translates the casts in \LangCast{} to the lower-level
  12996. \code{Inject} and \code{Project} operators and a new operator for
  12997. creating vector proxies, extending the \LangLoop{} language to create
  12998. \LangProxy{}. We recommend creating an auxiliary function named
  12999. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  13000. and a target type, and translates it to expression in \LangProxy{} that has
  13001. the same behavior as casting the expression from the source to the
  13002. target type in the interpreter.
  13003. The \code{lower-cast} function can follow a code structure similar to
  13004. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  13005. the interpreter for \LangCast{} because it must handle the same cases as
  13006. \code{apply-cast} and it needs to mimic the behavior of
  13007. \code{apply-cast}. The most interesting cases are those concerning the
  13008. casts between two vector types and between two function types.
  13009. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  13010. type to another vector type is accomplished by creating a proxy that
  13011. intercepts the operations on the underlying vector. Here we make the
  13012. creation of the proxy explicit with the \code{vector-proxy} primitive
  13013. operation. It takes three arguments, the first is an expression for
  13014. the vector, the second is a vector of functions for casting an element
  13015. that is being read from the vector, and the third is a vector of
  13016. functions for casting an element that is being written to the vector.
  13017. You can create the functions using \code{Lambda}. Also, as we shall
  13018. see in the next section, we need to differentiate these vectors from
  13019. the user-created ones, so we recommend using a new primitive operator
  13020. named \code{raw-vector} instead of \code{vector} to create these
  13021. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  13022. the output of \code{lower-casts} on the example in
  13023. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  13024. integers to a vector of \code{Any}.
  13025. \begin{figure}[tbp]
  13026. \begin{lstlisting}
  13027. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  13028. (begin
  13029. (vector-set! v 0 (f (vector-ref v 0)))
  13030. (vector-set! v 1 (f (vector-ref v 1)))))
  13031. (define (add1 [x : Any]) : Any
  13032. (inject (+ (project x Integer) 1) Integer))
  13033. (let ([v (vector 0 41)])
  13034. (begin
  13035. (map-vec! add1 (vector-proxy v
  13036. (raw-vector (lambda: ([x9 : Integer]) : Any
  13037. (inject x9 Integer))
  13038. (lambda: ([x9 : Integer]) : Any
  13039. (inject x9 Integer)))
  13040. (raw-vector (lambda: ([x9 : Any]) : Integer
  13041. (project x9 Integer))
  13042. (lambda: ([x9 : Any]) : Integer
  13043. (project x9 Integer)))))
  13044. (vector-ref v 1)))
  13045. \end{lstlisting}
  13046. \caption{Output of \code{lower-casts} on the example in
  13047. Figure~\ref{fig:map-vec-bang}.}
  13048. \label{fig:map-vec-bang-lower-cast}
  13049. \end{figure}
  13050. A cast from one function type to another function type is accomplished
  13051. by generating a \code{Lambda} whose parameter and return types match
  13052. the target function type. The body of the \code{Lambda} should cast
  13053. the parameters from the target type to the source type (yes,
  13054. backwards! functions are contravariant\index{subject}{contravariant} in the
  13055. parameters), then call the underlying function, and finally cast the
  13056. result from the source return type to the target return type.
  13057. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  13058. \code{lower-casts} pass on the \code{map-vec} example in
  13059. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  13060. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  13061. \begin{figure}[tbp]
  13062. \begin{lstlisting}
  13063. (define (map-vec [f : (Integer -> Integer)]
  13064. [v : (Vector Integer Integer)])
  13065. : (Vector Integer Integer)
  13066. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13067. (define (add1 [x : Any]) : Any
  13068. (inject (+ (project x Integer) 1) Integer))
  13069. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  13070. (project (add1 (inject x9 Integer)) Integer))
  13071. (vector 0 41)) 1)
  13072. \end{lstlisting}
  13073. \caption{Output of \code{lower-casts} on the example in
  13074. Figure~\ref{fig:gradual-map-vec}.}
  13075. \label{fig:map-vec-lower-cast}
  13076. \end{figure}
  13077. \section{Differentiate Proxies}
  13078. \label{sec:differentiate-proxies}
  13079. So far the job of differentiating vectors and vector proxies has been
  13080. the job of the interpreter. For example, the interpreter for \LangCast{}
  13081. implements \code{vector-ref} using the \code{guarded-vector-ref}
  13082. function in Figure~\ref{fig:guarded-vector}. In the
  13083. \code{differentiate-proxies} pass we shift this responsibility to the
  13084. generated code.
  13085. We begin by designing the output language $R^p_8$. In
  13086. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  13087. proxies. In $R^p_8$ we return the \code{Vector} type to
  13088. its original meaning, as the type of real vectors, and we introduce a
  13089. new type, \code{PVector}, whose values can be either real vectors or
  13090. vector proxies. This new type comes with a suite of new primitive
  13091. operations for creating and using values of type \code{PVector}. We
  13092. don't need to introduce a new type to represent vector proxies. A
  13093. proxy is represented by a vector containing three things: 1) the
  13094. underlying vector, 2) a vector of functions for casting elements that
  13095. are read from the vector, and 3) a vector of functions for casting
  13096. values to be written to the vector. So we define the following
  13097. abbreviation for the type of a vector proxy:
  13098. \[
  13099. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  13100. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  13101. \to (\key{PVector}~ T' \ldots)
  13102. \]
  13103. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  13104. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  13105. %
  13106. Next we describe each of the new primitive operations.
  13107. \begin{description}
  13108. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  13109. (\key{PVector} $T \ldots$)]\ \\
  13110. %
  13111. This operation brands a vector as a value of the \code{PVector} type.
  13112. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  13113. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  13114. %
  13115. This operation brands a vector proxy as value of the \code{PVector} type.
  13116. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  13117. \code{Boolean}] \ \\
  13118. %
  13119. returns true if the value is a vector proxy and false if it is a
  13120. real vector.
  13121. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  13122. (\key{Vector} $T \ldots$)]\ \\
  13123. %
  13124. Assuming that the input is a vector (and not a proxy), this
  13125. operation returns the vector.
  13126. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  13127. $\to$ \code{Boolean}]\ \\
  13128. %
  13129. Given a vector proxy, this operation returns the length of the
  13130. underlying vector.
  13131. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  13132. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  13133. %
  13134. Given a vector proxy, this operation returns the $i$th element of
  13135. the underlying vector.
  13136. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  13137. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  13138. proxy, this operation writes a value to the $i$th element of the
  13139. underlying vector.
  13140. \end{description}
  13141. Now to discuss the translation that differentiates vectors from
  13142. proxies. First, every type annotation in the program must be
  13143. translated (recursively) to replace \code{Vector} with \code{PVector}.
  13144. Next, we must insert uses of \code{PVector} operations in the
  13145. appropriate places. For example, we wrap every vector creation with an
  13146. \code{inject-vector}.
  13147. \begin{lstlisting}
  13148. (vector |$e_1 \ldots e_n$|)
  13149. |$\Rightarrow$|
  13150. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  13151. \end{lstlisting}
  13152. The \code{raw-vector} operator that we introduced in the previous
  13153. section does not get injected.
  13154. \begin{lstlisting}
  13155. (raw-vector |$e_1 \ldots e_n$|)
  13156. |$\Rightarrow$|
  13157. (vector |$e'_1 \ldots e'_n$|)
  13158. \end{lstlisting}
  13159. The \code{vector-proxy} primitive translates as follows.
  13160. \begin{lstlisting}
  13161. (vector-proxy |$e_1~e_2~e_3$|)
  13162. |$\Rightarrow$|
  13163. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  13164. \end{lstlisting}
  13165. We translate the vector operations into conditional expressions that
  13166. check whether the value is a proxy and then dispatch to either the
  13167. appropriate proxy vector operation or the regular vector operation.
  13168. For example, the following is the translation for \code{vector-ref}.
  13169. \begin{lstlisting}
  13170. (vector-ref |$e_1$| |$i$|)
  13171. |$\Rightarrow$|
  13172. (let ([|$v~e_1$|])
  13173. (if (proxy? |$v$|)
  13174. (proxy-vector-ref |$v$| |$i$|)
  13175. (vector-ref (project-vector |$v$|) |$i$|)
  13176. \end{lstlisting}
  13177. Note in the case of a real vector, we must apply \code{project-vector}
  13178. before the \code{vector-ref}.
  13179. \section{Reveal Casts}
  13180. \label{sec:reveal-casts-gradual}
  13181. Recall that the \code{reveal-casts} pass
  13182. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  13183. \code{Inject} and \code{Project} into lower-level operations. In
  13184. particular, \code{Project} turns into a conditional expression that
  13185. inspects the tag and retrieves the underlying value. Here we need to
  13186. augment the translation of \code{Project} to handle the situation when
  13187. the target type is \code{PVector}. Instead of using
  13188. \code{vector-length} we need to use \code{proxy-vector-length}.
  13189. \begin{lstlisting}
  13190. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  13191. |$\Rightarrow$|
  13192. (let |$\itm{tmp}$| |$e'$|
  13193. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  13194. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  13195. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  13196. (exit)))
  13197. \end{lstlisting}
  13198. \section{Closure Conversion}
  13199. \label{sec:closure-conversion-gradual}
  13200. The closure conversion pass only requires one minor adjustment. The
  13201. auxiliary function that translates type annotations needs to be
  13202. updated to handle the \code{PVector} type.
  13203. \section{Explicate Control}
  13204. \label{sec:explicate-control-gradual}
  13205. Update the \code{explicate-control} pass to handle the new primitive
  13206. operations on the \code{PVector} type.
  13207. \section{Select Instructions}
  13208. \label{sec:select-instructions-gradual}
  13209. Recall that the \code{select-instructions} pass is responsible for
  13210. lowering the primitive operations into x86 instructions. So we need
  13211. to translate the new \code{PVector} operations to x86. To do so, the
  13212. first question we need to answer is how will we differentiate the two
  13213. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  13214. We need just one bit to accomplish this, and use the bit in position
  13215. $57$ of the 64-bit tag at the front of every vector (see
  13216. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  13217. for \code{inject-vector} we leave it that way.
  13218. \begin{lstlisting}
  13219. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  13220. |$\Rightarrow$|
  13221. movq |$e'_1$|, |$\itm{lhs'}$|
  13222. \end{lstlisting}
  13223. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  13224. \begin{lstlisting}
  13225. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  13226. |$\Rightarrow$|
  13227. movq |$e'_1$|, %r11
  13228. movq |$(1 << 57)$|, %rax
  13229. orq 0(%r11), %rax
  13230. movq %rax, 0(%r11)
  13231. movq %r11, |$\itm{lhs'}$|
  13232. \end{lstlisting}
  13233. The \code{proxy?} operation consumes the information so carefully
  13234. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  13235. isolates the $57$th bit to tell whether the value is a real vector or
  13236. a proxy.
  13237. \begin{lstlisting}
  13238. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  13239. |$\Rightarrow$|
  13240. movq |$e_1'$|, %r11
  13241. movq 0(%r11), %rax
  13242. sarq $57, %rax
  13243. andq $1, %rax
  13244. movq %rax, |$\itm{lhs'}$|
  13245. \end{lstlisting}
  13246. The \code{project-vector} operation is straightforward to translate,
  13247. so we leave it up to the reader.
  13248. Regarding the \code{proxy-vector} operations, the runtime provides
  13249. procedures that implement them (they are recursive functions!) so
  13250. here we simply need to translate these vector operations into the
  13251. appropriate function call. For example, here is the translation for
  13252. \code{proxy-vector-ref}.
  13253. \begin{lstlisting}
  13254. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  13255. |$\Rightarrow$|
  13256. movq |$e_1'$|, %rdi
  13257. movq |$e_2'$|, %rsi
  13258. callq proxy_vector_ref
  13259. movq %rax, |$\itm{lhs'}$|
  13260. \end{lstlisting}
  13261. We have another batch of vector operations to deal with, those for the
  13262. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  13263. \code{any-vector-ref} when there is a \code{vector-ref} on something
  13264. of type \code{Any}, and similarly for \code{any-vector-set!} and
  13265. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  13266. Section~\ref{sec:select-Rany} we selected instructions for these
  13267. operations based on the idea that the underlying value was a real
  13268. vector. But in the current setting, the underlying value is of type
  13269. \code{PVector}. So \code{any-vector-ref} can be translates to
  13270. pseudo-x86 as follows. We begin by projecting the underlying value out
  13271. of the tagged value and then call the \code{proxy\_vector\_ref}
  13272. procedure in the runtime.
  13273. \begin{lstlisting}
  13274. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  13275. movq |$\neg 111$|, %rdi
  13276. andq |$e_1'$|, %rdi
  13277. movq |$e_2'$|, %rsi
  13278. callq proxy_vector_ref
  13279. movq %rax, |$\itm{lhs'}$|
  13280. \end{lstlisting}
  13281. The \code{any-vector-set!} and \code{any-vector-length} operators can
  13282. be translated in a similar way.
  13283. \begin{exercise}\normalfont
  13284. Implement a compiler for the gradually-typed \LangGrad{} language by
  13285. extending and adapting your compiler for \LangLoop{}. Create 10 new
  13286. partially-typed test programs. In addition to testing with these
  13287. new programs, also test your compiler on all the tests for \LangLoop{}
  13288. and tests for \LangDyn{}. Sometimes you may get a type checking error
  13289. on the \LangDyn{} programs but you can adapt them by inserting
  13290. a cast to the \code{Any} type around each subexpression
  13291. causing a type error. While \LangDyn{} doesn't have explicit casts,
  13292. you can induce one by wrapping the subexpression \code{e}
  13293. with a call to an un-annotated identity function, like this:
  13294. \code{((lambda (x) x) e)}.
  13295. \end{exercise}
  13296. \begin{figure}[p]
  13297. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13298. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  13299. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  13300. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  13301. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  13302. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  13303. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  13304. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  13305. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  13306. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  13307. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  13308. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  13309. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  13310. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  13311. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  13312. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13313. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13314. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13315. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13316. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13317. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13318. \path[->,bend right=15] (Rgradual) edge [above] node
  13319. {\ttfamily\footnotesize type-check} (Rgradualp);
  13320. \path[->,bend right=15] (Rgradualp) edge [above] node
  13321. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  13322. \path[->,bend right=15] (Rwhilepp) edge [right] node
  13323. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  13324. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  13325. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  13326. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  13327. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  13328. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  13329. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  13330. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  13331. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  13332. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  13333. {\ttfamily\footnotesize convert-assignments} (F1-1);
  13334. \path[->,bend left=15] (F1-1) edge [below] node
  13335. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  13336. \path[->,bend right=15] (F1-2) edge [above] node
  13337. {\ttfamily\footnotesize limit-fun.} (F1-3);
  13338. \path[->,bend right=15] (F1-3) edge [above] node
  13339. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  13340. \path[->,bend right=15] (F1-4) edge [above] node
  13341. {\ttfamily\footnotesize remove-complex.} (F1-5);
  13342. \path[->,bend right=15] (F1-5) edge [right] node
  13343. {\ttfamily\footnotesize explicate-control} (C3-2);
  13344. \path[->,bend left=15] (C3-2) edge [left] node
  13345. {\ttfamily\footnotesize select-instr.} (x86-2);
  13346. \path[->,bend right=15] (x86-2) edge [left] node
  13347. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  13348. \path[->,bend right=15] (x86-2-1) edge [below] node
  13349. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  13350. \path[->,bend right=15] (x86-2-2) edge [left] node
  13351. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  13352. \path[->,bend left=15] (x86-3) edge [above] node
  13353. {\ttfamily\footnotesize patch-instr.} (x86-4);
  13354. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  13355. \end{tikzpicture}
  13356. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  13357. \label{fig:Rgradual-passes}
  13358. \end{figure}
  13359. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  13360. for the compilation of \LangGrad{}.
  13361. \section{Further Reading}
  13362. This chapter just scratches the surface of gradual typing. The basic
  13363. approach described here is missing two key ingredients that one would
  13364. want in a implementation of gradual typing: blame
  13365. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  13366. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  13367. problem addressed by blame tracking is that when a cast on a
  13368. higher-order value fails, it often does so at a point in the program
  13369. that is far removed from the original cast. Blame tracking is a
  13370. technique for propagating extra information through casts and proxies
  13371. so that when a cast fails, the error message can point back to the
  13372. original location of the cast in the source program.
  13373. The problem addressed by space-efficient casts also relates to
  13374. higher-order casts. It turns out that in partially typed programs, a
  13375. function or vector can flow through very-many casts at runtime. With
  13376. the approach described in this chapter, each cast adds another
  13377. \code{lambda} wrapper or a vector proxy. Not only does this take up
  13378. considerable space, but it also makes the function calls and vector
  13379. operations slow. For example, a partially-typed version of quicksort
  13380. could, in the worst case, build a chain of proxies of length $O(n)$
  13381. around the vector, changing the overall time complexity of the
  13382. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  13383. solution to this problem by representing casts using the coercion
  13384. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  13385. long chains of proxies by compressing them into a concise normal
  13386. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  13387. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  13388. the Grift compiler.
  13389. \begin{center}
  13390. \url{https://github.com/Gradual-Typing/Grift}
  13391. \end{center}
  13392. There are also interesting interactions between gradual typing and
  13393. other language features, such as parametetric polymorphism,
  13394. information-flow types, and type inference, to name a few. We
  13395. recommend the reader to the online gradual typing bibliography:
  13396. \begin{center}
  13397. \url{http://samth.github.io/gradual-typing-bib/}
  13398. \end{center}
  13399. % TODO: challenge problem:
  13400. % type analysis and type specialization?
  13401. % coercions?
  13402. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13403. \chapter{Parametric Polymorphism}
  13404. \label{ch:Rpoly}
  13405. \index{subject}{parametric polymorphism}
  13406. \index{subject}{generics}
  13407. This chapter studies the compilation of parametric
  13408. polymorphism\index{subject}{parametric polymorphism}
  13409. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  13410. Racket. Parametric polymorphism enables improved code reuse by
  13411. parameterizing functions and data structures with respect to the types
  13412. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  13413. revisits the \code{map-vec} example but this time gives it a more
  13414. fitting type. This \code{map-vec} function is parameterized with
  13415. respect to the element type of the vector. The type of \code{map-vec}
  13416. is the following polymorphic type as specified by the \code{All} and
  13417. the type parameter \code{a}.
  13418. \begin{lstlisting}
  13419. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  13420. \end{lstlisting}
  13421. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  13422. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  13423. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  13424. \code{a}, but we could have just as well applied \code{map-vec} to a
  13425. vector of Booleans (and a function on Booleans).
  13426. \begin{figure}[tbp]
  13427. % poly_test_2.rkt
  13428. \begin{lstlisting}
  13429. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  13430. (define (map-vec f v)
  13431. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13432. (define (add1 [x : Integer]) : Integer (+ x 1))
  13433. (vector-ref (map-vec add1 (vector 0 41)) 1)
  13434. \end{lstlisting}
  13435. \caption{The \code{map-vec} example using parametric polymorphism.}
  13436. \label{fig:map-vec-poly}
  13437. \end{figure}
  13438. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  13439. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  13440. syntax. We add a second form for function definitions in which a type
  13441. declaration comes before the \code{define}. In the abstract syntax,
  13442. the return type in the \code{Def} is \code{Any}, but that should be
  13443. ignored in favor of the return type in the type declaration. (The
  13444. \code{Any} comes from using the same parser as in
  13445. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  13446. enables the use of an \code{All} type for a function, thereby making
  13447. it polymorphic. The grammar for types is extended to include
  13448. polymorphic types and type variables.
  13449. \begin{figure}[tp]
  13450. \centering
  13451. \fbox{
  13452. \begin{minipage}{0.96\textwidth}
  13453. \small
  13454. \[
  13455. \begin{array}{lcl}
  13456. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  13457. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  13458. &\MID& \LP\key{:}~\Var~\Type\RP \\
  13459. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  13460. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  13461. \end{array}
  13462. \]
  13463. \end{minipage}
  13464. }
  13465. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  13466. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  13467. \label{fig:Rpoly-concrete-syntax}
  13468. \end{figure}
  13469. \begin{figure}[tp]
  13470. \centering
  13471. \fbox{
  13472. \begin{minipage}{0.96\textwidth}
  13473. \small
  13474. \[
  13475. \begin{array}{lcl}
  13476. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  13477. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  13478. &\MID& \DECL{\Var}{\Type} \\
  13479. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  13480. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13481. \end{array}
  13482. \]
  13483. \end{minipage}
  13484. }
  13485. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  13486. (Figure~\ref{fig:Rwhile-syntax}).}
  13487. \label{fig:Rpoly-syntax}
  13488. \end{figure}
  13489. By including polymorphic types in the $\Type$ non-terminal we choose
  13490. to make them first-class which has interesting repercussions on the
  13491. compiler. Many languages with polymorphism, such as
  13492. C++~\citep{stroustrup88:_param_types} and Standard
  13493. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  13494. it is useful to see an example of first-class polymorphism. In
  13495. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  13496. whose parameter is a polymorphic function. The occurrence of a
  13497. polymorphic type underneath a function type is enabled by the normal
  13498. recursive structure of the grammar for $\Type$ and the categorization
  13499. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  13500. applies the polymorphic function to a Boolean and to an integer.
  13501. \begin{figure}[tbp]
  13502. \begin{lstlisting}
  13503. (: apply-twice ((All (b) (b -> b)) -> Integer))
  13504. (define (apply-twice f)
  13505. (if (f #t) (f 42) (f 777)))
  13506. (: id (All (a) (a -> a)))
  13507. (define (id x) x)
  13508. (apply-twice id)
  13509. \end{lstlisting}
  13510. \caption{An example illustrating first-class polymorphism.}
  13511. \label{fig:apply-twice}
  13512. \end{figure}
  13513. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  13514. three new responsibilities (compared to \LangLoop{}). The type checking of
  13515. function application is extended to handle the case where the operator
  13516. expression is a polymorphic function. In that case the type arguments
  13517. are deduced by matching the type of the parameters with the types of
  13518. the arguments.
  13519. %
  13520. The \code{match-types} auxiliary function carries out this deduction
  13521. by recursively descending through a parameter type \code{pt} and the
  13522. corresponding argument type \code{at}, making sure that they are equal
  13523. except when there is a type parameter on the left (in the parameter
  13524. type). If it's the first time that the type parameter has been
  13525. encountered, then the algorithm deduces an association of the type
  13526. parameter to the corresponding type on the right (in the argument
  13527. type). If it's not the first time that the type parameter has been
  13528. encountered, the algorithm looks up its deduced type and makes sure
  13529. that it is equal to the type on the right.
  13530. %
  13531. Once the type arguments are deduced, the operator expression is
  13532. wrapped in an \code{Inst} AST node (for instantiate) that records the
  13533. type of the operator, but more importantly, records the deduced type
  13534. arguments. The return type of the application is the return type of
  13535. the polymorphic function, but with the type parameters replaced by the
  13536. deduced type arguments, using the \code{subst-type} function.
  13537. The second responsibility of the type checker is extending the
  13538. function \code{type-equal?} to handle the \code{All} type. This is
  13539. not quite a simple as equal on other types, such as function and
  13540. vector types, because two polymorphic types can be syntactically
  13541. different even though they are equivalent types. For example,
  13542. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  13543. Two polymorphic types should be considered equal if they differ only
  13544. in the choice of the names of the type parameters. The
  13545. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  13546. renames the type parameters of the first type to match the type
  13547. parameters of the second type.
  13548. The third responsibility of the type checker is making sure that only
  13549. defined type variables appear in type annotations. The
  13550. \code{check-well-formed} function defined in
  13551. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  13552. sure that each type variable has been defined.
  13553. The output language of the type checker is \LangInst{}, defined in
  13554. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  13555. declaration and polymorphic function into a single definition, using
  13556. the \code{Poly} form, to make polymorphic functions more convenient to
  13557. process in next pass of the compiler.
  13558. \begin{figure}[tp]
  13559. \centering
  13560. \fbox{
  13561. \begin{minipage}{0.96\textwidth}
  13562. \small
  13563. \[
  13564. \begin{array}{lcl}
  13565. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  13566. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  13567. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  13568. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  13569. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13570. \end{array}
  13571. \]
  13572. \end{minipage}
  13573. }
  13574. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  13575. (Figure~\ref{fig:Rwhile-syntax}).}
  13576. \label{fig:Rpoly-prime-syntax}
  13577. \end{figure}
  13578. The output of the type checker on the polymorphic \code{map-vec}
  13579. example is listed in Figure~\ref{fig:map-vec-type-check}.
  13580. \begin{figure}[tbp]
  13581. % poly_test_2.rkt
  13582. \begin{lstlisting}
  13583. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  13584. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  13585. (define (add1 [x : Integer]) : Integer (+ x 1))
  13586. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  13587. (Integer))
  13588. add1 (vector 0 41)) 1)
  13589. \end{lstlisting}
  13590. \caption{Output of the type checker on the \code{map-vec} example.}
  13591. \label{fig:map-vec-type-check}
  13592. \end{figure}
  13593. \begin{figure}[tbp]
  13594. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13595. (define type-check-poly-class
  13596. (class type-check-Rwhile-class
  13597. (super-new)
  13598. (inherit check-type-equal?)
  13599. (define/override (type-check-apply env e1 es)
  13600. (define-values (e^ ty) ((type-check-exp env) e1))
  13601. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  13602. ((type-check-exp env) e)))
  13603. (match ty
  13604. [`(,ty^* ... -> ,rt)
  13605. (for ([arg-ty ty*] [param-ty ty^*])
  13606. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  13607. (values e^ es^ rt)]
  13608. [`(All ,xs (,tys ... -> ,rt))
  13609. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  13610. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  13611. (match-types env^^ param-ty arg-ty)))
  13612. (define targs
  13613. (for/list ([x xs])
  13614. (match (dict-ref env^^ x (lambda () #f))
  13615. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  13616. x (Apply e1 es))]
  13617. [ty ty])))
  13618. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  13619. [else (error 'type-check "expected a function, not ~a" ty)]))
  13620. (define/override ((type-check-exp env) e)
  13621. (match e
  13622. [(Lambda `([,xs : ,Ts] ...) rT body)
  13623. (for ([T Ts]) ((check-well-formed env) T))
  13624. ((check-well-formed env) rT)
  13625. ((super type-check-exp env) e)]
  13626. [(HasType e1 ty)
  13627. ((check-well-formed env) ty)
  13628. ((super type-check-exp env) e)]
  13629. [else ((super type-check-exp env) e)]))
  13630. (define/override ((type-check-def env) d)
  13631. (verbose 'type-check "poly/def" d)
  13632. (match d
  13633. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  13634. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  13635. (for ([p ps]) ((check-well-formed ts-env) p))
  13636. ((check-well-formed ts-env) rt)
  13637. (define new-env (append ts-env (map cons xs ps) env))
  13638. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13639. (check-type-equal? ty^ rt body)
  13640. (Generic ts (Def f p:t* rt info body^))]
  13641. [else ((super type-check-def env) d)]))
  13642. (define/override (type-check-program p)
  13643. (match p
  13644. [(Program info body)
  13645. (type-check-program (ProgramDefsExp info '() body))]
  13646. [(ProgramDefsExp info ds body)
  13647. (define ds^ (combine-decls-defs ds))
  13648. (define new-env (for/list ([d ds^])
  13649. (cons (def-name d) (fun-def-type d))))
  13650. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  13651. (define-values (body^ ty) ((type-check-exp new-env) body))
  13652. (check-type-equal? ty 'Integer body)
  13653. (ProgramDefsExp info ds^^ body^)]))
  13654. ))
  13655. \end{lstlisting}
  13656. \caption{Type checker for the \LangPoly{} language.}
  13657. \label{fig:type-check-Rvar0}
  13658. \end{figure}
  13659. \begin{figure}[tbp]
  13660. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13661. (define/override (type-equal? t1 t2)
  13662. (match* (t1 t2)
  13663. [(`(All ,xs ,T1) `(All ,ys ,T2))
  13664. (define env (map cons xs ys))
  13665. (type-equal? (subst-type env T1) T2)]
  13666. [(other wise)
  13667. (super type-equal? t1 t2)]))
  13668. (define/public (match-types env pt at)
  13669. (match* (pt at)
  13670. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  13671. [('Void 'Void) env] [('Any 'Any) env]
  13672. [(`(Vector ,pts ...) `(Vector ,ats ...))
  13673. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  13674. (match-types env^ pt1 at1))]
  13675. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  13676. (define env^ (match-types env prt art))
  13677. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  13678. (match-types env^^ pt1 at1))]
  13679. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  13680. (define env^ (append (map cons pxs axs) env))
  13681. (match-types env^ pt1 at1)]
  13682. [((? symbol? x) at)
  13683. (match (dict-ref env x (lambda () #f))
  13684. [#f (error 'type-check "undefined type variable ~a" x)]
  13685. ['Type (cons (cons x at) env)]
  13686. [t^ (check-type-equal? at t^ 'matching) env])]
  13687. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  13688. (define/public (subst-type env pt)
  13689. (match pt
  13690. ['Integer 'Integer] ['Boolean 'Boolean]
  13691. ['Void 'Void] ['Any 'Any]
  13692. [`(Vector ,ts ...)
  13693. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  13694. [`(,ts ... -> ,rt)
  13695. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  13696. [`(All ,xs ,t)
  13697. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  13698. [(? symbol? x) (dict-ref env x)]
  13699. [else (error 'type-check "expected a type not ~a" pt)]))
  13700. (define/public (combine-decls-defs ds)
  13701. (match ds
  13702. ['() '()]
  13703. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  13704. (unless (equal? name f)
  13705. (error 'type-check "name mismatch, ~a != ~a" name f))
  13706. (match type
  13707. [`(All ,xs (,ps ... -> ,rt))
  13708. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  13709. (cons (Generic xs (Def name params^ rt info body))
  13710. (combine-decls-defs ds^))]
  13711. [`(,ps ... -> ,rt)
  13712. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  13713. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  13714. [else (error 'type-check "expected a function type, not ~a" type) ])]
  13715. [`(,(Def f params rt info body) . ,ds^)
  13716. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  13717. \end{lstlisting}
  13718. \caption{Auxiliary functions for type checking \LangPoly{}.}
  13719. \label{fig:type-check-Rvar0-aux}
  13720. \end{figure}
  13721. \begin{figure}[tbp]
  13722. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  13723. (define/public ((check-well-formed env) ty)
  13724. (match ty
  13725. ['Integer (void)]
  13726. ['Boolean (void)]
  13727. ['Void (void)]
  13728. [(? symbol? a)
  13729. (match (dict-ref env a (lambda () #f))
  13730. ['Type (void)]
  13731. [else (error 'type-check "undefined type variable ~a" a)])]
  13732. [`(Vector ,ts ...)
  13733. (for ([t ts]) ((check-well-formed env) t))]
  13734. [`(,ts ... -> ,t)
  13735. (for ([t ts]) ((check-well-formed env) t))
  13736. ((check-well-formed env) t)]
  13737. [`(All ,xs ,t)
  13738. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  13739. ((check-well-formed env^) t)]
  13740. [else (error 'type-check "unrecognized type ~a" ty)]))
  13741. \end{lstlisting}
  13742. \caption{Well-formed types.}
  13743. \label{fig:well-formed-types}
  13744. \end{figure}
  13745. % TODO: interpreter for R'_10
  13746. \section{Compiling Polymorphism}
  13747. \label{sec:compiling-poly}
  13748. Broadly speaking, there are four approaches to compiling parametric
  13749. polymorphism, which we describe below.
  13750. \begin{description}
  13751. \item[Monomorphization] generates a different version of a polymorphic
  13752. function for each set of type arguments that it is used with,
  13753. producing type-specialized code. This approach results in the most
  13754. efficient code but requires whole-program compilation (no separate
  13755. compilation) and increases code size. For our current purposes
  13756. monomorphization is a non-starter because, with first-class
  13757. polymorphism, it is sometimes not possible to determine which
  13758. generic functions are used with which type arguments during
  13759. compilation. (It can be done at runtime, with just-in-time
  13760. compilation.) This approach is used to compile C++
  13761. templates~\citep{stroustrup88:_param_types} and polymorphic
  13762. functions in NESL~\citep{Blelloch:1993aa} and
  13763. ML~\citep{Weeks:2006aa}.
  13764. \item[Uniform representation] generates one version of each
  13765. polymorphic function but requires all values have a common ``boxed''
  13766. format, such as the tagged values of type \code{Any} in
  13767. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  13768. similarly to code in a dynamically typed language (like \LangDyn{}),
  13769. in which primitive operators require their arguments to be projected
  13770. from \code{Any} and their results are injected into \code{Any}. (In
  13771. object-oriented languages, the projection is accomplished via
  13772. virtual method dispatch.) The uniform representation approach is
  13773. compatible with separate compilation and with first-class
  13774. polymorphism. However, it produces the least-efficient code because
  13775. it introduces overhead in the entire program, including
  13776. non-polymorphic code. This approach is used in implementations of
  13777. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  13778. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  13779. Java~\citep{Bracha:1998fk}.
  13780. \item[Mixed representation] generates one version of each polymorphic
  13781. function, using a boxed representation for type
  13782. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  13783. and conversions are performed at the boundaries between monomorphic
  13784. and polymorphic (e.g. when a polymorphic function is instantiated
  13785. and called). This approach is compatible with separate compilation
  13786. and first-class polymorphism and maintains the efficiency of
  13787. monomorphic code. The tradeoff is increased overhead at the boundary
  13788. between monomorphic and polymorphic code. This approach is used in
  13789. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  13790. Java 5 with the addition of autoboxing.
  13791. \item[Type passing] uses the unboxed representation in both
  13792. monomorphic and polymorphic code. Each polymorphic function is
  13793. compiled to a single function with extra parameters that describe
  13794. the type arguments. The type information is used by the generated
  13795. code to know how to access the unboxed values at runtime. This
  13796. approach is used in implementation of the Napier88
  13797. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  13798. passing is compatible with separate compilation and first-class
  13799. polymorphism and maintains the efficiency for monomorphic
  13800. code. There is runtime overhead in polymorphic code from dispatching
  13801. on type information.
  13802. \end{description}
  13803. In this chapter we use the mixed representation approach, partly
  13804. because of its favorable attributes, and partly because it is
  13805. straightforward to implement using the tools that we have already
  13806. built to support gradual typing. To compile polymorphic functions, we
  13807. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  13808. \LangCast{}.
  13809. \section{Erase Types}
  13810. \label{sec:erase-types}
  13811. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  13812. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  13813. shows the output of the \code{erase-types} pass on the polymorphic
  13814. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  13815. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  13816. \code{All} types are removed from the type of \code{map-vec}.
  13817. \begin{figure}[tbp]
  13818. \begin{lstlisting}
  13819. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  13820. : (Vector Any Any)
  13821. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13822. (define (add1 [x : Integer]) : Integer (+ x 1))
  13823. (vector-ref ((cast map-vec
  13824. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  13825. ((Integer -> Integer) (Vector Integer Integer)
  13826. -> (Vector Integer Integer)))
  13827. add1 (vector 0 41)) 1)
  13828. \end{lstlisting}
  13829. \caption{The polymorphic \code{map-vec} example after type erasure.}
  13830. \label{fig:map-vec-erase}
  13831. \end{figure}
  13832. This process of type erasure creates a challenge at points of
  13833. instantiation. For example, consider the instantiation of
  13834. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  13835. The type of \code{map-vec} is
  13836. \begin{lstlisting}
  13837. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  13838. \end{lstlisting}
  13839. and it is instantiated to
  13840. \begin{lstlisting}
  13841. ((Integer -> Integer) (Vector Integer Integer)
  13842. -> (Vector Integer Integer))
  13843. \end{lstlisting}
  13844. After erasure, the type of \code{map-vec} is
  13845. \begin{lstlisting}
  13846. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  13847. \end{lstlisting}
  13848. but we need to convert it to the instantiated type. This is easy to
  13849. do in the target language \LangCast{} with a single \code{cast}. In
  13850. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  13851. has been compiled to a \code{cast} from the type of \code{map-vec} to
  13852. the instantiated type. The source and target type of a cast must be
  13853. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  13854. because both the source and target are obtained from the same
  13855. polymorphic type of \code{map-vec}, replacing the type parameters with
  13856. \code{Any} in the former and with the deduced type arguments in the
  13857. later. (Recall that the \code{Any} type is consistent with any type.)
  13858. To implement the \code{erase-types} pass, we recommend defining a
  13859. recursive auxiliary function named \code{erase-type} that applies the
  13860. following two transformations. It replaces type variables with
  13861. \code{Any}
  13862. \begin{lstlisting}
  13863. |$x$|
  13864. |$\Rightarrow$|
  13865. Any
  13866. \end{lstlisting}
  13867. and it removes the polymorphic \code{All} types.
  13868. \begin{lstlisting}
  13869. (All |$xs$| |$T_1$|)
  13870. |$\Rightarrow$|
  13871. |$T'_1$|
  13872. \end{lstlisting}
  13873. Apply the \code{erase-type} function to all of the type annotations in
  13874. the program.
  13875. Regarding the translation of expressions, the case for \code{Inst} is
  13876. the interesting one. We translate it into a \code{Cast}, as shown
  13877. below. The type of the subexpression $e$ is the polymorphic type
  13878. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  13879. $T$, the type $T'$. The target type $T''$ is the result of
  13880. substituting the arguments types $ts$ for the type parameters $xs$ in
  13881. $T$ followed by doing type erasure.
  13882. \begin{lstlisting}
  13883. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  13884. |$\Rightarrow$|
  13885. (Cast |$e'$| |$T'$| |$T''$|)
  13886. \end{lstlisting}
  13887. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  13888. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  13889. Finally, each polymorphic function is translated to a regular
  13890. functions in which type erasure has been applied to all the type
  13891. annotations and the body.
  13892. \begin{lstlisting}
  13893. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  13894. |$\Rightarrow$|
  13895. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  13896. \end{lstlisting}
  13897. \begin{exercise}\normalfont
  13898. Implement a compiler for the polymorphic language \LangPoly{} by
  13899. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  13900. programs that use polymorphic functions. Some of them should make
  13901. use of first-class polymorphism.
  13902. \end{exercise}
  13903. \begin{figure}[p]
  13904. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13905. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  13906. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  13907. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  13908. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  13909. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  13910. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  13911. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  13912. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  13913. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  13914. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  13915. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  13916. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  13917. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  13918. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  13919. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  13920. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13921. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13922. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13923. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13924. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13925. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13926. \path[->,bend right=15] (Rpoly) edge [above] node
  13927. {\ttfamily\footnotesize type-check} (Rpolyp);
  13928. \path[->,bend right=15] (Rpolyp) edge [above] node
  13929. {\ttfamily\footnotesize erase-types} (Rgradualp);
  13930. \path[->,bend right=15] (Rgradualp) edge [above] node
  13931. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  13932. \path[->,bend right=15] (Rwhilepp) edge [right] node
  13933. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  13934. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  13935. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  13936. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  13937. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  13938. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  13939. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  13940. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  13941. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  13942. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  13943. {\ttfamily\footnotesize convert-assignments} (F1-1);
  13944. \path[->,bend left=15] (F1-1) edge [below] node
  13945. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  13946. \path[->,bend right=15] (F1-2) edge [above] node
  13947. {\ttfamily\footnotesize limit-fun.} (F1-3);
  13948. \path[->,bend right=15] (F1-3) edge [above] node
  13949. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  13950. \path[->,bend right=15] (F1-4) edge [above] node
  13951. {\ttfamily\footnotesize remove-complex.} (F1-5);
  13952. \path[->,bend right=15] (F1-5) edge [right] node
  13953. {\ttfamily\footnotesize explicate-control} (C3-2);
  13954. \path[->,bend left=15] (C3-2) edge [left] node
  13955. {\ttfamily\footnotesize select-instr.} (x86-2);
  13956. \path[->,bend right=15] (x86-2) edge [left] node
  13957. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  13958. \path[->,bend right=15] (x86-2-1) edge [below] node
  13959. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  13960. \path[->,bend right=15] (x86-2-2) edge [left] node
  13961. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  13962. \path[->,bend left=15] (x86-3) edge [above] node
  13963. {\ttfamily\footnotesize patch-instr.} (x86-4);
  13964. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  13965. \end{tikzpicture}
  13966. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  13967. \label{fig:Rpoly-passes}
  13968. \end{figure}
  13969. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  13970. for the compilation of \LangPoly{}.
  13971. % TODO: challenge problem: specialization of instantiations
  13972. % Further Reading
  13973. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13974. \clearpage
  13975. \appendix
  13976. \chapter{Appendix}
  13977. \section{Interpreters}
  13978. \label{appendix:interp}
  13979. \index{subject}{interpreter}
  13980. We provide interpreters for each of the source languages \LangInt{},
  13981. \LangVar{}, $\ldots$ in the files \code{interp\_Rint.rkt},
  13982. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  13983. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  13984. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  13985. and x86 are in the \key{interp.rkt} file.
  13986. \section{Utility Functions}
  13987. \label{appendix:utilities}
  13988. The utility functions described in this section are in the
  13989. \key{utilities.rkt} file of the support code.
  13990. \paragraph{\code{interp-tests}}
  13991. The \key{interp-tests} function runs the compiler passes and the
  13992. interpreters on each of the specified tests to check whether each pass
  13993. is correct. The \key{interp-tests} function has the following
  13994. parameters:
  13995. \begin{description}
  13996. \item[name (a string)] a name to identify the compiler,
  13997. \item[typechecker] a function of exactly one argument that either
  13998. raises an error using the \code{error} function when it encounters a
  13999. type error, or returns \code{\#f} when it encounters a type
  14000. error. If there is no type error, the type checker returns the
  14001. program.
  14002. \item[passes] a list with one entry per pass. An entry is a list with
  14003. four things:
  14004. \begin{enumerate}
  14005. \item a string giving the name of the pass,
  14006. \item the function that implements the pass (a translator from AST
  14007. to AST),
  14008. \item a function that implements the interpreter (a function from
  14009. AST to result value) for the output language,
  14010. \item and a type checker for the output language. Type checkers for
  14011. the $R$ and $C$ languages are provided in the support code. For
  14012. example, the type checkers for \LangVar{} and \LangCVar{} are in
  14013. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  14014. type checker entry is optional. The support code does not provide
  14015. type checkers for the x86 languages.
  14016. \end{enumerate}
  14017. \item[source-interp] an interpreter for the source language. The
  14018. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  14019. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  14020. \item[tests] a list of test numbers that specifies which tests to
  14021. run. (see below)
  14022. \end{description}
  14023. %
  14024. The \key{interp-tests} function assumes that the subdirectory
  14025. \key{tests} has a collection of Racket programs whose names all start
  14026. with the family name, followed by an underscore and then the test
  14027. number, ending with the file extension \key{.rkt}. Also, for each test
  14028. program that calls \code{read} one or more times, there is a file with
  14029. the same name except that the file extension is \key{.in} that
  14030. provides the input for the Racket program. If the test program is
  14031. expected to fail type checking, then there should be an empty file of
  14032. the same name but with extension \key{.tyerr}.
  14033. \paragraph{\code{compiler-tests}}
  14034. runs the compiler passes to generate x86 (a \key{.s} file) and then
  14035. runs the GNU C compiler (gcc) to generate machine code. It runs the
  14036. machine code and checks that the output is $42$. The parameters to the
  14037. \code{compiler-tests} function are similar to those of the
  14038. \code{interp-tests} function, and consist of
  14039. \begin{itemize}
  14040. \item a compiler name (a string),
  14041. \item a type checker,
  14042. \item description of the passes,
  14043. \item name of a test-family, and
  14044. \item a list of test numbers.
  14045. \end{itemize}
  14046. \paragraph{\code{compile-file}}
  14047. takes a description of the compiler passes (see the comment for
  14048. \key{interp-tests}) and returns a function that, given a program file
  14049. name (a string ending in \key{.rkt}), applies all of the passes and
  14050. writes the output to a file whose name is the same as the program file
  14051. name but with \key{.rkt} replaced with \key{.s}.
  14052. \paragraph{\code{read-program}}
  14053. takes a file path and parses that file (it must be a Racket program)
  14054. into an abstract syntax tree.
  14055. \paragraph{\code{parse-program}}
  14056. takes an S-expression representation of an abstract syntax tree and converts it into
  14057. the struct-based representation.
  14058. \paragraph{\code{assert}}
  14059. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  14060. and displays the message \key{msg} if the Boolean \key{bool} is false.
  14061. \paragraph{\code{lookup}}
  14062. % remove discussion of lookup? -Jeremy
  14063. takes a key and an alist, and returns the first value that is
  14064. associated with the given key, if there is one. If not, an error is
  14065. triggered. The alist may contain both immutable pairs (built with
  14066. \key{cons}) and mutable pairs (built with \key{mcons}).
  14067. %The \key{map2} function ...
  14068. \section{x86 Instruction Set Quick-Reference}
  14069. \label{sec:x86-quick-reference}
  14070. \index{subject}{x86}
  14071. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  14072. do. We write $A \to B$ to mean that the value of $A$ is written into
  14073. location $B$. Address offsets are given in bytes. The instruction
  14074. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  14075. registers (such as \code{\%rax}), or memory references (such as
  14076. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  14077. reference per instruction. Other operands must be immediates or
  14078. registers.
  14079. \begin{table}[tbp]
  14080. \centering
  14081. \begin{tabular}{l|l}
  14082. \textbf{Instruction} & \textbf{Operation} \\ \hline
  14083. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  14084. \texttt{negq} $A$ & $- A \to A$ \\
  14085. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  14086. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  14087. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  14088. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  14089. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  14090. \texttt{retq} & Pops the return address and jumps to it \\
  14091. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  14092. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  14093. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  14094. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  14095. be an immediate) \\
  14096. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  14097. matches the condition code of the instruction, otherwise go to the
  14098. next instructions. The condition codes are \key{e} for ``equal'',
  14099. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  14100. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  14101. \texttt{jl} $L$ & \\
  14102. \texttt{jle} $L$ & \\
  14103. \texttt{jg} $L$ & \\
  14104. \texttt{jge} $L$ & \\
  14105. \texttt{jmp} $L$ & Jump to label $L$ \\
  14106. \texttt{movq} $A$, $B$ & $A \to B$ \\
  14107. \texttt{movzbq} $A$, $B$ &
  14108. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  14109. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  14110. and the extra bytes of $B$ are set to zero.} \\
  14111. & \\
  14112. & \\
  14113. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  14114. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  14115. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  14116. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  14117. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  14118. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  14119. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  14120. description of the condition codes. $A$ must be a single byte register
  14121. (e.g., \texttt{al} or \texttt{cl}).} \\
  14122. \texttt{setl} $A$ & \\
  14123. \texttt{setle} $A$ & \\
  14124. \texttt{setg} $A$ & \\
  14125. \texttt{setge} $A$ &
  14126. \end{tabular}
  14127. \vspace{5pt}
  14128. \caption{Quick-reference for the x86 instructions used in this book.}
  14129. \label{tab:x86-instr}
  14130. \end{table}
  14131. \cleardoublepage
  14132. \section{Concrete Syntax for Intermediate Languages}
  14133. The concrete syntax of \LangAny{} is defined in
  14134. Figure~\ref{fig:Rany-concrete-syntax}.
  14135. \begin{figure}[tp]
  14136. \centering
  14137. \fbox{
  14138. \begin{minipage}{0.97\textwidth}\small
  14139. \[
  14140. \begin{array}{lcl}
  14141. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  14142. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  14143. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  14144. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  14145. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  14146. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  14147. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  14148. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  14149. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  14150. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  14151. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  14152. \MID \LP\key{void?}\;\Exp\RP \\
  14153. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  14154. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  14155. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  14156. \end{array}
  14157. \]
  14158. \end{minipage}
  14159. }
  14160. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  14161. (Figure~\ref{fig:Rlam-syntax}).}
  14162. \label{fig:Rany-concrete-syntax}
  14163. \end{figure}
  14164. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  14165. defined in Figures~\ref{fig:c0-concrete-syntax},
  14166. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  14167. and \ref{fig:c3-concrete-syntax}, respectively.
  14168. \begin{figure}[tbp]
  14169. \fbox{
  14170. \begin{minipage}{0.96\textwidth}
  14171. \[
  14172. \begin{array}{lcl}
  14173. \Atm &::=& \Int \MID \Var \\
  14174. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  14175. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  14176. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  14177. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  14178. \end{array}
  14179. \]
  14180. \end{minipage}
  14181. }
  14182. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  14183. \label{fig:c0-concrete-syntax}
  14184. \end{figure}
  14185. \begin{figure}[tbp]
  14186. \fbox{
  14187. \begin{minipage}{0.96\textwidth}
  14188. \small
  14189. \[
  14190. \begin{array}{lcl}
  14191. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  14192. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  14193. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  14194. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  14195. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  14196. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  14197. \MID \key{goto}~\itm{label}\key{;}\\
  14198. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  14199. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  14200. \end{array}
  14201. \]
  14202. \end{minipage}
  14203. }
  14204. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  14205. \label{fig:c1-concrete-syntax}
  14206. \end{figure}
  14207. \begin{figure}[tbp]
  14208. \fbox{
  14209. \begin{minipage}{0.96\textwidth}
  14210. \small
  14211. \[
  14212. \begin{array}{lcl}
  14213. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  14214. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  14215. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  14216. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  14217. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  14218. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  14219. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  14220. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  14221. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  14222. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  14223. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  14224. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  14225. \end{array}
  14226. \]
  14227. \end{minipage}
  14228. }
  14229. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  14230. \label{fig:c2-concrete-syntax}
  14231. \end{figure}
  14232. \begin{figure}[tp]
  14233. \fbox{
  14234. \begin{minipage}{0.96\textwidth}
  14235. \small
  14236. \[
  14237. \begin{array}{lcl}
  14238. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  14239. \\
  14240. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  14241. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  14242. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  14243. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  14244. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  14245. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  14246. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  14247. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  14248. \MID \LP\key{collect} \,\itm{int}\RP }\\
  14249. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  14250. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  14251. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  14252. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  14253. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  14254. \LangCFunM{} & ::= & \Def\ldots
  14255. \end{array}
  14256. \]
  14257. \end{minipage}
  14258. }
  14259. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  14260. \label{fig:c3-concrete-syntax}
  14261. \end{figure}
  14262. \backmatter
  14263. \addtocontents{toc}{\vspace{11pt}}
  14264. %% \addtocontents{toc}{\vspace{11pt}}
  14265. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  14266. \nocite{*}\let\bibname\refname
  14267. \addcontentsline{toc}{fmbm}{\refname}
  14268. \printbibliography
  14269. \printindex{authors}{Author Index}
  14270. \printindex{subject}{Subject Index}
  14271. \end{document}