book.tex 248 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674
  1. \documentclass[11pt]{book}
  2. \usepackage[T1]{fontenc}
  3. \usepackage[utf8]{inputenc}
  4. \usepackage{lmodern}
  5. \usepackage{hyperref}
  6. \usepackage{graphicx}
  7. \usepackage[english]{babel}
  8. \usepackage{listings}
  9. \usepackage{amsmath}
  10. \usepackage{amsthm}
  11. \usepackage{amssymb}
  12. \usepackage{natbib}
  13. \usepackage{stmaryrd}
  14. \usepackage{xypic}
  15. \usepackage{semantic}
  16. \usepackage{wrapfig}
  17. \usepackage{multirow}
  18. \usepackage{color}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. %% For pictures
  23. \usepackage{tikz}
  24. \usetikzlibrary{arrows.meta}
  25. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  26. % Computer Modern is already the default. -Jeremy
  27. %\renewcommand{\ttdefault}{cmtt}
  28. \lstset{%
  29. language=Lisp,
  30. basicstyle=\ttfamily\small,
  31. escapechar=|,
  32. columns=flexible,
  33. moredelim=[is][\color{red}]{~}{~}
  34. }
  35. \newtheorem{theorem}{Theorem}
  36. \newtheorem{lemma}[theorem]{Lemma}
  37. \newtheorem{corollary}[theorem]{Corollary}
  38. \newtheorem{proposition}[theorem]{Proposition}
  39. \newtheorem{constraint}[theorem]{Constraint}
  40. \newtheorem{definition}[theorem]{Definition}
  41. \newtheorem{exercise}[theorem]{Exercise}
  42. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  43. % 'dedication' environment: To add a dedication paragraph at the start of book %
  44. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  45. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  46. \newenvironment{dedication}
  47. {
  48. \cleardoublepage
  49. \thispagestyle{empty}
  50. \vspace*{\stretch{1}}
  51. \hfill\begin{minipage}[t]{0.66\textwidth}
  52. \raggedright
  53. }
  54. {
  55. \end{minipage}
  56. \vspace*{\stretch{3}}
  57. \clearpage
  58. }
  59. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  60. % Chapter quote at the start of chapter %
  61. % Source: http://tex.stackexchange.com/a/53380 %
  62. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  63. \makeatletter
  64. \renewcommand{\@chapapp}{}% Not necessary...
  65. \newenvironment{chapquote}[2][2em]
  66. {\setlength{\@tempdima}{#1}%
  67. \def\chapquote@author{#2}%
  68. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  69. \itshape}
  70. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  71. \makeatother
  72. \input{defs}
  73. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  74. \title{\Huge \textbf{Essentials of Compilation} \\
  75. \huge An Incremental Approach}
  76. \author{\textsc{Jeremy G. Siek} \\
  77. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  78. Indiana University \\
  79. \\
  80. with contributions from: \\
  81. Carl Factora \\
  82. Andre Kuhlenschmidt \\
  83. Michael M. Vitousek \\
  84. Cameron Swords
  85. }
  86. \begin{document}
  87. \frontmatter
  88. \maketitle
  89. \begin{dedication}
  90. This book is dedicated to the programming language wonks at Indiana
  91. University.
  92. \end{dedication}
  93. \tableofcontents
  94. \listoffigures
  95. %\listoftables
  96. \mainmatter
  97. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  98. \chapter*{Preface}
  99. The tradition of compiler writing at Indiana University goes back to
  100. programming language research and courses taught by Daniel Friedman in
  101. the 1970's and 1980's. Dan had conducted research on lazy evaluation
  102. in the context of Lisp~\citep{McCarthy:1960dz} and then studied
  103. continuations and macros in the context of the
  104. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of students of
  105. those courses, Kent Dybvig, went on to build Chez
  106. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  107. compiler for Scheme. After completing his Ph.D. at the University of
  108. North Carolina, Kent returned to teach at Indiana University.
  109. Throughout the 1990's and 2000's, Kent continued development of
  110. Chez Scheme and taught the compiler course.
  111. The compiler course evolved to incorporate novel pedagogical ideas
  112. while also including elements of effective real-world compilers. One
  113. of Dan's ideas was to split the compiler into many small passes over
  114. the input program and subsequent intermediate representations, so that
  115. the code for each pass would be easy to understood in isolation. (In
  116. contrast, most compilers of the time were organized into only a few
  117. monolithic passes for reasons of compile-time efficiency.) Kent and
  118. his students, Dipanwita Sarkar and Andrew Keep, developed
  119. infrastructure to support this approach and evolved the course, first
  120. to use micro-sized passes and then into even smaller nano
  121. passes~\citep{Sarkar:2004fk,Keep:2012aa}. I took this compiler course
  122. in the early 2000's, as part of my Ph.D. studies at Indiana
  123. University. Needless to say, I enjoyed the course immensely.
  124. One of my classmates, Abdulaziz Ghuloum, observed that the
  125. front-to-back organization of the course made it difficult for
  126. students to understand the rationale for the compiler
  127. design. Abdulaziz proposed an incremental approach in which the
  128. students build the compiler in stages; they start by implementing a
  129. complete compiler for a very small subset of the input language, then
  130. in each subsequent stage they add a feature to the input language and
  131. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  132. In this way, the students see how the language features motivate
  133. aspects of the compiler design.
  134. After graduating from Indiana University in 2005, I went on to teach
  135. at the University of Colorado. I adapted the nano pass and incremental
  136. approaches to compiling a subset of the Python
  137. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  138. on the surface but there is a large overlap in the compiler techniques
  139. required for the two languages. Thus, I was able to teach much of the
  140. same content from the Indiana compiler course. I very much enjoyed
  141. teaching the course organized in this way, and even better, many of
  142. the students learned a lot and got excited about compilers.
  143. It is now 2016 and I too have returned to teach at Indiana University.
  144. In my absence the compiler course had switched from the front-to-back
  145. organization to a back-to-front organization. Seeing how well the
  146. incremental approach worked at Colorado, I started porting and
  147. adapting the structure of the Colorado course back into the land of
  148. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  149. the course is now about compiling a subset of Racket to the x86
  150. assembly language and the compiler is implemented in
  151. Racket~\citep{plt-tr}.
  152. This is the textbook for the incremental version of the compiler
  153. course at Indiana University (Spring 2016) and it is the first
  154. textbook for an Indiana compiler course. With this book I hope to
  155. make the Indiana compiler course available to people that have not had
  156. the chance to study in Bloomington in person. Many of the compiler
  157. design decisions in this book are drawn from the assignment
  158. descriptions of \cite{Dybvig:2010aa}. I have captured what I think are
  159. the most important topics from \cite{Dybvig:2010aa} but I have omitted
  160. topics that I think are less interesting conceptually and I have made
  161. simplifications to reduce complexity. In this way, this book leans
  162. more towards pedagogy than towards the absolute efficiency of the
  163. generated code. Also, the book differs in places where I saw the
  164. opportunity to make the topics more fun, such as in relating register
  165. allocation to Sudoku (Chapter~\ref{ch:register-allocation}).
  166. \section*{Prerequisites}
  167. The material in this book is challenging but rewarding. It is meant to
  168. prepare students for a lifelong career in programming languages. I do
  169. not recommend this book for students who want to dabble in programming
  170. languages. Because the book uses the Racket language both for the
  171. implementation of the compiler and for the language that is compiled,
  172. a student should be proficient with Racket (or Scheme) prior to
  173. reading this book. There are many other excellent resources for
  174. learning Scheme and
  175. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  176. is helpful but not necessary for the student to have prior exposure to
  177. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  178. obtain from a computer systems
  179. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  180. parts of x86-64 assembly language that are needed.
  181. %\section*{Structure of book}
  182. % You might want to add short description about each chapter in this book.
  183. %\section*{About the companion website}
  184. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  185. %\begin{itemize}
  186. % \item A link to (freely downlodable) latest version of this document.
  187. % \item Link to download LaTeX source for this document.
  188. % \item Miscellaneous material (e.g. suggested readings etc).
  189. %\end{itemize}
  190. \section*{Acknowledgments}
  191. Need to give thanks to
  192. \begin{itemize}
  193. \item Bor-Yuh Evan Chang
  194. \item Kent Dybvig
  195. \item Daniel P. Friedman
  196. \item Ronald Garcia
  197. \item Abdulaziz Ghuloum
  198. \item Ryan Newton
  199. \item Dipanwita Sarkar
  200. \item Andrew Keep
  201. \item Oscar Waddell
  202. \end{itemize}
  203. \mbox{}\\
  204. \noindent Jeremy G. Siek \\
  205. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  206. \noindent Spring 2016
  207. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  208. \chapter{Preliminaries}
  209. \label{ch:trees-recur}
  210. In this chapter, we review the basic tools that are needed for
  211. implementing a compiler. We use abstract syntax trees (ASTs) in the
  212. form of S-expressions to represent programs (Section~\ref{sec:ast})
  213. and pattern matching to inspect individual nodes in an AST
  214. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  215. and deconstruct entire ASTs (Section~\ref{sec:recursion}).
  216. \section{Abstract Syntax Trees}
  217. \label{sec:ast}
  218. The primary data structure that is commonly used for representing
  219. programs is the \emph{abstract syntax tree} (AST). When considering
  220. some part of a program, a compiler needs to ask what kind of part it
  221. is and what sub-parts it has. For example, the program on the left is
  222. represented by the AST on the right.
  223. \begin{center}
  224. \begin{minipage}{0.4\textwidth}
  225. \begin{lstlisting}
  226. (+ (read) (- 8))
  227. \end{lstlisting}
  228. \end{minipage}
  229. \begin{minipage}{0.4\textwidth}
  230. \begin{equation}
  231. \begin{tikzpicture}
  232. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  233. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  234. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  235. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  236. \draw[->] (plus) to (read);
  237. \draw[->] (plus) to (minus);
  238. \draw[->] (minus) to (8);
  239. \end{tikzpicture}
  240. \label{eq:arith-prog}
  241. \end{equation}
  242. \end{minipage}
  243. \end{center}
  244. We shall use the standard terminology for trees: each circle above is
  245. called a \emph{node}. The arrows connect a node to its \emph{children}
  246. (which are also nodes). The top-most node is the \emph{root}. Every
  247. node except for the root has a \emph{parent} (the node it is the child
  248. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  249. it is an \emph{internal} node.
  250. When deciding how to compile the above program, we need to know that
  251. the root node operation is addition and that it has two children:
  252. \texttt{read} and a negation. The abstract syntax tree data structure
  253. directly supports these queries and hence is a good choice. In this
  254. book, we will often write down the textual representation of a program
  255. even when we really have in mind the AST because the textual
  256. representation is more concise. We recommend that, in your mind, you
  257. always interpret programs as abstract syntax trees.
  258. \section{Grammars}
  259. \label{sec:grammar}
  260. A programming language can be thought of as a \emph{set} of programs.
  261. The set is typically infinite (one can always create larger and larger
  262. programs), so one cannot simply describe a language by listing all of
  263. the programs in the language. Instead we write down a set of rules, a
  264. \emph{grammar}, for building programs. We shall write our rules in a
  265. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  266. As an example, we describe a small language, named $R_0$, of
  267. integers and arithmetic operations. The first rule says that any
  268. integer is an expression, $\Exp$, in the language:
  269. \begin{equation}
  270. \Exp ::= \Int \label{eq:arith-int}
  271. \end{equation}
  272. Each rule has a left-hand-side and a right-hand-side. The way to read
  273. a rule is that if you have all the program parts on the
  274. right-hand-side, then you can create an AST node and categorize it
  275. according to the left-hand-side. (We do not define $\Int$ because the
  276. reader already knows what an integer is.) We make the simplifying
  277. design decision that all of the languages in this book only handle
  278. machine-representable integers (those representable with 64-bits,
  279. i.e., the range $-2^{63}$ to $2^{63}$) which corresponds to the
  280. \texttt{fixnum} datatype in Racket. A name such as $\Exp$ that is
  281. defined by the grammar rules is a \emph{non-terminal}.
  282. The second grammar rule is the \texttt{read} operation that receives
  283. an input integer from the user of the program.
  284. \begin{equation}
  285. \Exp ::= (\key{read}) \label{eq:arith-read}
  286. \end{equation}
  287. The third rule says that, given an $\Exp$ node, you can build another
  288. $\Exp$ node by negating it.
  289. \begin{equation}
  290. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  291. \end{equation}
  292. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  293. and must literally appear in the program for the rule to be
  294. applicable.
  295. We can apply the rules to build ASTs in the $R_0$
  296. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  297. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  298. an $\Exp$.
  299. \begin{center}
  300. \begin{minipage}{0.25\textwidth}
  301. \begin{lstlisting}
  302. (- 8)
  303. \end{lstlisting}
  304. \end{minipage}
  305. \begin{minipage}{0.25\textwidth}
  306. \begin{equation}
  307. \begin{tikzpicture}
  308. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  309. \node[draw, circle] (8) at (0, -1.2) {$8$};
  310. \draw[->] (minus) to (8);
  311. \end{tikzpicture}
  312. \label{eq:arith-neg8}
  313. \end{equation}
  314. \end{minipage}
  315. \end{center}
  316. The following grammar rule defines addition expressions:
  317. \begin{equation}
  318. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  319. \end{equation}
  320. Now we can see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  321. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  322. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  323. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  324. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  325. If you have an AST for which the above rules do not apply, then the
  326. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  327. not in $R_0$ because there are no rules for \key{+} with only one
  328. argument, nor for \key{-} with two arguments. Whenever we define a
  329. language with a grammar, we implicitly mean for the language to be the
  330. smallest set of programs that are justified by the rules. That is, the
  331. language only includes those programs that the rules allow.
  332. The last grammar for $R_0$ states that there is a \key{program} node
  333. to mark the top of the whole program:
  334. \[
  335. R_0 ::= (\key{program} \; \Exp)
  336. \]
  337. The \code{read-program} function provided in \code{utilities.rkt}
  338. reads programs in from a file (the sequence of characters in the
  339. concrete syntax of Racket) and parses them into the abstract syntax
  340. tree. The concrete syntax does not include a \key{program} form; that
  341. is added by the \code{read-program} function as it creates the
  342. AST. See the description of \code{read-program} in
  343. Appendix~\ref{appendix:utilities} for more details.
  344. It is common to have many rules with the same left-hand side, such as
  345. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  346. for gathering several rules, as shown in
  347. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  348. called an {\em alternative}.
  349. \begin{figure}[tp]
  350. \fbox{
  351. \begin{minipage}{0.96\textwidth}
  352. \[
  353. \begin{array}{rcl}
  354. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  355. (\key{+} \; \Exp \; \Exp) \\
  356. R_0 &::=& (\key{program} \; \Exp)
  357. \end{array}
  358. \]
  359. \end{minipage}
  360. }
  361. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  362. \label{fig:r0-syntax}
  363. \end{figure}
  364. \section{S-Expressions}
  365. \label{sec:s-expr}
  366. Racket, as a descendant of Lisp, has
  367. convenient support for creating and manipulating abstract syntax trees
  368. with its \emph{symbolic expression} feature, or S-expression for
  369. short. We can create an S-expression simply by writing a backquote
  370. followed by the textual representation of the AST. (Technically
  371. speaking, this is called a \emph{quasiquote} in Racket.) For example,
  372. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  373. by the following Racket expression:
  374. \begin{center}
  375. \texttt{`(+ (read) (- 8))}
  376. \end{center}
  377. To build larger S-expressions one often needs to splice together
  378. several smaller S-expressions. Racket provides the comma operator to
  379. splice an S-expression into a larger one. For example, instead of
  380. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  381. we could have first created an S-expression for AST
  382. \eqref{eq:arith-neg8} and then spliced that into the addition
  383. S-expression.
  384. \begin{lstlisting}
  385. (define ast1.4 `(- 8))
  386. (define ast1.1 `(+ (read) ,ast1.4))
  387. \end{lstlisting}
  388. In general, the Racket expression that follows the comma (splice)
  389. can be any expression that computes an S-expression.
  390. \section{Pattern Matching}
  391. \label{sec:pattern-matching}
  392. As mentioned above, one of the operations that a compiler needs to
  393. perform on an AST is to access the children of a node. Racket
  394. provides the \texttt{match} form to access the parts of an
  395. S-expression. Consider the following example and the output on the
  396. right.
  397. \begin{center}
  398. \begin{minipage}{0.5\textwidth}
  399. \begin{lstlisting}
  400. (match ast1.1
  401. [`(,op ,child1 ,child2)
  402. (print op) (newline)
  403. (print child1) (newline)
  404. (print child2)])
  405. \end{lstlisting}
  406. \end{minipage}
  407. \vrule
  408. \begin{minipage}{0.25\textwidth}
  409. \begin{lstlisting}
  410. '+
  411. '(read)
  412. '(- 8)
  413. \end{lstlisting}
  414. \end{minipage}
  415. \end{center}
  416. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  417. parts to the three variables \texttt{op}, \texttt{child1}, and
  418. \texttt{child2}. In general, a match clause consists of a
  419. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  420. that may contain pattern-variables (preceded by a comma). The body
  421. may contain any Racket code.
  422. A \texttt{match} form may contain several clauses, as in the following
  423. function \texttt{leaf?} that recognizes when an $R_0$ node is
  424. a leaf. The \texttt{match} proceeds through the clauses in order,
  425. checking whether the pattern can match the input S-expression. The
  426. body of the first clause that matches is executed. The output of
  427. \texttt{leaf?} for several S-expressions is shown on the right. In the
  428. below \texttt{match}, we see another form of pattern: the \texttt{(?
  429. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  430. S-expression to see if it is a machine-representable integer.
  431. \begin{center}
  432. \begin{minipage}{0.5\textwidth}
  433. \begin{lstlisting}
  434. (define (leaf? arith)
  435. (match arith
  436. [(? fixnum?) #t]
  437. [`(read) #t]
  438. [`(- ,c1) #f]
  439. [`(+ ,c1 ,c2) #f]))
  440. (leaf? `(read))
  441. (leaf? `(- 8))
  442. (leaf? `(+ (read) (- 8)))
  443. \end{lstlisting}
  444. \end{minipage}
  445. \vrule
  446. \begin{minipage}{0.25\textwidth}
  447. \begin{lstlisting}
  448. #t
  449. #f
  450. #f
  451. \end{lstlisting}
  452. \end{minipage}
  453. \end{center}
  454. \section{Recursion}
  455. \label{sec:recursion}
  456. Programs are inherently recursive in that an $R_0$ AST is made
  457. up of smaller $R_0$ ASTs. Thus, the natural way to process in
  458. entire program is with a recursive function. As a first example of
  459. such a function, we define \texttt{R0?} below, which takes an
  460. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  461. sexp} is in {\tt arith}. Note that each match clause corresponds to
  462. one grammar rule for $R_0$ and the body of each clause makes a
  463. recursive call for each child node. This pattern of recursive function
  464. is so common that it has a name, \emph{structural recursion}. In
  465. general, when a recursive function is defined using a sequence of
  466. match clauses that correspond to a grammar, and each clause body makes
  467. a recursive call on each child node, then we say the function is
  468. defined by structural recursion.
  469. \begin{center}
  470. \begin{minipage}{0.7\textwidth}
  471. \begin{lstlisting}
  472. (define (R0? sexp)
  473. (match sexp
  474. [(? fixnum?) #t]
  475. [`(read) #t]
  476. [`(- ,e) (R0? e)]
  477. [`(+ ,e1 ,e2)
  478. (and (R0? e1) (R0? e2))]
  479. [`(program ,e) (R0? e)]
  480. [else #f]))
  481. (R0? `(+ (read) (- 8)))
  482. (R0? `(- (read) (+ 8)))
  483. \end{lstlisting}
  484. \end{minipage}
  485. \vrule
  486. \begin{minipage}{0.25\textwidth}
  487. \begin{lstlisting}
  488. #t
  489. #f
  490. \end{lstlisting}
  491. \end{minipage}
  492. \end{center}
  493. \section{Interpreters}
  494. \label{sec:interp-R0}
  495. The meaning, or semantics, of a program is typically defined in the
  496. specification of the language. For example, the Scheme language is
  497. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  498. defined in its reference manual~\citep{plt-tr}. In this book we use an
  499. interpreter to define the meaning of each language that we consider,
  500. following Reynold's advice in this
  501. regard~\citep{reynolds72:_def_interp}. Here we will warm up by writing
  502. an interpreter for the $R_0$ language, which will also serve as a
  503. second example of structural recursion. The \texttt{interp-R0}
  504. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  505. function is a match on the input expression \texttt{e} and there is
  506. one clause per grammar rule for $R_0$. The clauses for internal AST
  507. nodes make recursive calls to \texttt{interp-R0} on each child
  508. node. Here we make use of the \key{app} feature of Racket's
  509. \key{match} to concisely apply a function and bind the result. For
  510. example, in the case for negation, we use \key{app} to recursively
  511. apply \texttt{interp-R0} to the child node and bind the result value
  512. to variable \texttt{v}.
  513. \begin{figure}[tbp]
  514. \begin{lstlisting}
  515. (define (interp-R0 e)
  516. (match e
  517. [(? fixnum?) e]
  518. [`(read)
  519. (let ([r (read)])
  520. (cond [(fixnum? r) r]
  521. [else (error 'interp-R0 "input not an integer" r)]))]
  522. [`(- ,(app interp-R0 v))
  523. (fx- 0 v)]
  524. [`(+ ,(app interp-R0 v1) ,(app interp-R0 v2))
  525. (fx+ v1 v2)]
  526. [`(program ,(app interp-R0 v)) v]
  527. ))
  528. \end{lstlisting}
  529. \caption{Interpreter for the $R_0$ language.}
  530. \label{fig:interp-R0}
  531. \end{figure}
  532. Let us consider the result of interpreting some example $R_0$
  533. programs. The following program simply adds two integers.
  534. \begin{lstlisting}
  535. (+ 10 32)
  536. \end{lstlisting}
  537. The result is \key{42}, as you might have expected.
  538. %
  539. The next example demonstrates that expressions may be nested within
  540. each other, in this case nesting several additions and negations.
  541. \begin{lstlisting}
  542. (+ 10 (- (+ 12 20)))
  543. \end{lstlisting}
  544. What is the result of the above program?
  545. If we interpret the AST \eqref{eq:arith-prog} and give it the input
  546. \texttt{50}
  547. \begin{lstlisting}
  548. (interp-R0 ast1.1)
  549. \end{lstlisting}
  550. we get the answer to life, the universe, and everything:
  551. \begin{lstlisting}
  552. 42
  553. \end{lstlisting}
  554. Moving on, the \key{read} operation prompts the user of the program
  555. for an integer. Given an input of \key{10}, the following program
  556. produces \key{42}.
  557. \begin{lstlisting}
  558. (+ (read) 32)
  559. \end{lstlisting}
  560. We include the \key{read} operation in $R_1$ so that a compiler for
  561. $R_1$ cannot be implemented simply by running the interpreter at
  562. compilation time to obtain the output and then generating the trivial
  563. code to return the output. (A clever student at Colorado did this the
  564. first time I taught the course.)
  565. The job of a compiler is to translate a program in one language into a
  566. program in another language so that the output program behaves the
  567. same way as the input program. This idea is depicted in the following
  568. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  569. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  570. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  571. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  572. and $P_2$ on their respective interpreters with input $i$ should yield
  573. the same output $o$.
  574. \begin{equation} \label{eq:compile-correct}
  575. \begin{tikzpicture}[baseline=(current bounding box.center)]
  576. \node (p1) at (0, 0) {$P_1$};
  577. \node (p2) at (3, 0) {$P_2$};
  578. \node (o) at (3, -2.5) {$o$};
  579. \path[->] (p1) edge [above] node {compile} (p2);
  580. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  581. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  582. \end{tikzpicture}
  583. \end{equation}
  584. In the next section we see our first example of a compiler, which is
  585. another example of structural recursion.
  586. \section{Example Compiler: a Partial Evaluator}
  587. \label{sec:partial-evaluation}
  588. In this section we consider a compiler that translates $R_0$
  589. programs into $R_0$ programs that are more efficient, that is,
  590. this compiler is an optimizer. Our optimizer will accomplish this by
  591. trying to eagerly compute the parts of the program that do not depend
  592. on any inputs. For example, given the following program
  593. \begin{lstlisting}
  594. (+ (read) (- (+ 5 3)))
  595. \end{lstlisting}
  596. our compiler will translate it into the program
  597. \begin{lstlisting}
  598. (+ (read) -8)
  599. \end{lstlisting}
  600. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  601. evaluator for the $R_0$ language. The output of the partial evaluator
  602. is an $R_0$ program, which we build up using a combination of
  603. quasiquotes and commas. (Though no quasiquote is necessary for
  604. integers.) In Figure~\ref{fig:pe-arith}, the normal structural
  605. recursion is captured in the main \texttt{pe-arith} function whereas
  606. the code for partially evaluating negation and addition is factored
  607. into two separate helper functions: \texttt{pe-neg} and
  608. \texttt{pe-add}. The input to these helper functions is the output of
  609. partially evaluating the children nodes.
  610. \begin{figure}[tbp]
  611. \begin{lstlisting}
  612. (define (pe-neg r)
  613. (cond [(fixnum? r) (fx- 0 r)]
  614. [else `(- ,r)]))
  615. (define (pe-add r1 r2)
  616. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  617. [else `(+ ,r1 ,r2)]))
  618. (define (pe-arith e)
  619. (match e
  620. [(? fixnum?) e]
  621. [`(read) `(read)]
  622. [`(- ,(app pe-arith r1))
  623. (pe-neg r1)]
  624. [`(+ ,(app pe-arith r1) ,(app pe-arith r2))
  625. (pe-add r1 r2)]))
  626. \end{lstlisting}
  627. \caption{A partial evaluator for the $R_0$ language.}
  628. \label{fig:pe-arith}
  629. \end{figure}
  630. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  631. idea of checking whether the inputs are integers and if they are, to
  632. go ahead and perform the arithmetic. Otherwise, we use quasiquote to
  633. create an AST node for the appropriate operation (either negation or
  634. addition) and use comma to splice in the child nodes.
  635. To gain some confidence that the partial evaluator is correct, we can
  636. test whether it produces programs that get the same result as the
  637. input program. That is, we can test whether it satisfies Diagram
  638. \eqref{eq:compile-correct}. The following code runs the partial
  639. evaluator on several examples and tests the output program. The
  640. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  641. \begin{lstlisting}
  642. (define (test-pe p)
  643. (assert "testing pe-arith"
  644. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  645. (test-pe `(+ (read) (- (+ 5 3))))
  646. (test-pe `(+ 1 (+ (read) 1)))
  647. (test-pe `(- (+ (read) (- 5))))
  648. \end{lstlisting}
  649. \begin{exercise}
  650. \normalfont % I don't like the italics for exercises. -Jeremy
  651. We challenge the reader to improve on the simple partial evaluator in
  652. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  653. \texttt{pe-add} helper functions with functions that know more about
  654. arithmetic. For example, your partial evaluator should translate
  655. \begin{lstlisting}
  656. (+ 1 (+ (read) 1))
  657. \end{lstlisting}
  658. into
  659. \begin{lstlisting}
  660. (+ 2 (read))
  661. \end{lstlisting}
  662. To accomplish this, we recommend that your partial evaluator produce
  663. output that takes the form of the $\itm{residual}$ non-terminal in the
  664. following grammar.
  665. \[
  666. \begin{array}{lcl}
  667. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  668. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  669. \end{array}
  670. \]
  671. \end{exercise}
  672. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  673. \chapter{Compiling Integers and Variables}
  674. \label{ch:int-exp}
  675. This chapter concerns the challenge of compiling a subset of Racket,
  676. which we name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}.
  677. (Hence force we shall refer to x86-64 simply as x86). The chapter
  678. begins with a description of the $R_1$ language (Section~\ref{sec:s0})
  679. and then a description of x86 (Section~\ref{sec:x86}). The
  680. x86 assembly language is quite large, so we only discuss what is
  681. needed for compiling $R_1$. We introduce more of x86 in later
  682. chapters. Once we have introduced $R_1$ and x86, we reflect on
  683. their differences and come up with a plan breaking down the
  684. translation from $R_1$ to x86 into a handful of steps
  685. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  686. Chapter give detailed hints regarding each step
  687. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  688. to give enough hints that the well-prepared reader can implement a
  689. compiler from $R_1$ to x86 while at the same time leaving room for
  690. some fun and creativity.
  691. \section{The $R_1$ Language}
  692. \label{sec:s0}
  693. The $R_1$ language extends the $R_0$ language
  694. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  695. the $R_1$ language is defined by the grammar in
  696. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  697. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  698. a unary operator, and \key{+} is a binary operator. In addition to
  699. variable definitions, the $R_1$ language includes the \key{program}
  700. form to mark the top of the program, which is helpful in some of the
  701. compiler passes. The $R_1$ language is rich enough to exhibit several
  702. compilation techniques but simple enough so that the reader can
  703. implement a compiler for it in a week of part-time work. To give the
  704. reader a feeling for the scale of this first compiler, the instructor
  705. solution for the $R_1$ compiler consists of 6 recursive functions and
  706. a few small helper functions that together span 256 lines of code.
  707. \begin{figure}[btp]
  708. \centering
  709. \fbox{
  710. \begin{minipage}{0.96\textwidth}
  711. \[
  712. \begin{array}{rcl}
  713. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  714. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  715. R_1 &::=& (\key{program} \; \Exp)
  716. \end{array}
  717. \]
  718. \end{minipage}
  719. }
  720. \caption{The syntax of $R_1$, a language of integers and variables.}
  721. \label{fig:r1-syntax}
  722. \end{figure}
  723. The \key{let} construct defines a variable for use within its body
  724. and initializes the variable with the value of an expression. So the
  725. following program initializes \code{x} to \code{32} and then evaluates
  726. the body \code{(+ 10 x)}, producing \code{42}.
  727. \begin{lstlisting}
  728. (program
  729. (let ([x (+ 12 20)]) (+ 10 x)))
  730. \end{lstlisting}
  731. When there are multiple \key{let}'s for the same variable, the closest
  732. enclosing \key{let} is used. That is, variable definitions overshadow
  733. prior definitions. Consider the following program with two \key{let}'s
  734. that define variables named \code{x}. Can you figure out the result?
  735. \begin{lstlisting}
  736. (program
  737. (let ([x 32]) (+ (let ([x 10]) x) x)))
  738. \end{lstlisting}
  739. For the purposes of showing which variable uses correspond to which
  740. definitions, the following shows the \code{x}'s annotated with subscripts
  741. to distinguish them. Double check that your answer for the above is
  742. the same as your answer for this annotated version of the program.
  743. \begin{lstlisting}
  744. (program
  745. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  746. \end{lstlisting}
  747. The initializing expression is always evaluated before the body of the
  748. \key{let}, so in the following, the \key{read} for \code{x} is
  749. performed before the \key{read} for \code{y}. Given the input
  750. \code{52} then \code{10}, the following produces \code{42} (and not
  751. \code{-42}).
  752. \begin{lstlisting}
  753. (program
  754. (let ([x (read)]) (let ([y (read)]) (- x y))))
  755. \end{lstlisting}
  756. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  757. language. It extends the interpreter for $R_0$ with two new
  758. \key{match} clauses for variables and for \key{let}. For \key{let},
  759. we will need a way to communicate the initializing value of a variable
  760. to all the uses of a variable. To accomplish this, we maintain a
  761. mapping from variables to values, which is traditionally called an
  762. \emph{environment}. For simplicity, here we use an association list to
  763. represent the environment. The \code{interp-R1} function takes the
  764. current environment, \code{env}, as an extra parameter. When the
  765. interpreter encounters a variable, it finds the corresponding value
  766. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  767. When the interpreter encounters a \key{let}, it evaluates the
  768. initializing expression, extends the environment with the result bound
  769. to the variable, then evaluates the body of the \key{let}.
  770. \begin{figure}[tbp]
  771. \begin{lstlisting}
  772. (define (interp-R1 env)
  773. (lambda (e)
  774. (define recur (interp-R1 env))
  775. (match e
  776. [(? symbol?) (lookup e env)]
  777. [`(let ([,x ,(app recur v)]) ,body)
  778. (define new-env (cons (cons x v) env))
  779. ((interp-R1 new-env) body)]
  780. [(? fixnum?) e]
  781. [`(read)
  782. (define r (read))
  783. (cond [(fixnum? r) r]
  784. [else (error 'interp-R1 "expected an integer" r)])]
  785. [`(- ,(app recur v))
  786. (fx- 0 v)]
  787. [`(+ ,(app recur v1) ,(app recur v2))
  788. (fx+ v1 v2)]
  789. [`(program ,e) ((interp-R1 '()) e)]
  790. )))
  791. \end{lstlisting}
  792. \caption{Interpreter for the $R_1$ language.}
  793. \label{fig:interp-R1}
  794. \end{figure}
  795. The goal for this chapter is to implement a compiler that translates
  796. any program $P_1$ in the $R_1$ language into an x86 assembly
  797. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  798. computer as the $R_1$ program running in a Racket implementation.
  799. That is, they both output the same integer $n$.
  800. \[
  801. \begin{tikzpicture}[baseline=(current bounding box.center)]
  802. \node (p1) at (0, 0) {$P_1$};
  803. \node (p2) at (4, 0) {$P_2$};
  804. \node (o) at (4, -2) {$n$};
  805. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  806. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  807. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  808. \end{tikzpicture}
  809. \]
  810. In the next section we introduce enough of the x86 assembly
  811. language to compile $R_1$.
  812. \section{The x86 Assembly Language}
  813. \label{sec:x86}
  814. An x86 program is a sequence of instructions. The program is stored in
  815. the computer's memory and the \emph{program counter} points to the
  816. address of the next instruction to be executed. For most instructions,
  817. once the instruction is executed, the program counter is incremented
  818. to point to the immediately following instruction in the program.
  819. Each instruction may refer to integer constants (called
  820. \emph{immediate values}), variables called \emph{registers}, and
  821. instructions may load and store values into memory. For our purposes,
  822. we can think of the computer's memory as a mapping of 64-bit addresses
  823. to 64-bit values. Figure~\ref{fig:x86-a} defines the syntax for the
  824. subset of the x86 assembly language needed for this chapter. (We use
  825. the AT\&T syntax expected by the GNU assembler inside \key{gcc}.)
  826. Also, Appendix~\ref{sec:x86-quick-reference} includes a
  827. quick-reference of all the x86 instructions used in this book and a
  828. short explanation of what they do.
  829. % to do: finish treatment of imulq
  830. % it's needed for vector's in R6/R7
  831. \begin{figure}[tp]
  832. \fbox{
  833. \begin{minipage}{0.96\textwidth}
  834. \[
  835. \begin{array}{lcl}
  836. \Reg &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  837. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  838. && \key{r8} \mid \key{r9} \mid \key{r10}
  839. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  840. \mid \key{r14} \mid \key{r15} \\
  841. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  842. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  843. \key{subq} \; \Arg, \Arg \mid
  844. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  845. && \key{callq} \; \mathit{label} \mid
  846. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  847. \Prog &::= & \key{.globl main}\\
  848. & & \key{main:} \; \Instr^{+}
  849. \end{array}
  850. \]
  851. \end{minipage}
  852. }
  853. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  854. \label{fig:x86-a}
  855. \end{figure}
  856. An immediate value is written using the notation \key{\$}$n$ where $n$
  857. is an integer.
  858. %
  859. A register is written with a \key{\%} followed by the register name,
  860. such as \key{\%rax}.
  861. %
  862. An access to memory is specified using the syntax $n(\key{\%}r)$,
  863. which reads register $r$ and then offsets the address by $n$ bytes
  864. (8 bits). The address is then used to either load or store to memory
  865. depending on whether it occurs as a source or destination argument of
  866. an instruction.
  867. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  868. source $s$ and destination $d$, applies the arithmetic operation, then
  869. writes the result in $d$.
  870. %
  871. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  872. result in $d$.
  873. %
  874. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  875. specified by the label.
  876. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  877. to \code{(+ 10 32)}. The \key{globl} directive says that the
  878. \key{main} procedure is externally visible, which is necessary so
  879. that the operating system can call it. The label \key{main:}
  880. indicates the beginning of the \key{main} procedure which is where
  881. the operating system starts executing this program. The instruction
  882. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  883. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  884. $10$ in \key{rax} and puts the result, $42$, back into
  885. \key{rax}. The instruction \lstinline{movq %rax, %rdi} moves the value
  886. in \key{rax} into another register, \key{rdi}, and
  887. \lstinline{callq print_int} calls the external function \code{print\_int}, which
  888. prints the value in \key{rdi}.
  889. The instruction \key{retq} finishes the \key{main}
  890. function by returning the integer in \key{rax} to the
  891. operating system.
  892. %\begin{wrapfigure}{r}{2.25in}
  893. \begin{figure}[tbp]
  894. \begin{lstlisting}
  895. .globl main
  896. main:
  897. movq $10, %rax
  898. addq $32, %rax
  899. movq %rax, %rdi
  900. callq print_int
  901. retq
  902. \end{lstlisting}
  903. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  904. \label{fig:p0-x86}
  905. %\end{wrapfigure}
  906. \end{figure}
  907. %% \marginpar{Consider using italics for the texts in these figures.
  908. %% It can get confusing to differentiate them from the main text.}
  909. %% It looks pretty ugly in italics.-Jeremy
  910. Unfortunately, x86 varies in a couple ways depending on what
  911. operating system it is assembled in. The code examples shown here are
  912. correct on the Unix platform, but when assembled on Mac OS X, labels
  913. like \key{main} must be prefixed with an underscore. So the correct
  914. output for the above program on Mac would begin with:
  915. \begin{lstlisting}
  916. .globl _main
  917. _main:
  918. ...
  919. \end{lstlisting}
  920. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  921. lists an x86 program that is equivalent to $\BINOP{+}{52}{
  922. \UNIOP{-}{10} }$. To understand how this x86 program works, we
  923. need to explain a region of memory called the \emph{procedure call
  924. stack} (or \emph{stack} for short). The stack consists of a separate
  925. \emph{frame} for each procedure call. The memory layout for an
  926. individual frame is shown in Figure~\ref{fig:frame}. The register
  927. \key{rsp} is called the \emph{stack pointer} and points to the item at
  928. the top of the stack. The stack grows downward in memory, so we
  929. increase the size of the stack by subtracting from the stack
  930. pointer. The frame size is required to be a multiple of 16 bytes. The
  931. register \key{rbp} is the \emph{base pointer} which serves two
  932. purposes: 1) it saves the location of the stack pointer for the
  933. procedure that called the current one and 2) it is used to access
  934. variables associated with the current procedure. We number the
  935. variables from $1$ to $n$. Variable $1$ is stored at address
  936. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  937. %\begin{wrapfigure}{r}{2.1in}
  938. \begin{figure}[tbp]
  939. \begin{lstlisting}
  940. .globl main
  941. main:
  942. pushq %rbp
  943. movq %rsp, %rbp
  944. subq $16, %rsp
  945. movq $10, -8(%rbp)
  946. negq -8(%rbp)
  947. movq $52, %rax
  948. addq -8(%rbp), %rax
  949. movq %rax, %rdi
  950. callq print_int
  951. addq $16, %rsp
  952. popq %rbp
  953. retq
  954. \end{lstlisting}
  955. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  956. \label{fig:p1-x86}
  957. \end{figure}
  958. %\end{wrapfigure}
  959. \begin{figure}[tbp]
  960. \centering
  961. \begin{tabular}{|r|l|} \hline
  962. Position & Contents \\ \hline
  963. 8(\key{\%rbp}) & return address \\
  964. 0(\key{\%rbp}) & old \key{rbp} \\
  965. -8(\key{\%rbp}) & variable $1$ \\
  966. -16(\key{\%rbp}) & variable $2$ \\
  967. \ldots & \ldots \\
  968. 0(\key{\%rsp}) & variable $n$\\ \hline
  969. \end{tabular}
  970. \caption{Memory layout of a frame.}
  971. \label{fig:frame}
  972. \end{figure}
  973. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  974. three instructions are the typical \emph{prelude} for a procedure.
  975. The instruction \key{pushq \%rbp} saves the base pointer for the
  976. procedure that called the current one onto the stack and subtracts $8$
  977. from the stack pointer. The second instruction \key{movq \%rsp, \%rbp}
  978. changes the base pointer to the top of the stack. The instruction
  979. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  980. room for storing variables. This program just needs one variable ($8$
  981. bytes) but because the frame size is required to be a multiple of 16
  982. bytes, it rounds to 16 bytes.
  983. The next four instructions carry out the work of computing
  984. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  985. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  986. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  987. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  988. adds the contents of variable $1$ to \key{rax}, at which point
  989. \key{rax} contains $42$.
  990. The last five instructions are the typical \emph{conclusion} of a
  991. procedure. The first two print the final result of the program. The
  992. latter three are necessary to get the state of the machine back to
  993. where it was before the current procedure was called. The \key{addq
  994. \$16, \%rsp} instruction moves the stack pointer back to point at
  995. the old base pointer. The amount added here needs to match the amount
  996. that was subtracted in the prelude of the procedure. Then \key{popq
  997. \%rbp} returns the old base pointer to \key{rbp} and adds $8$ to the
  998. stack pointer. The \key{retq} instruction jumps back to the procedure
  999. that called this one and subtracts 8 from the stack pointer.
  1000. The compiler will need a convenient representation for manipulating
  1001. x86 programs, so we define an abstract syntax for x86 in
  1002. Figure~\ref{fig:x86-ast-a}. The $\Int$ field of the \key{program} AST
  1003. node is number of bytes of stack space needed for variables in the
  1004. program. (Some of the intermediate languages will store other
  1005. information in that location for the purposes of communicating
  1006. auxiliary data from one step of the compiler to the next. )
  1007. \begin{figure}[tp]
  1008. \fbox{
  1009. \begin{minipage}{0.96\textwidth}
  1010. \[
  1011. \begin{array}{lcl}
  1012. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1013. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1014. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1015. (\key{subq} \; \Arg\; \Arg) \mid
  1016. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) \\
  1017. &\mid& (\key{callq} \; \mathit{label}) \mid
  1018. (\key{pushq}\;\Arg) \mid
  1019. (\key{popq}\;\Arg) \mid
  1020. (\key{retq}) \\
  1021. x86_0 &::= & (\key{program} \;\Int \; \Instr^{+})
  1022. \end{array}
  1023. \]
  1024. \end{minipage}
  1025. }
  1026. \caption{Abstract syntax for x86 assembly.}
  1027. \label{fig:x86-ast-a}
  1028. \end{figure}
  1029. \section{Planning the trip to x86 via the $C_0$ language}
  1030. \label{sec:plan-s0-x86}
  1031. To compile one language to another it helps to focus on the
  1032. differences between the two languages. It is these differences that
  1033. the compiler will need to bridge. What are the differences between
  1034. $R_1$ and x86 assembly? Here we list some of the most important the
  1035. differences.
  1036. \begin{enumerate}
  1037. \item x86 arithmetic instructions typically take two arguments and
  1038. update the second argument in place. In contrast, $R_1$ arithmetic
  1039. operations only read their arguments and produce a new value.
  1040. \item An argument to an $R_1$ operator can be any expression, whereas
  1041. x86 instructions restrict their arguments to integers, registers,
  1042. and memory locations.
  1043. \item An $R_1$ program can have any number of variables whereas x86
  1044. has only 16 registers.
  1045. \item Variables in $R_1$ can overshadow other variables with the same
  1046. name. The registers and memory locations of x86 all have unique
  1047. names.
  1048. \end{enumerate}
  1049. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1050. the problem into several steps, dealing with the above differences one
  1051. at a time. The main question then becomes: in what order do we tackle
  1052. these differences? This is often one of the most challenging questions
  1053. that a compiler writer must answer because some orderings may be much
  1054. more difficult to implement than others. It is difficult to know ahead
  1055. of time which orders will be better so often some trial-and-error is
  1056. involved. However, we can try to plan ahead and choose the orderings
  1057. based on this planning.
  1058. For example, to handle difference \#2 (nested expressions), we shall
  1059. introduce new variables and pull apart the nested expressions into a
  1060. sequence of assignment statements. To deal with difference \#3 we
  1061. will be replacing variables with registers and/or stack
  1062. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  1063. \#3 can replace both the original variables and the new ones. Next,
  1064. consider where \#1 should fit in. Because it has to do with the format
  1065. of x86 instructions, it makes more sense after we have flattened the
  1066. nested expressions (\#2). Finally, when should we deal with \#4
  1067. (variable overshadowing)? We shall solve this problem by renaming
  1068. variables to make sure they have unique names. Recall that our plan
  1069. for \#2 involves moving nested expressions, which could be problematic
  1070. if it changes the shadowing of variables. However, if we deal with \#4
  1071. first, then it will not be an issue. Thus, we arrive at the following
  1072. ordering.
  1073. \[
  1074. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1075. \foreach \i/\p in {4/1,2/2,1/3,3/4}
  1076. {
  1077. \node (\i) at (\p*1.5,0) {$\i$};
  1078. }
  1079. \foreach \x/\y in {4/2,2/1,1/3}
  1080. {
  1081. \draw[->] (\x) to (\y);
  1082. }
  1083. \end{tikzpicture}
  1084. \]
  1085. We further simplify the translation from $R_1$ to x86 by identifying
  1086. an intermediate language named $C_0$, roughly half-way between $R_1$
  1087. and x86, to provide a rest stop along the way. We name the language
  1088. $C_0$ because it is vaguely similar to the $C$
  1089. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  1090. regarding variables and nested expressions, will be handled by two
  1091. steps, \key{uniquify} and \key{flatten}, which bring us to
  1092. $C_0$.
  1093. \[
  1094. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1095. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  1096. {
  1097. \node (\p) at (\p*3,0) {\large $\i$};
  1098. }
  1099. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  1100. {
  1101. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  1102. }
  1103. \end{tikzpicture}
  1104. \]
  1105. Each of these steps in the compiler is implemented by a function,
  1106. typically a structurally recursive function that translates an input
  1107. AST into an output AST. We refer to such a function as a \emph{pass}
  1108. because it makes a pass over, i.e. it traverses the entire AST.
  1109. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1110. $C_0$ language supports the same operators as $R_1$ but the arguments
  1111. of operators are now restricted to just variables and integers. The
  1112. \key{let} construct of $R_1$ is replaced by an assignment statement
  1113. and there is a \key{return} construct to specify the return value of
  1114. the program. A program consists of a sequence of statements that
  1115. include at least one \key{return} statement. Each program is also
  1116. annotated with a list of variables (viz. {\tt (var*)}). At the start
  1117. of the program, these variables are uninitialized (they contain garbage)
  1118. and each variable becomes initialized on its first assignment. All of
  1119. the variables used in the program must be present in this list.
  1120. \begin{figure}[tp]
  1121. \fbox{
  1122. \begin{minipage}{0.96\textwidth}
  1123. \[
  1124. \begin{array}{lcl}
  1125. \Arg &::=& \Int \mid \Var \\
  1126. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1127. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1128. C_0 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  1129. \end{array}
  1130. \]
  1131. \end{minipage}
  1132. }
  1133. \caption{The $C_0$ intermediate language.}
  1134. \label{fig:c0-syntax}
  1135. \end{figure}
  1136. To get from $C_0$ to x86 assembly it remains for us to handle
  1137. difference \#1 (the format of instructions) and difference \#3
  1138. (variables versus registers). These two differences are intertwined,
  1139. creating a bit of a Gordian Knot. To handle difference \#3, we need to
  1140. map some variables to registers (there are only 16 registers) and the
  1141. remaining variables to locations on the stack (which is unbounded). To
  1142. make good decisions regarding this mapping, we need the program to be
  1143. close to its final form (in x86 assembly) so we know exactly when
  1144. which variables are used. After all, variables that are used in
  1145. disjoint parts of the program can be assigned to the same register.
  1146. However, our choice of x86 instructions depends on whether the
  1147. variables are mapped to registers or stack locations, so we have a
  1148. circular dependency. We cut this knot by doing an optimistic selection
  1149. of instructions in the \key{select-instructions} pass, followed by the
  1150. \key{assign-homes} pass to map variables to registers or stack
  1151. locations, and conclude by finalizing the instruction selection in the
  1152. \key{patch-instructions} pass.
  1153. \[
  1154. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1155. \node (1) at (0,0) {\large $C_0$};
  1156. \node (2) at (3,0) {\large $\text{x86}^{*}$};
  1157. \node (3) at (6,0) {\large $\text{x86}^{*}$};
  1158. \node (4) at (9,0) {\large $\text{x86}$};
  1159. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  1160. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  1161. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  1162. \end{tikzpicture}
  1163. \]
  1164. The \key{select-instructions} pass is optimistic in the sense that it
  1165. treats variables as if they were all mapped to registers. The
  1166. \key{select-instructions} pass generates a program that consists of
  1167. x86 instructions but that still uses variables, so it is an
  1168. intermediate language that is technically different than x86, which
  1169. explains the asterisks in the diagram above.
  1170. In this Chapter we shall take the easy road to implementing
  1171. \key{assign-homes} and simply map all variables to stack locations.
  1172. The topic of Chapter~\ref{ch:register-allocation} is implementing a
  1173. smarter approach in which we make a best-effort to map variables to
  1174. registers, resorting to the stack only when necessary.
  1175. %% \marginpar{\scriptsize I'm confused: shouldn't `select instructions' do this?
  1176. %% After all, that selects the x86 instructions. Even if it is separate,
  1177. %% if we perform `patching' before register allocation, we aren't forced to rely on
  1178. %% \key{rax} as much. This can ultimately make a more-performant result. --
  1179. %% Cam}
  1180. Once variables have been assigned to their homes, we can finalize the
  1181. instruction selection by dealing with an idiosyncrasy of x86
  1182. assembly. Many x86 instructions have two arguments but only one of the
  1183. arguments may be a memory reference (and the stack is a part of
  1184. memory). Because some variables may get mapped to stack locations,
  1185. some of our generated instructions may violate this restriction. The
  1186. purpose of the \key{patch-instructions} pass is to fix this problem by
  1187. replacing every violating instruction with a short sequence of
  1188. instructions that use the \key{rax} register. Once we have implemented
  1189. a good register allocator (Chapter~\ref{ch:register-allocation}), the
  1190. need to patch instructions will be relatively rare.
  1191. \section{Uniquify Variables}
  1192. \label{sec:uniquify-s0}
  1193. The purpose of this pass is to make sure that each \key{let} uses a
  1194. unique variable name. For example, the \code{uniquify} pass should
  1195. translate the program on the left into the program on the right. \\
  1196. \begin{tabular}{lll}
  1197. \begin{minipage}{0.4\textwidth}
  1198. \begin{lstlisting}
  1199. (program
  1200. (let ([x 32])
  1201. (+ (let ([x 10]) x) x)))
  1202. \end{lstlisting}
  1203. \end{minipage}
  1204. &
  1205. $\Rightarrow$
  1206. &
  1207. \begin{minipage}{0.4\textwidth}
  1208. \begin{lstlisting}
  1209. (program
  1210. (let ([x.1 32])
  1211. (+ (let ([x.2 10]) x.2) x.1)))
  1212. \end{lstlisting}
  1213. \end{minipage}
  1214. \end{tabular} \\
  1215. %
  1216. The following is another example translation, this time of a program
  1217. with a \key{let} nested inside the initializing expression of another
  1218. \key{let}.\\
  1219. \begin{tabular}{lll}
  1220. \begin{minipage}{0.4\textwidth}
  1221. \begin{lstlisting}
  1222. (program
  1223. (let ([x (let ([x 4])
  1224. (+ x 1))])
  1225. (+ x 2)))
  1226. \end{lstlisting}
  1227. \end{minipage}
  1228. &
  1229. $\Rightarrow$
  1230. &
  1231. \begin{minipage}{0.4\textwidth}
  1232. \begin{lstlisting}
  1233. (program
  1234. (let ([x.2 (let ([x.1 4])
  1235. (+ x.1 1))])
  1236. (+ x.2 2)))
  1237. \end{lstlisting}
  1238. \end{minipage}
  1239. \end{tabular}
  1240. We recommend implementing \code{uniquify} as a structurally recursive
  1241. function that mostly copies the input program. However, when
  1242. encountering a \key{let}, it should generate a unique name for the
  1243. variable (the Racket function \code{gensym} is handy for this) and
  1244. associate the old name with the new unique name in an association
  1245. list. The \code{uniquify} function will need to access this
  1246. association list when it gets to a variable reference, so we add
  1247. another parameter to \code{uniquify} for the association list. It is
  1248. quite common for a compiler pass to need a map to store extra
  1249. information about variables. Such maps are often called \emph{symbol
  1250. tables}.
  1251. The skeleton of the \code{uniquify} function is shown in
  1252. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1253. convenient to partially apply it to an association list and then apply
  1254. it to different expressions, as in the last clause for primitive
  1255. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1256. clause for the primitive operators, note the use of the comma-@
  1257. operator to splice a list of S-expressions into an enclosing
  1258. S-expression.
  1259. \begin{exercise}
  1260. \normalfont % I don't like the italics for exercises. -Jeremy
  1261. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1262. implement the clauses for variables and for the \key{let} construct.
  1263. \end{exercise}
  1264. \begin{figure}[tbp]
  1265. \begin{lstlisting}
  1266. (define (uniquify alist)
  1267. (lambda (e)
  1268. (match e
  1269. [(? symbol?) ___]
  1270. [(? integer?) e]
  1271. [`(let ([,x ,e]) ,body) ___]
  1272. [`(program ,e)
  1273. `(program ,((uniquify alist) e))]
  1274. [`(,op ,es ...)
  1275. `(,op ,@(map (uniquify alist) es))]
  1276. )))
  1277. \end{lstlisting}
  1278. \caption{Skeleton for the \key{uniquify} pass.}
  1279. \label{fig:uniquify-s0}
  1280. \end{figure}
  1281. \begin{exercise}
  1282. \normalfont % I don't like the italics for exercises. -Jeremy
  1283. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1284. and checking whether the output programs produce the same result as
  1285. the input programs. The $R_1$ programs should be designed to test the
  1286. most interesting parts of the \key{uniquify} pass, that is, the
  1287. programs should include \key{let} constructs, variables, and variables
  1288. that overshadow each other. The five programs should be in a
  1289. subdirectory named \key{tests} and they should have the same file name
  1290. except for a different integer at the end of the name, followed by the
  1291. ending \key{.rkt}. Use the \key{interp-tests} function
  1292. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1293. your \key{uniquify} pass on the example programs.
  1294. \end{exercise}
  1295. \section{Flatten Expressions}
  1296. \label{sec:flatten-r1}
  1297. The \code{flatten} pass will transform $R_1$ programs into $C_0$
  1298. programs. In particular, the purpose of the \code{flatten} pass is to
  1299. get rid of nested expressions, such as the \code{(- 10)} in the program
  1300. below. This can be accomplished by introducing a new variable,
  1301. assigning the nested expression to the new variable, and then using
  1302. the new variable in place of the nested expressions, as shown in the
  1303. output of \code{flatten} on the right.\\
  1304. \begin{tabular}{lll}
  1305. \begin{minipage}{0.4\textwidth}
  1306. \begin{lstlisting}
  1307. (program
  1308. (+ 52 (- 10)))
  1309. \end{lstlisting}
  1310. \end{minipage}
  1311. &
  1312. $\Rightarrow$
  1313. &
  1314. \begin{minipage}{0.4\textwidth}
  1315. \begin{lstlisting}
  1316. (program (tmp.1 tmp.2)
  1317. (assign tmp.1 (- 10))
  1318. (assign tmp.2 (+ 52 tmp.1))
  1319. (return tmp.2))
  1320. \end{lstlisting}
  1321. \end{minipage}
  1322. \end{tabular}
  1323. The clause of \code{flatten} for \key{let} is straightforward to
  1324. implement as it just requires the generation of an assignment
  1325. statement for the \key{let}-bound variable. The following shows the
  1326. result of \code{flatten} for a \key{let}. \\
  1327. \begin{tabular}{lll}
  1328. \begin{minipage}{0.4\textwidth}
  1329. \begin{lstlisting}
  1330. (program
  1331. (let ([x (+ (- 10) 11)])
  1332. (+ x 41)))
  1333. \end{lstlisting}
  1334. \end{minipage}
  1335. &
  1336. $\Rightarrow$
  1337. &
  1338. \begin{minipage}{0.4\textwidth}
  1339. \begin{lstlisting}
  1340. (program (tmp.1 x tmp.2)
  1341. (assign tmp.1 (- 10))
  1342. (assign x (+ tmp.1 11))
  1343. (assign tmp.2 (+ x 41))
  1344. (return tmp.2))
  1345. \end{lstlisting}
  1346. \end{minipage}
  1347. \end{tabular}
  1348. We recommend implementing \key{flatten} as a structurally recursive
  1349. function that returns three things, 1) the newly flattened expression,
  1350. 2) a list of assignment statements, one for each of the new variables
  1351. introduced during the flattening the expression, and 3) a list of all
  1352. the variables including both let-bound variables and the generated
  1353. temporary variables. The newly flattened expression should be an
  1354. $\Arg$ in the $C_0$ syntax (Figure~\ref{fig:c0-syntax}), that is, it
  1355. should be an integer or a variable. You can return multiple things
  1356. from a function using the \key{values} form and you can receive
  1357. multiple things from a function call using the \key{define-values}
  1358. form. If you are not familiar with these constructs, the Racket
  1359. documentation will be of help. Also, the \key{map3} function
  1360. (Appendix~\ref{appendix:utilities}) is useful for applying a function
  1361. to each element of a list, in the case where the function returns
  1362. three values. The result of \key{map3} is three lists.
  1363. The clause of \key{flatten} for the \key{program} node needs to
  1364. recursively flatten the body of the program and the newly flattened
  1365. expression should be placed in a \key{return} statement. The
  1366. \key{flatten} pass should also compute the list of variables used in
  1367. the program. I recommend traversing the statements in the body of the
  1368. program (after it has been flattened) and collect all variables that
  1369. appear on the left-hand-side of an assignment. Note that each variable
  1370. should only occur once in the list of variables that you place in the
  1371. \key{program} form.
  1372. Take special care for programs such as the following that initialize
  1373. variables with integers or other variables. It should be translated
  1374. to the program on the right \\
  1375. \begin{tabular}{lll}
  1376. \begin{minipage}{0.4\textwidth}
  1377. \begin{lstlisting}
  1378. (let ([a 42])
  1379. (let ([b a])
  1380. b))
  1381. \end{lstlisting}
  1382. \end{minipage}
  1383. &
  1384. $\Rightarrow$
  1385. &
  1386. \begin{minipage}{0.4\textwidth}
  1387. \begin{lstlisting}
  1388. (program (a b)
  1389. (assign a 42)
  1390. (assign b a)
  1391. (return b))
  1392. \end{lstlisting}
  1393. \end{minipage}
  1394. \end{tabular} \\
  1395. and not to the following, which could result from a naive
  1396. implementation of \key{flatten}.
  1397. \begin{lstlisting}
  1398. (program (tmp.1 a tmp.2 b)
  1399. (assign tmp.1 42)
  1400. (assign a tmp.1)
  1401. (assign tmp.2 a)
  1402. (assign b tmp.2)
  1403. (return b))
  1404. \end{lstlisting}
  1405. \begin{exercise}
  1406. \normalfont
  1407. Implement the \key{flatten} pass and test it on all of the example
  1408. programs that you created to test the \key{uniquify} pass and create
  1409. three new example programs that are designed to exercise all of the
  1410. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1411. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1412. test your passes on the example programs.
  1413. \end{exercise}
  1414. \section{Select Instructions}
  1415. \label{sec:select-s0}
  1416. In the \key{select-instructions} pass we begin the work of translating
  1417. from $C_0$ to x86. The target language of this pass is a pseudo-x86
  1418. language that still uses variables, so we add an AST node of the form
  1419. $\VAR{\itm{var}}$ to the x86 abstract syntax. Also, the \key{program}
  1420. form should still list the variables (similar to $C_0$):
  1421. \[
  1422. (\key{program}\;(\Var^{*})\;\Instr^{+})
  1423. \]
  1424. The \key{select-instructions} pass deals with the differing format of
  1425. arithmetic operations. For example, in $C_0$ an addition operation can
  1426. take the form below. To translate to x86, we need to use the
  1427. \key{addq} instruction which does an in-place update. So we must first
  1428. move \code{10} to \code{x}. \\
  1429. \begin{tabular}{lll}
  1430. \begin{minipage}{0.4\textwidth}
  1431. \begin{lstlisting}
  1432. (assign x (+ 10 32))
  1433. \end{lstlisting}
  1434. \end{minipage}
  1435. &
  1436. $\Rightarrow$
  1437. &
  1438. \begin{minipage}{0.4\textwidth}
  1439. \begin{lstlisting}
  1440. (movq (int 10) (var x))
  1441. (addq (int 32) (var x))
  1442. \end{lstlisting}
  1443. \end{minipage}
  1444. \end{tabular} \\
  1445. There are some cases that require special care to avoid generating
  1446. needlessly complicated code. If one of the arguments is the same as
  1447. the left-hand side of the assignment, then there is no need for the
  1448. extra move instruction. For example, the following assignment
  1449. statement can be translated into a single \key{addq} instruction.\\
  1450. \begin{tabular}{lll}
  1451. \begin{minipage}{0.4\textwidth}
  1452. \begin{lstlisting}
  1453. (assign x (+ 10 x))
  1454. \end{lstlisting}
  1455. \end{minipage}
  1456. &
  1457. $\Rightarrow$
  1458. &
  1459. \begin{minipage}{0.4\textwidth}
  1460. \begin{lstlisting}
  1461. (addq (int 10) (var x))
  1462. \end{lstlisting}
  1463. \end{minipage}
  1464. \end{tabular} \\
  1465. The \key{read} operation does not have a direct counterpart in x86
  1466. assembly, so we have instead implemented this functionality in the C
  1467. language, with the function \code{read\_int} in the file
  1468. \code{runtime.c}. In general, we refer to all of the functionality in
  1469. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1470. for short. When compiling your generated x86 assembly code, you
  1471. will need to compile \code{runtime.c} to \code{runtime.o} (an ``object
  1472. file'', using \code{gcc} option \code{-c}) and link it into the final
  1473. executable. For our purposes of code generation, all you need to do is
  1474. translate an assignment of \key{read} to some variable $\itm{lhs}$
  1475. (for left-hand side) into a call to the \code{read\_int} function
  1476. followed by a move from \code{rax} to the left-hand side. The move
  1477. from \code{rax} is needed because the return value from
  1478. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1479. \begin{tabular}{lll}
  1480. \begin{minipage}{0.4\textwidth}
  1481. \begin{lstlisting}
  1482. (assign |$\itm{lhs}$| (read))
  1483. \end{lstlisting}
  1484. \end{minipage}
  1485. &
  1486. $\Rightarrow$
  1487. &
  1488. \begin{minipage}{0.4\textwidth}
  1489. \begin{lstlisting}
  1490. (callq read_int)
  1491. (movq (reg rax) (var |$\itm{lhs}$|))
  1492. \end{lstlisting}
  1493. \end{minipage}
  1494. \end{tabular} \\
  1495. Regarding the \RETURN{\Arg} statement of $C_0$, we recommend treating it
  1496. as an assignment to the \key{rax} register and let the procedure
  1497. conclusion handle the transfer of control back to the calling
  1498. procedure.
  1499. \begin{exercise}
  1500. \normalfont
  1501. Implement the \key{select-instructions} pass and test it on all of the
  1502. example programs that you created for the previous passes and create
  1503. three new example programs that are designed to exercise all of the
  1504. interesting code in this pass. Use the \key{interp-tests} function
  1505. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1506. your passes on the example programs.
  1507. \end{exercise}
  1508. \section{Assign Homes}
  1509. \label{sec:assign-s0}
  1510. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1511. \key{assign-homes} pass places all of the variables on the stack.
  1512. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1513. which after \key{select-instructions} looks like the following.
  1514. \begin{lstlisting}
  1515. (movq (int 10) (var tmp.1))
  1516. (negq (var tmp.1))
  1517. (movq (var tmp.1) (var tmp.2))
  1518. (addq (int 52) (var tmp.2))
  1519. (movq (var tmp.2) (reg rax)))
  1520. \end{lstlisting}
  1521. The variable \code{tmp.1} is assigned to stack location
  1522. \code{-8(\%rbp)}, and \code{tmp.2} is assign to \code{-16(\%rbp)}, so
  1523. the \code{assign-homes} pass translates the above to
  1524. \begin{lstlisting}
  1525. (movq (int 10) (deref rbp -16))
  1526. (negq (deref rbp -16))
  1527. (movq (deref rbp -16) (deref rbp -8))
  1528. (addq (int 52) (deref rbp -8))
  1529. (movq (deref rbp -8) (reg rax)))
  1530. \end{lstlisting}
  1531. In the process of assigning stack locations to variables, it is
  1532. convenient to compute and store the size of the frame (in bytes) in
  1533. the first field of the \key{program} node which will be needed later
  1534. to generate the procedure conclusion.
  1535. \[
  1536. (\key{program}\;\Int\;\Instr^{+})
  1537. \]
  1538. Some operating systems place restrictions on
  1539. the frame size. For example, Mac OS X requires the frame size to be a
  1540. multiple of 16 bytes.
  1541. \begin{exercise}
  1542. \normalfont Implement the \key{assign-homes} pass and test it on all
  1543. of the example programs that you created for the previous passes pass.
  1544. I recommend that \key{assign-homes} take an extra parameter that is a
  1545. mapping of variable names to homes (stack locations for now). Use the
  1546. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1547. \key{utilities.rkt} to test your passes on the example programs.
  1548. \end{exercise}
  1549. \section{Patch Instructions}
  1550. \label{sec:patch-s0}
  1551. The purpose of this pass is to make sure that each instruction adheres
  1552. to the restrictions regarding which arguments can be memory
  1553. references. For most instructions, the rule is that at most one
  1554. argument may be a memory reference.
  1555. Consider again the following example.
  1556. \begin{lstlisting}
  1557. (let ([a 42])
  1558. (let ([b a])
  1559. b))
  1560. \end{lstlisting}
  1561. After \key{assign-homes} pass, the above has been translated to
  1562. \begin{lstlisting}
  1563. (movq (int 42) (deref rbp -8))
  1564. (movq (deref rbp -8) (deref rbp -16))
  1565. (movq (deref rbp -16) (reg rax))
  1566. \end{lstlisting}
  1567. The second \key{movq} instruction is problematic because both
  1568. arguments are stack locations. We suggest fixing this problem by
  1569. moving from the source to the register \key{rax} and then from
  1570. \key{rax} to the destination, as follows.
  1571. \begin{lstlisting}
  1572. (movq (int 42) (deref rbp -8))
  1573. (movq (deref rbp -8) (reg rax))
  1574. (movq (reg rax) (deref rbp -16))
  1575. (movq (deref rbp -16) (reg rax))
  1576. \end{lstlisting}
  1577. \begin{exercise}
  1578. \normalfont
  1579. Implement the \key{patch-instructions} pass and test it on all of the
  1580. example programs that you created for the previous passes and create
  1581. three new example programs that are designed to exercise all of the
  1582. interesting code in this pass. Use the \key{interp-tests} function
  1583. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1584. your passes on the example programs.
  1585. \end{exercise}
  1586. \section{Print x86}
  1587. \label{sec:print-x86}
  1588. The last step of the compiler from $R_1$ to x86 is to convert the
  1589. x86 AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1590. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1591. \key{format} and \key{string-append} functions are useful in this
  1592. regard. The main work that this step needs to perform is to create the
  1593. \key{main} function and the standard instructions for its prelude
  1594. and conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1595. Section~\ref{sec:x86}. You need to know the number of
  1596. stack-allocated variables, for which it is suggest that you compute in
  1597. the \key{assign-homes} pass (Section~\ref{sec:assign-s0}) and store in
  1598. the $\itm{info}$ field of the \key{program} node.
  1599. Your compiled code should print the result of the program's execution by using the
  1600. \code{print\_int} function provided in \code{runtime.c}. If your compiler has been implemented correctly so far, this final result should be stored in the \key{rax} register.
  1601. We'll talk more about
  1602. how to perform function calls with arguments in general later on, but
  1603. for now, make sure that your x86 printer includes the following code as part of the conclusion:
  1604. \begin{lstlisting}
  1605. movq %rax, %rdi
  1606. callq print_int
  1607. \end{lstlisting}
  1608. These lines move the value in \key{rax} into the \key{rdi} register, which
  1609. stores the first argument to be passed into \key{print\_int}.
  1610. If you want your program to run on Mac OS X, your code needs to
  1611. determine whether or not it is running on a Mac, and prefix
  1612. underscores to labels like \key{main}. You can determine the platform
  1613. with the Racket call \code{(system-type 'os)}, which returns
  1614. \code{'macosx}, \code{'unix}, or \code{'windows}. In addition to
  1615. placing underscores on \key{main}, you need to put them in front of
  1616. \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1617. \_print\_int}).
  1618. \begin{exercise}
  1619. \normalfont Implement the \key{print-x86} pass and test it on all of
  1620. the example programs that you created for the previous passes. Use the
  1621. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1622. \key{utilities.rkt} to test your complete compiler on the example
  1623. programs.
  1624. % The following is specific to P423/P523. -Jeremy
  1625. %Mac support is optional, but your compiler has to output
  1626. %valid code for Unix machines.
  1627. \end{exercise}
  1628. \begin{figure}[p]
  1629. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1630. \node (R1) at (0,2) {\large $R_1$};
  1631. \node (R1-2) at (3,2) {\large $R_1$};
  1632. \node (C0-1) at (3,0) {\large $C_0$};
  1633. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  1634. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  1635. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  1636. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  1637. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1638. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  1639. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1640. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1641. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1642. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1643. \end{tikzpicture}
  1644. \caption{Overview of the passes for compiling $R_1$. }
  1645. \label{fig:R1-passes}
  1646. \end{figure}
  1647. Figure~\ref{fig:R1-passes} provides an overview of all the compiler
  1648. passes described in this Chapter. The x86$^{*}$ language extends x86
  1649. with variables and looser rules regarding instruction arguments. The
  1650. x86$^{\dagger}$ language is the concrete syntax (string) for x86.
  1651. \marginpar{\footnotesize To do: add a challenge section. Perhaps
  1652. extending the partial evaluation to $R_0$? \\ --Jeremy}
  1653. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1654. \chapter{Register Allocation}
  1655. \label{ch:register-allocation}
  1656. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1657. assembly by placing all variables on the stack. We can improve the
  1658. performance of the generated code considerably if we instead try to
  1659. place as many variables as possible into registers. The CPU can
  1660. access a register in a single cycle, whereas accessing the stack takes
  1661. many cycles to go to cache or many more to access main memory.
  1662. Figure~\ref{fig:reg-eg} shows a program with four variables that
  1663. serves as a running example. We show the source program and also the
  1664. output of instruction selection. At that point the program is almost
  1665. x86 assembly but not quite; it still contains variables instead of
  1666. stack locations or registers.
  1667. \begin{figure}
  1668. \begin{minipage}{0.45\textwidth}
  1669. Source program:
  1670. \begin{lstlisting}
  1671. (program
  1672. (let ([v 1])
  1673. (let ([w 46])
  1674. (let ([x (+ v 7)])
  1675. (let ([y (+ 4 x)])
  1676. (let ([z (+ x w)])
  1677. (+ z (- y))))))))
  1678. \end{lstlisting}
  1679. \end{minipage}
  1680. \begin{minipage}{0.45\textwidth}
  1681. After instruction selection:
  1682. \begin{lstlisting}
  1683. (program (v w x y z t.1 t.2)
  1684. (movq (int 1) (var v))
  1685. (movq (int 46) (var w))
  1686. (movq (var v) (var x))
  1687. (addq (int 7) (var x))
  1688. (movq (var x) (var y))
  1689. (addq (int 4) (var y))
  1690. (movq (var x) (var z))
  1691. (addq (var w) (var z))
  1692. (movq (var y) (var t.1))
  1693. (negq (var t.1))
  1694. (movq (var z) (var t.2))
  1695. (addq (var t.1) (var t.2))
  1696. (movq (var t.2) (reg rax)))
  1697. \end{lstlisting}
  1698. \end{minipage}
  1699. \caption{An example program for register allocation.}
  1700. \label{fig:reg-eg}
  1701. \end{figure}
  1702. The goal of register allocation is to fit as many variables into
  1703. registers as possible. It is often the case that we have more
  1704. variables than registers, so we cannot map each variable to a
  1705. different register. Fortunately, it is common for different variables
  1706. to be needed during different periods of time, and in such cases
  1707. several variables can be mapped to the same register. Consider
  1708. variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the
  1709. variable \code{x} is moved to \code{z} it is no longer needed.
  1710. Variable \code{y}, on the other hand, is used only after this point,
  1711. so \code{x} and \code{y} could share the same register. The topic of
  1712. Section~\ref{sec:liveness-analysis} is how we compute where a variable
  1713. is needed. Once we have that information, we compute which variables
  1714. are needed at the same time, i.e., which ones \emph{interfere}, and
  1715. represent this relation as graph whose vertices are variables and
  1716. edges indicate when two variables interfere with eachother
  1717. (Section~\ref{sec:build-interference}). We then model register
  1718. allocation as a graph coloring problem, which we discuss in
  1719. Section~\ref{sec:graph-coloring}.
  1720. In the event that we run out of registers despite these efforts, we
  1721. place the remaining variables on the stack, similar to what we did in
  1722. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  1723. that is assigned to a stack location, it has been \emph{spilled}. The
  1724. process of spilling variables is handled as part of the graph coloring
  1725. process described in \ref{sec:graph-coloring}.
  1726. \section{Liveness Analysis}
  1727. \label{sec:liveness-analysis}
  1728. A variable is \emph{live} if the variable is used at some later point
  1729. in the program and there is not an intervening assignment to the
  1730. variable.
  1731. %
  1732. To understand the latter condition, consider the following code
  1733. fragment in which there are two writes to \code{b}. Are \code{a} and
  1734. \code{b} both live at the same time?
  1735. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1736. (movq (int 5) (var a))
  1737. (movq (int 30) (var b))
  1738. (movq (var a) (var c))
  1739. (movq (int 10) (var b))
  1740. (addq (var b) (var c))
  1741. \end{lstlisting}
  1742. The answer is no because the value \code{30} written to \code{b} on
  1743. line 2 is never used. The variable \code{b} is read on line 5 and
  1744. there is an intervening write to \code{b} on line 4, so the read on
  1745. line 5 receives the value written on line 4, not line 2.
  1746. The live variables can be computed by traversing the instruction
  1747. sequence back to front (i.e., backwards in execution order). Let
  1748. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1749. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1750. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1751. variables before instruction $I_k$. The live variables after an
  1752. instruction are always the same as the live variables before the next
  1753. instruction.
  1754. \begin{equation*}
  1755. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1756. \end{equation*}
  1757. To start things off, there are no live variables after the last
  1758. instruction, so
  1759. \begin{equation*}
  1760. L_{\mathsf{after}}(n) = \emptyset
  1761. \end{equation*}
  1762. We then apply the following rule repeatedly, traversing the
  1763. instruction sequence back to front.
  1764. \begin{equation*}
  1765. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1766. \end{equation*}
  1767. where $W(k)$ are the variables written to by instruction $I_k$ and
  1768. $R(k)$ are the variables read by instruction $I_k$.
  1769. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1770. for the running example, with each instruction aligned with its
  1771. $L_{\mathtt{after}}$ set to make the figure easy to read.
  1772. \marginpar{JM: I think you should walk through the explanation of this formula,
  1773. connecting it back to the example from before. \\
  1774. JS: Agreed.}
  1775. \begin{figure}[tbp]
  1776. \hspace{20pt}
  1777. \begin{minipage}{0.45\textwidth}
  1778. \begin{lstlisting}[numbers=left]
  1779. (program (v w x y z t.1 t.2)
  1780. (movq (int 1) (var v))
  1781. (movq (int 46) (var w))
  1782. (movq (var v) (var x))
  1783. (addq (int 7) (var x))
  1784. (movq (var x) (var y))
  1785. (addq (int 4) (var y))
  1786. (movq (var x) (var z))
  1787. (addq (var w) (var z))
  1788. (movq (var y) (var t.1))
  1789. (negq (var t.1))
  1790. (movq (var z) (var t.2))
  1791. (addq (var t.1) (var t.2))
  1792. (movq (var t.2) (reg rax)))
  1793. \end{lstlisting}
  1794. \end{minipage}
  1795. \vrule\hspace{10pt}
  1796. \begin{minipage}{0.45\textwidth}
  1797. \begin{lstlisting}
  1798. |$\{ v \}$|
  1799. |$\{ v, w \}$|
  1800. |$\{ w, x \}$|
  1801. |$\{ w, x \}$|
  1802. |$\{ w, x, y\}$|
  1803. |$\{ w, x, y \}$|
  1804. |$\{ w, y, z \}$|
  1805. |$\{ y, z \}$|
  1806. |$\{ t.1, z \}$|
  1807. |$\{ t.1, z \}$|
  1808. |$\{t.1,t.2\}$|
  1809. |$\{t.2\}$|
  1810. |$\{\}$|
  1811. \end{lstlisting}
  1812. \end{minipage}
  1813. \caption{An example program annotated with live-after sets.}
  1814. \label{fig:live-eg}
  1815. \end{figure}
  1816. \begin{exercise}\normalfont
  1817. Implement the compiler pass named \code{uncover-live} that computes
  1818. the live-after sets. We recommend storing the live-after sets (a list
  1819. of lists of variables) in the $\itm{info}$ field of the \key{program}
  1820. node alongside the list of variables as follows.
  1821. \begin{lstlisting}
  1822. (program (|$\Var^{*}$| |$\itm{live{-}afters}$|) |$\Instr^{+}$|)
  1823. \end{lstlisting}
  1824. I recommend organizing your code to use a helper function that takes a
  1825. list of statements and an initial live-after set (typically empty) and
  1826. returns the list of statements and the list of live-after sets. For
  1827. this chapter, returning the list of statements is unnecessary, as they
  1828. awill be unchanged, but in Chapter~\ref{ch:bool-types} we introduce
  1829. \key{if} statements and will need to annotate them with the live-after
  1830. sets of the two branches.
  1831. I recommend creating helper functions to 1) compute the set of
  1832. variables that appear in an argument (of an instruction), 2) compute
  1833. the variables read by an instruction which corresponds to the $R$
  1834. function discussed above, and 3) the variables written by an
  1835. instruction which corresponds to $W$.
  1836. \end{exercise}
  1837. \section{Building the Interference Graph}
  1838. \label{sec:build-interference}
  1839. Based on the liveness analysis, we know where each variable is needed.
  1840. However, during register allocation, we need to answer questions of
  1841. the specific form: are variables $u$ and $v$ live at the same time?
  1842. (And therefore cannot be assigned to the same register.) To make this
  1843. question easier to answer, we create an explicit data structure, an
  1844. \emph{interference graph}. An interference graph is an undirected
  1845. graph that has an edge between two variables if they are live at the
  1846. same time, that is, if they interfere with each other.
  1847. The most obvious way to compute the interference graph is to look at
  1848. the set of live variables between each statement in the program, and
  1849. add an edge to the graph for every pair of variables in the same set.
  1850. This approach is less than ideal for two reasons. First, it can be
  1851. rather expensive because it takes $O(n^2)$ time to look at every pair
  1852. in a set of $n$ live variables. Second, there is a special case in
  1853. which two variables that are live at the same time do not actually
  1854. interfere with each other: when they both contain the same value
  1855. because we have assigned one to the other.
  1856. A better way to compute the interference graph is given by the
  1857. following.
  1858. \begin{itemize}
  1859. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  1860. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1861. d$ or $v = s$.
  1862. \item If instruction $I_k$ is not a move but some other arithmetic
  1863. instruction such as (\key{addq} $s$\, $d$), then add the edge $(d,v)$
  1864. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1865. \item If instruction $I_k$ is of the form (\key{callq}
  1866. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1867. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1868. \end{itemize}
  1869. \marginpar{JM: I think you could give examples of each one of these
  1870. using the example program and use those to help explain why these
  1871. rules are correct.\\
  1872. JS: Agreed.}
  1873. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  1874. the following interference for the instruction at the specified line
  1875. number.
  1876. \begin{quote}
  1877. Line 2: no interference,\\
  1878. Line 3: $w$ interferes with $v$,\\
  1879. Line 4: $x$ interferes with $w$,\\
  1880. Line 5: $x$ interferes with $w$,\\
  1881. Line 6: $y$ interferes with $w$,\\
  1882. Line 7: $y$ interferes with $w$ and $x$,\\
  1883. Line 8: $z$ interferes with $w$ and $y$,\\
  1884. Line 9: $z$ interferes with $y$, \\
  1885. Line 10: $t.1$ interferes with $z$, \\
  1886. Line 11: $t.1$ interferes with $z$, \\
  1887. Line 12: $t.2$ interferes with $t.1$, \\
  1888. Line 13: no interference. \\
  1889. Line 14: no interference.
  1890. \end{quote}
  1891. The resulting interference graph is shown in
  1892. Figure~\ref{fig:interfere}.
  1893. \begin{figure}[tbp]
  1894. \large
  1895. \[
  1896. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1897. \node (v) at (0,0) {$v$};
  1898. \node (w) at (2,0) {$w$};
  1899. \node (x) at (4,0) {$x$};
  1900. \node (t1) at (6,0) {$t.1$};
  1901. \node (y) at (2,-2) {$y$};
  1902. \node (z) at (4,-2) {$z$};
  1903. \node (t2) at (6,-2) {$t.2$};
  1904. \draw (v) to (w);
  1905. \foreach \i in {w,x,y}
  1906. {
  1907. \foreach \j in {w,x,y}
  1908. {
  1909. \draw (\i) to (\j);
  1910. }
  1911. }
  1912. \draw (z) to (w);
  1913. \draw (z) to (y);
  1914. \draw (t1) to (z);
  1915. \draw (t2) to (t1);
  1916. \end{tikzpicture}
  1917. \]
  1918. \caption{The interference graph of the example program.}
  1919. \label{fig:interfere}
  1920. \end{figure}
  1921. Our next concern is to choose a data structure for representing the
  1922. interference graph. There are many standard choices for how to
  1923. represent a graph: \emph{adjacency matrix}, \emph{adjacency list}, and
  1924. \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a data
  1925. structure is to study the algorithm that uses the data structure,
  1926. determine what operations need to be performed, and then choose the
  1927. data structure that provide the most efficient implementations of
  1928. those operations. Often times the choice of data structure can have an
  1929. effect on the time complexity of the algorithm, as it does here. If
  1930. you skim the next section, you will see that the register allocation
  1931. algorithm needs to ask the graph for all of its vertices and, given a
  1932. vertex, it needs to known all of the adjacent vertices. Thus, the
  1933. correct choice of graph representation is that of an adjacency
  1934. list. There are helper functions in \code{utilities.rkt} for
  1935. representing graphs using the adjacency list representation:
  1936. \code{make-graph}, \code{add-edge}, and \code{adjacent}
  1937. (Appendix~\ref{appendix:utilities}). In particular, those functions
  1938. use a hash table to map each vertex to the set of adjacent vertices,
  1939. and the sets are represented using Racket's \key{set}, which is also a
  1940. hash table.
  1941. \begin{exercise}\normalfont
  1942. Implement the compiler pass named \code{build-interference} according
  1943. to the algorithm suggested above. The output of this pass should
  1944. replace the live-after sets with the interference $\itm{graph}$ as
  1945. follows.
  1946. \begin{lstlisting}
  1947. (program (|$\Var^{*}$| |$\itm{graph}$|) |$\Instr^{+}$|)
  1948. \end{lstlisting}
  1949. \end{exercise}
  1950. \section{Graph Coloring via Sudoku}
  1951. \label{sec:graph-coloring}
  1952. We now come to the main event, mapping variables to registers (or to
  1953. stack locations in the event that we run out of registers). We need
  1954. to make sure not to map two variables to the same register if the two
  1955. variables interfere with each other. In terms of the interference
  1956. graph, this means we cannot map adjacent nodes to the same register.
  1957. If we think of registers as colors, the register allocation problem
  1958. becomes the widely-studied graph coloring
  1959. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1960. The reader may be more familiar with the graph coloring problem then he
  1961. or she realizes; the popular game of Sudoku is an instance of the
  1962. graph coloring problem. The following describes how to build a graph
  1963. out of an initial Sudoku board.
  1964. \begin{itemize}
  1965. \item There is one node in the graph for each Sudoku square.
  1966. \item There is an edge between two nodes if the corresponding squares
  1967. are in the same row, in the same column, or if the squares are in
  1968. the same $3\times 3$ region.
  1969. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1970. \item Based on the initial assignment of numbers to squares in the
  1971. Sudoku board, assign the corresponding colors to the corresponding
  1972. nodes in the graph.
  1973. \end{itemize}
  1974. If you can color the remaining nodes in the graph with the nine
  1975. colors, then you have also solved the corresponding game of Sudoku.
  1976. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  1977. the corresponding graph with colored vertices. We map the Sudoku
  1978. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  1979. sampling of the vertices (those that are colored) because showing
  1980. edges for all of the vertices would make the graph unreadable.
  1981. \begin{figure}[tbp]
  1982. \includegraphics[width=0.45\textwidth]{sudoku}
  1983. \includegraphics[width=0.5\textwidth]{sudoku-graph}
  1984. \caption{A Sudoku game board and the corresponding colored graph.}
  1985. \label{fig:sudoku-graph}
  1986. \end{figure}
  1987. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1988. come up with an algorithm for allocating registers. For example, one
  1989. of the basic techniques for Sudoku is called Pencil Marks. The idea is
  1990. that you use a process of elimination to determine what numbers no
  1991. longer make sense for a square, and write down those numbers in the
  1992. square (writing very small). For example, if the number $1$ is
  1993. assigned to a square, then by process of elimination, you can write
  1994. the pencil mark $1$ in all the squares in the same row, column, and
  1995. region. Many Sudoku computer games provide automatic support for
  1996. Pencil Marks. This heuristic also reduces the degree of branching in
  1997. the search tree.
  1998. The Pencil Marks technique corresponds to the notion of color
  1999. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2000. node, in Sudoku terms, is the set of colors that are no longer
  2001. available. In graph terminology, we have the following definition:
  2002. \begin{equation*}
  2003. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  2004. \text{ and } \mathrm{color}(v) = c \}
  2005. \end{equation*}
  2006. where $\mathrm{adjacent}(u)$ is the set of nodes adjacent to $u$.
  2007. Using the Pencil Marks technique leads to a simple strategy for
  2008. filling in numbers: if there is a square with only one possible number
  2009. left, then write down that number! But what if there are no squares
  2010. with only one possibility left? One brute-force approach is to just
  2011. make a guess. If that guess ultimately leads to a solution, great. If
  2012. not, backtrack to the guess and make a different guess. Of course,
  2013. backtracking can be horribly time consuming. One standard way to
  2014. reduce the amount of backtracking is to use the most-constrained-first
  2015. heuristic. That is, when making a guess, always choose a square with
  2016. the fewest possibilities left (the node with the highest saturation).
  2017. The idea is that choosing highly constrained squares earlier rather
  2018. than later is better because later there may not be any possibilities.
  2019. In some sense, register allocation is easier than Sudoku because we
  2020. can always cheat and add more numbers by mapping variables to the
  2021. stack. We say that a variable is \emph{spilled} when we decide to map
  2022. it to a stack location. We would like to minimize the time needed to
  2023. color the graph, and backtracking is expensive. Thus, it makes sense
  2024. to keep the most-constrained-first heuristic but drop the backtracking
  2025. in favor of greedy search (guess and just keep going).
  2026. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2027. greedy algorithm for register allocation based on saturation and the
  2028. most-constrained-first heuristic, which is roughly equivalent to the
  2029. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2030. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2031. as in Sudoku, the algorithm represents colors with integers, with the
  2032. first $k$ colors corresponding to the $k$ registers in a given machine
  2033. and the rest of the integers corresponding to stack locations.
  2034. \begin{figure}[btp]
  2035. \centering
  2036. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2037. Algorithm: DSATUR
  2038. Input: a graph |$G$|
  2039. Output: an assignment |$\mathrm{color}[v]$| for each node |$v \in G$|
  2040. |$W \gets \mathit{vertices}(G)$|
  2041. while |$W \neq \emptyset$| do
  2042. pick a node |$u$| from |$W$| with the highest saturation,
  2043. breaking ties randomly
  2044. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(v)\}$|
  2045. |$\mathrm{color}[u] \gets c$|
  2046. |$W \gets W - \{u\}$|
  2047. \end{lstlisting}
  2048. \caption{The saturation-based greedy graph coloring algorithm.}
  2049. \label{fig:satur-algo}
  2050. \end{figure}
  2051. With this algorithm in hand, let us return to the running example and
  2052. consider how to color the interference graph in
  2053. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2054. register allocation because we use it to patch instructions, so we
  2055. remove that vertex from the graph. Initially, all of the nodes are
  2056. not yet colored and they are unsaturated, so we annotate each of them
  2057. with a dash for their color and an empty set for the saturation.
  2058. \[
  2059. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2060. \node (v) at (0,0) {$v:-,\{\}$};
  2061. \node (w) at (3,0) {$w:-,\{\}$};
  2062. \node (x) at (6,0) {$x:-,\{\}$};
  2063. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2064. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2065. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2066. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2067. \draw (v) to (w);
  2068. \foreach \i in {w,x,y}
  2069. {
  2070. \foreach \j in {w,x,y}
  2071. {
  2072. \draw (\i) to (\j);
  2073. }
  2074. }
  2075. \draw (z) to (w);
  2076. \draw (z) to (y);
  2077. \draw (t1) to (z);
  2078. \draw (t2) to (t1);
  2079. \end{tikzpicture}
  2080. \]
  2081. We select a maximally saturated node and color it $0$. In this case we
  2082. have a 7-way tie, so we arbitrarily pick $y$. The then mark color $0$
  2083. as no longer available for $w$, $x$, and $z$ because they interfere
  2084. with $y$.
  2085. \[
  2086. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2087. \node (v) at (0,0) {$v:-,\{\}$};
  2088. \node (w) at (3,0) {$w:-,\{0\}$};
  2089. \node (x) at (6,0) {$x:-,\{0\}$};
  2090. \node (y) at (3,-1.5) {$y:0,\{\}$};
  2091. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  2092. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2093. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2094. \draw (v) to (w);
  2095. \foreach \i in {w,x,y}
  2096. {
  2097. \foreach \j in {w,x,y}
  2098. {
  2099. \draw (\i) to (\j);
  2100. }
  2101. }
  2102. \draw (z) to (w);
  2103. \draw (z) to (y);
  2104. \draw (t1) to (z);
  2105. \draw (t2) to (t1);
  2106. \end{tikzpicture}
  2107. \]
  2108. Now we repeat the process, selecting another maximally saturated node.
  2109. This time there is a three-way tie between $w$, $x$, and $z$. We color
  2110. $w$ with $1$.
  2111. \[
  2112. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2113. \node (v) at (0,0) {$v:-,\{1\}$};
  2114. \node (w) at (3,0) {$w:1,\{0\}$};
  2115. \node (x) at (6,0) {$x:-,\{0,1\}$};
  2116. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  2117. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2118. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2119. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2120. \draw (t1) to (z);
  2121. \draw (t2) to (t1);
  2122. \draw (v) to (w);
  2123. \foreach \i in {w,x,y}
  2124. {
  2125. \foreach \j in {w,x,y}
  2126. {
  2127. \draw (\i) to (\j);
  2128. }
  2129. }
  2130. \draw (z) to (w);
  2131. \draw (z) to (y);
  2132. \end{tikzpicture}
  2133. \]
  2134. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  2135. next available color which is $2$.
  2136. \[
  2137. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2138. \node (v) at (0,0) {$v:-,\{1\}$};
  2139. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2140. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2141. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2142. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2143. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2144. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2145. \draw (t1) to (z);
  2146. \draw (t2) to (t1);
  2147. \draw (v) to (w);
  2148. \foreach \i in {w,x,y}
  2149. {
  2150. \foreach \j in {w,x,y}
  2151. {
  2152. \draw (\i) to (\j);
  2153. }
  2154. }
  2155. \draw (z) to (w);
  2156. \draw (z) to (y);
  2157. \end{tikzpicture}
  2158. \]
  2159. Node $z$ is the next most highly saturated, so we color $z$ with $2$.
  2160. \[
  2161. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2162. \node (v) at (0,0) {$v:-,\{1\}$};
  2163. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2164. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2165. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2166. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2167. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2168. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2169. \draw (t1) to (z);
  2170. \draw (t2) to (t1);
  2171. \draw (v) to (w);
  2172. \foreach \i in {w,x,y}
  2173. {
  2174. \foreach \j in {w,x,y}
  2175. {
  2176. \draw (\i) to (\j);
  2177. }
  2178. }
  2179. \draw (z) to (w);
  2180. \draw (z) to (y);
  2181. \end{tikzpicture}
  2182. \]
  2183. We have a 2-way tie between $v$ and $t.1$. We choose to color $v$ with
  2184. $0$.
  2185. \[
  2186. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2187. \node (v) at (0,0) {$v:0,\{1\}$};
  2188. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2189. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2190. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2191. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2192. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2193. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2194. \draw (t1) to (z);
  2195. \draw (t2) to (t1);
  2196. \draw (v) to (w);
  2197. \foreach \i in {w,x,y}
  2198. {
  2199. \foreach \j in {w,x,y}
  2200. {
  2201. \draw (\i) to (\j);
  2202. }
  2203. }
  2204. \draw (z) to (w);
  2205. \draw (z) to (y);
  2206. \end{tikzpicture}
  2207. \]
  2208. In the last two steps of the algorithm, we color $t.1$ with $0$
  2209. then $t.2$ with $1$.
  2210. \[
  2211. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2212. \node (v) at (0,0) {$v:0,\{1\}$};
  2213. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2214. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2215. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2216. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2217. \node (t1) at (9,0) {$t.1:0,\{2,1\}$};
  2218. \node (t2) at (9,-1.5) {$t.2:1,\{0\}$};
  2219. \draw (t1) to (z);
  2220. \draw (t2) to (t1);
  2221. \draw (v) to (w);
  2222. \foreach \i in {w,x,y}
  2223. {
  2224. \foreach \j in {w,x,y}
  2225. {
  2226. \draw (\i) to (\j);
  2227. }
  2228. }
  2229. \draw (z) to (w);
  2230. \draw (z) to (y);
  2231. \end{tikzpicture}
  2232. \]
  2233. With the coloring complete, we can finalize the assignment of
  2234. variables to registers and stack locations. Recall that if we have $k$
  2235. registers, we map the first $k$ colors to registers and the rest to
  2236. stack locations. Suppose for the moment that we just have one extra
  2237. register to use for register allocation, just \key{rbx}. Then the
  2238. following is the mapping of colors to registers and stack allocations.
  2239. \[
  2240. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2241. \]
  2242. Putting this mapping together with the above coloring of the variables, we
  2243. arrive at the assignment:
  2244. \begin{gather*}
  2245. \{ v \mapsto \key{\%rbx}, \,
  2246. w \mapsto \key{-8(\%rbp)}, \,
  2247. x \mapsto \key{-16(\%rbp)}, \,
  2248. y \mapsto \key{\%rbx}, \,
  2249. z\mapsto \key{-16(\%rbp)}, \\
  2250. t.1\mapsto \key{\%rbx} ,\,
  2251. t.2\mapsto \key{-8(\%rbp)} \}
  2252. \end{gather*}
  2253. Applying this assignment to our running example
  2254. (Figure~\ref{fig:reg-eg}) yields the program on the right.\\
  2255. % why frame size of 32? -JGS
  2256. \begin{minipage}{0.4\textwidth}
  2257. \begin{lstlisting}
  2258. (program (v w x y z)
  2259. (movq (int 1) (var v))
  2260. (movq (int 46) (var w))
  2261. (movq (var v) (var x))
  2262. (addq (int 7) (var x))
  2263. (movq (var x) (var y))
  2264. (addq (int 4) (var y))
  2265. (movq (var x) (var z))
  2266. (addq (var w) (var z))
  2267. (movq (var y) (var t.1))
  2268. (negq (var t.1))
  2269. (movq (var z) (var t.2))
  2270. (addq (var t.1) (var t.2))
  2271. (movq (var t.2) (reg rax)))
  2272. \end{lstlisting}
  2273. \end{minipage}
  2274. $\Rightarrow$
  2275. \begin{minipage}{0.45\textwidth}
  2276. \begin{lstlisting}
  2277. (program 16
  2278. (movq (int 1) (reg rbx))
  2279. (movq (int 46) (deref rbp -8))
  2280. (movq (reg rbx) (deref rbp -16))
  2281. (addq (int 7) (deref rbp -16))
  2282. (movq (deref rbp -16) (reg rbx))
  2283. (addq (int 4) (reg rbx))
  2284. (movq (deref rbp -16) (deref rbp -16))
  2285. (addq (deref rbp -8) (deref rbp -16))
  2286. (movq (reg rbx) (reg rbx))
  2287. (negq (reg rbx))
  2288. (movq (deref rbp -16) (deref rbp -8))
  2289. (addq (reg rbx) (deref rbp -8))
  2290. (movq (deref rbp -8) (reg rax)))
  2291. \end{lstlisting}
  2292. \end{minipage}
  2293. The resulting program is almost an x86 program. The remaining step
  2294. is to apply the patch instructions pass. In this example, the trivial
  2295. move of \code{-16(\%rbp)} to itself is deleted and the addition of
  2296. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2297. \code{rax}. The following shows the portion of the program that
  2298. changed.
  2299. \begin{lstlisting}
  2300. (addq (int 4) (reg rbx))
  2301. (movq (deref rbp -8) (reg rax)
  2302. (addq (reg rax) (deref rbp -16))
  2303. \end{lstlisting}
  2304. An overview of all of the passes involved in register allocation is
  2305. shown in Figure~\ref{fig:reg-alloc-passes}.
  2306. \begin{figure}[p]
  2307. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2308. \node (R1) at (0,2) {\large $R_1$};
  2309. \node (R1-2) at (3,2) {\large $R_1$};
  2310. \node (C0-1) at (3,0) {\large $C_0$};
  2311. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2312. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2313. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2314. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2315. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2316. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2317. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2318. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  2319. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2320. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2321. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2322. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2323. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2324. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2325. \end{tikzpicture}
  2326. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2327. \label{fig:reg-alloc-passes}
  2328. \end{figure}
  2329. \begin{exercise}\normalfont
  2330. Implement the pass \code{allocate-registers} and test it by creating
  2331. new example programs that exercise all of the register allocation
  2332. algorithm, such as forcing variables to be spilled to the stack.
  2333. I recommend organizing our code by creating a helper function named
  2334. \code{color-graph} that takes an interference graph and a list of all
  2335. the variables in the program. This function should return a mapping of
  2336. variables to their colors. By creating this helper function, we will
  2337. be able to reuse it in Chapter~\ref{ch:functions} when we add support
  2338. for functions. Once you have obtained the coloring from
  2339. \code{color-graph}, you can assign the variables to registers or stack
  2340. locations based on their color and then use the \code{assign-homes}
  2341. function from Section~\ref{sec:assign-s0} to replace the variables
  2342. with their assigned location.
  2343. \end{exercise}
  2344. \section{Print x86 and Conventions for Registers}
  2345. \label{sec:print-x86-reg-alloc}
  2346. Recall the the \code{print-x86} pass generates the prelude and
  2347. conclusion instructions for the \code{main} function. The prelude
  2348. saved the values in \code{rbp} and \code{rsp} and the conclusion
  2349. returned those values to \code{rbp} and \code{rsp}. The reason for
  2350. this is that there are agreed-upon conventions for how different
  2351. functions share the same fixed set of registers. There is a function
  2352. inside the operating system (OS) that calls our \code{main} function,
  2353. and that OS function uses the same registers that we use in
  2354. \code{main}. The convention for x86 is that the caller is responsible
  2355. for freeing up some registers, the \emph{caller save registers}, prior
  2356. to the function call, and the callee is responsible for saving and
  2357. restoring some other registers, the \emph{callee save registers},
  2358. before and after using them. The caller save registers are
  2359. \begin{lstlisting}
  2360. rax rdx rcx rsi rdi r8 r9 r10 r11
  2361. \end{lstlisting}
  2362. while the callee save registers are
  2363. \begin{lstlisting}
  2364. rsp rbp rbx r12 r13 r14 r15
  2365. \end{lstlisting}
  2366. Another way to think about this caller/callee convention is the
  2367. following. The caller should assume that all the caller save registers
  2368. get overwritten with arbitrary values by the callee. On the other
  2369. hand, the caller can safely assume that all the callee save registers
  2370. contain the same values after the call that they did before the call.
  2371. The callee can freely use any of the caller save registers. However,
  2372. if the callee wants to use a callee save register, the callee must
  2373. arrange to put the original value back in the register prior to
  2374. returning to the caller, which is usually accomplished by saving and
  2375. restoring the value from the stack.
  2376. The upshot of these conventions is that the \code{main} function needs
  2377. to save (in the prelude) and restore (in the conclusion) any callee
  2378. save registers that get used during register allocation. The simplest
  2379. approach is to save and restore all the callee save registers. The
  2380. more efficient approach is to keep track of which callee save
  2381. registers were used and only save and restore them. Either way, make
  2382. sure to take this use of stack space into account when you round up
  2383. the size of the frame to make sure it is a multiple of 16 bytes.
  2384. \section{Challenge: Move Biasing$^{*}$}
  2385. \label{sec:move-biasing}
  2386. This section describes an optional enhancement to register allocation
  2387. for those students who are looking for an extra challenge or who have
  2388. a deeper interest in register allocation.
  2389. We return to the running example, but we remove the supposition that
  2390. we only have one register to use. So we have the following mapping of
  2391. color numbers to registers.
  2392. \[
  2393. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2394. \]
  2395. Using the same assignment that was produced by register allocator
  2396. described in the last section, we get the following program.
  2397. \begin{minipage}{0.45\textwidth}
  2398. \begin{lstlisting}
  2399. (program (v w x y z)
  2400. (movq (int 1) (var v))
  2401. (movq (int 46) (var w))
  2402. (movq (var v) (var x))
  2403. (addq (int 7) (var x))
  2404. (movq (var x) (var y))
  2405. (addq (int 4) (var y))
  2406. (movq (var x) (var z))
  2407. (addq (var w) (var z))
  2408. (movq (var y) (var t.1))
  2409. (negq (var t.1))
  2410. (movq (var z) (var t.2))
  2411. (addq (var t.1) (var t.2))
  2412. (movq (var t.2) (reg rax)))
  2413. \end{lstlisting}
  2414. \end{minipage}
  2415. $\Rightarrow$
  2416. \begin{minipage}{0.45\textwidth}
  2417. \begin{lstlisting}
  2418. (program 0
  2419. (movq (int 1) (reg rbx))
  2420. (movq (int 46) (reg rcx))
  2421. (movq (reg rbx) (reg rdx))
  2422. (addq (int 7) (reg rdx))
  2423. (movq (reg rdx) (reg rbx))
  2424. (addq (int 4) (reg rbx))
  2425. (movq (reg rdx) (reg rdx))
  2426. (addq (reg rcx) (reg rdx))
  2427. (movq (reg rbx) (reg rbx))
  2428. (negq (reg rbx))
  2429. (movq (reg rdx) (reg rcx))
  2430. (addq (reg rbx) (reg rcx))
  2431. (movq (reg rcx) (reg rax)))
  2432. \end{lstlisting}
  2433. \end{minipage}
  2434. While this allocation is quite good, we could do better. For example,
  2435. the variables \key{v} and \key{x} ended up in different registers, but
  2436. if they had been placed in the same register, then the move from
  2437. \key{v} to \key{x} could be removed.
  2438. We say that two variables $p$ and $q$ are \emph{move related} if they
  2439. participate together in a \key{movq} instruction, that is, \key{movq
  2440. p, q} or \key{movq q, p}. When the register allocator chooses a
  2441. color for a variable, it should prefer a color that has already been
  2442. used for a move-related variable (assuming that they do not
  2443. interfere). Of course, this preference should not override the
  2444. preference for registers over stack locations, but should only be used
  2445. as a tie breaker when choosing between registers or when choosing
  2446. between stack locations.
  2447. We recommend that you represent the move relationships in a graph,
  2448. similar to how we represented interference. The following is the
  2449. \emph{move graph} for our running example.
  2450. \[
  2451. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2452. \node (v) at (0,0) {$v$};
  2453. \node (w) at (3,0) {$w$};
  2454. \node (x) at (6,0) {$x$};
  2455. \node (y) at (3,-1.5) {$y$};
  2456. \node (z) at (6,-1.5) {$z$};
  2457. \node (t1) at (9,0) {$t.1$};
  2458. \node (t2) at (9,-1.5) {$t.2$};
  2459. \draw (t1) to (y);
  2460. \draw (t2) to (z);
  2461. \draw[bend left=20] (v) to (x);
  2462. \draw (x) to (y);
  2463. \draw (x) to (z);
  2464. \end{tikzpicture}
  2465. \]
  2466. Now we replay the graph coloring, pausing to see the coloring of $z$
  2467. and $v$. So we have the following coloring so far and the most
  2468. saturated vertex is $z$.
  2469. \[
  2470. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2471. \node (v) at (0,0) {$v:-,\{1\}$};
  2472. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2473. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2474. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2475. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2476. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2477. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2478. \draw (t1) to (z);
  2479. \draw (t2) to (t1);
  2480. \draw (v) to (w);
  2481. \foreach \i in {w,x,y}
  2482. {
  2483. \foreach \j in {w,x,y}
  2484. {
  2485. \draw (\i) to (\j);
  2486. }
  2487. }
  2488. \draw (z) to (w);
  2489. \draw (z) to (y);
  2490. \end{tikzpicture}
  2491. \]
  2492. Last time we chose to color $z$ with $2$, which so happens to be the
  2493. color of $x$, and $z$ is move related to $x$. This was rather lucky,
  2494. and if the program had been a little different, and say $x$ had been
  2495. already assigned to $3$, then $z$ would still get $2$ and our luck
  2496. would have run out. With move biasing, we use the fact that $z$ and
  2497. $x$ are move related to influence the choice of color for $z$, in this
  2498. case choosing $2$ because that's the color of $x$.
  2499. \[
  2500. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2501. \node (v) at (0,0) {$v:-,\{1\}$};
  2502. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2503. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2504. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2505. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2506. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2507. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2508. \draw (t1) to (z);
  2509. \draw (t2) to (t1);
  2510. \draw (v) to (w);
  2511. \foreach \i in {w,x,y}
  2512. {
  2513. \foreach \j in {w,x,y}
  2514. {
  2515. \draw (\i) to (\j);
  2516. }
  2517. }
  2518. \draw (z) to (w);
  2519. \draw (z) to (y);
  2520. \end{tikzpicture}
  2521. \]
  2522. Next we consider coloring the variable $v$, and we just need to avoid
  2523. choosing $1$ because of the interference with $w$. Last time we choose
  2524. the color $0$, simply because it was the lowest, but this time we know
  2525. that $v$ is move related to $x$, so we choose the color $2$.
  2526. \[
  2527. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2528. \node (v) at (0,0) {$v:2,\{1\}$};
  2529. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2530. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2531. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2532. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2533. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2534. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2535. \draw (t1) to (z);
  2536. \draw (t2) to (t1);
  2537. \draw (v) to (w);
  2538. \foreach \i in {w,x,y}
  2539. {
  2540. \foreach \j in {w,x,y}
  2541. {
  2542. \draw (\i) to (\j);
  2543. }
  2544. }
  2545. \draw (z) to (w);
  2546. \draw (z) to (y);
  2547. \end{tikzpicture}
  2548. \]
  2549. We apply this register assignment to the running example, on the left,
  2550. to obtain the code on right.
  2551. \begin{minipage}{0.45\textwidth}
  2552. \begin{lstlisting}
  2553. (program (v w x y z)
  2554. (movq (int 1) (var v))
  2555. (movq (int 46) (var w))
  2556. (movq (var v) (var x))
  2557. (addq (int 7) (var x))
  2558. (movq (var x) (var y))
  2559. (addq (int 4) (var y))
  2560. (movq (var x) (var z))
  2561. (addq (var w) (var z))
  2562. (movq (var y) (var t.1))
  2563. (negq (var t.1))
  2564. (movq (var z) (var t.2))
  2565. (addq (var t.1) (var t.2))
  2566. (movq (var t.2) (reg rax)))
  2567. \end{lstlisting}
  2568. \end{minipage}
  2569. $\Rightarrow$
  2570. \begin{minipage}{0.45\textwidth}
  2571. \begin{lstlisting}
  2572. (program 0
  2573. (movq (int 1) (reg rdx))
  2574. (movq (int 46) (reg rcx))
  2575. (movq (reg rdx) (reg rdx))
  2576. (addq (int 7) (reg rdx))
  2577. (movq (reg rdx) (reg rbx))
  2578. (addq (int 4) (reg rbx))
  2579. (movq (reg rdx) (reg rdx))
  2580. (addq (reg rcx) (reg rdx))
  2581. (movq (reg rbx) (reg rbx))
  2582. (negq (reg rbx))
  2583. (movq (reg rdx) (reg rcx))
  2584. (addq (reg rbx) (reg rcx))
  2585. (movq (reg rcx) (reg rax)))
  2586. \end{lstlisting}
  2587. \end{minipage}
  2588. The \code{patch-instructions} then removes the trivial moves from
  2589. \key{v} to \key{x}, from \key{x} to \key{z}, and from \key{y} to
  2590. \key{t.1}, to obtain the following result.
  2591. \begin{lstlisting}
  2592. (program 0
  2593. (movq (int 1) (reg rdx))
  2594. (movq (int 46) (reg rcx))
  2595. (addq (int 7) (reg rdx))
  2596. (movq (reg rdx) (reg rbx))
  2597. (addq (int 4) (reg rbx))
  2598. (addq (reg rcx) (reg rdx))
  2599. (negq (reg rbx))
  2600. (movq (reg rdx) (reg rcx))
  2601. (addq (reg rbx) (reg rcx))
  2602. (movq (reg rcx) (reg rax)))
  2603. \end{lstlisting}
  2604. \begin{exercise}\normalfont
  2605. Change your implementation of \code{allocate-registers} to take move
  2606. biasing into account. Make sure that your compiler still passes all of
  2607. the previous tests. Create two new tests that include at least one
  2608. opportunity for move biasing and visually inspect the output x86
  2609. programs to make sure that your move biasing is working properly.
  2610. \end{exercise}
  2611. \marginpar{\footnotesize To do: another neat challenge would be to do
  2612. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2613. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2614. \chapter{Booleans, Control Flow, and Type Checking}
  2615. \label{ch:bool-types}
  2616. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2617. integers. In this Chapter we add a second kind of value, the Booleans,
  2618. to create the $R_2$ language. The Boolean values \emph{true} and
  2619. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2620. Racket. We also introduce several operations that involve Booleans
  2621. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2622. \key{if} expression. With the addition of \key{if} expressions,
  2623. programs can have non-trivial control flow which has an impact on
  2624. several parts of the compiler. Also, because we now have two kinds of
  2625. values, we need to worry about programs that apply an operation to the
  2626. wrong kind of value, such as \code{(not 1)}.
  2627. There are two language design options for such situations. One option
  2628. is to signal an error and the other is to provide a wider
  2629. interpretation of the operation. The Racket language uses a mixture of
  2630. these two options, depending on the operation and the kind of
  2631. value. For example, the result of \code{(not 1)} in Racket is
  2632. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2633. the other hand, \code{(car 1)} results in a run-time error in Racket
  2634. stating that \code{car} expects a pair.
  2635. The Typed Racket language makes similar design choices as Racket,
  2636. except much of the error detection happens at compile time instead of
  2637. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2638. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2639. reports a compile-time error because the type of the argument is
  2640. expected to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2641. For the $R_2$ language we choose to be more like Typed Racket in that
  2642. we shall perform type checking during compilation. In
  2643. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2644. is, how to compile a dynamically typed language like Racket. The
  2645. $R_2$ language is a subset of Typed Racket but by no means includes
  2646. all of Typed Racket. Furthermore, for many of the operations we shall
  2647. take a narrower interpretation than Typed Racket, for example,
  2648. rejecting \code{(not 1)}.
  2649. This chapter is organized as follows. We begin by defining the syntax
  2650. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2651. then introduce the idea of type checking and build a type checker for
  2652. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2653. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2654. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2655. how our compiler passes need to change to accommodate Booleans and
  2656. conditional control flow.
  2657. \section{The $R_2$ Language}
  2658. \label{sec:r2-lang}
  2659. The syntax of the $R_2$ language is defined in
  2660. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray) ,
  2661. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  2662. \code{if} expression. Also, we expand the operators to include the
  2663. \key{and} and \key{not} on Booleans, the \key{eq?} operations for
  2664. comparing two integers or two Booleans, and the \key{<}, \key{<=},
  2665. \key{>}, and \key{>=} operations for comparing integers.
  2666. \begin{figure}[tp]
  2667. \centering
  2668. \fbox{
  2669. \begin{minipage}{0.96\textwidth}
  2670. \[
  2671. \begin{array}{lcl}
  2672. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2673. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  2674. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2675. &\mid& \key{\#t} \mid \key{\#f} \mid
  2676. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  2677. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2678. R_2 &::=& (\key{program} \; \Exp)
  2679. \end{array}
  2680. \]
  2681. \end{minipage}
  2682. }
  2683. \caption{The syntax of $R_2$, extending $R_1$ with Booleans and
  2684. conditionals.}
  2685. \label{fig:r2-syntax}
  2686. \end{figure}
  2687. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2688. the parts that are the same as the interpreter for $R_1$
  2689. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2690. simply evaluate to themselves. The conditional expression $(\key{if}\,
  2691. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  2692. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  2693. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  2694. operations \code{not} and \code{and} behave as you might expect, but
  2695. note that the \code{and} operation is short-circuiting. That is, given
  2696. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  2697. evaluated if $e_1$ evaluates to \code{\#f}.
  2698. With the addition of the comparison operations, there are quite a few
  2699. primitive operations and the interpreter code for them is somewhat
  2700. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2701. parts into the \code{interp-op} function and the similar parts into
  2702. the one match clause shown in Figure~\ref{fig:interp-R2}. It is
  2703. important for that match clause to come last because it matches
  2704. \emph{any} compound S-expression. We do not use \code{interp-op} for
  2705. the \code{and} operation because of the short-circuiting behavior in
  2706. the order of evaluation of its arguments.
  2707. \begin{figure}[tbp]
  2708. \begin{lstlisting}
  2709. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2710. (define (interp-op op)
  2711. (match op
  2712. ['+ fx+]
  2713. ['- (lambda (n) (fx- 0 n))]
  2714. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2715. ['read read-fixnum]
  2716. ['eq? (lambda (v1 v2)
  2717. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2718. (and (boolean? v1) (boolean? v2))
  2719. (and (vector? v1) (vector? v2)))
  2720. (eq? v1 v2)]))]
  2721. ['< (lambda (v1 v2)
  2722. (cond [(and (fixnum? v1) (fixnum? v2))
  2723. (< v1 v2)]))]
  2724. ['<= (lambda (v1 v2)
  2725. (cond [(and (fixnum? v1) (fixnum? v2))
  2726. (<= v1 v2)]))]
  2727. ['> (lambda (v1 v2)
  2728. (cond [(and (fixnum? v1) (fixnum? v2))
  2729. (<= v1 v2)]))]
  2730. ['>= (lambda (v1 v2)
  2731. (cond [(and (fixnum? v1) (fixnum? v2))
  2732. (<= v1 v2)]))]
  2733. [else (error 'interp-op "unknown operator")]))
  2734. (define (interp-R2 env)
  2735. (lambda (e)
  2736. (define recur (interp-R2 env))
  2737. (match e
  2738. ...
  2739. [(? boolean?) e]
  2740. [`(if ,(app recur cnd) ,thn ,els)
  2741. (match cnd
  2742. [#t (recur thn)]
  2743. [#f (recur els)])]
  2744. [`(not ,(app recur v))
  2745. (match v [#t #f] [#f #t])]
  2746. [`(and ,(app recur v1) ,e2)
  2747. (match v1
  2748. [#t (match (recur e2) [#t #t] [#f #f])]
  2749. [#f #f])]
  2750. [`(,op ,(app recur args) ...)
  2751. #:when (set-member? primitives op)
  2752. (apply (interp-op op) args)]
  2753. )))
  2754. \end{lstlisting}
  2755. \caption{Interpreter for the $R_2$ language.}
  2756. \label{fig:interp-R2}
  2757. \end{figure}
  2758. \section{Type Checking $R_2$ Programs}
  2759. \label{sec:type-check-r2}
  2760. It is helpful to think about type checking into two complementary
  2761. ways. A type checker predicts the \emph{type} of value that will be
  2762. produced by each expression in the program. For $R_2$, we have just
  2763. two types, \key{Integer} and \key{Boolean}. So a type checker should
  2764. predict that
  2765. \begin{lstlisting}
  2766. (+ 10 (- (+ 12 20)))
  2767. \end{lstlisting}
  2768. produces an \key{Integer} while
  2769. \begin{lstlisting}
  2770. (and (not #f) #t)
  2771. \end{lstlisting}
  2772. produces a \key{Boolean}.
  2773. As mentioned at the beginning of this chapter, a type checker also
  2774. rejects programs that apply operators to the wrong type of value. Our
  2775. type checker for $R_2$ will signal an error for the following
  2776. expression because, as we have seen above, the expression \code{(+ 10
  2777. ...)} has type \key{Integer}, and we require the argument of a
  2778. \code{not} to have type \key{Boolean}.
  2779. \begin{lstlisting}
  2780. (not (+ 10 (- (+ 12 20))))
  2781. \end{lstlisting}
  2782. The type checker for $R_2$ is best implemented as a structurally
  2783. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  2784. many of the clauses for the \code{typecheck-R2} function. Given an
  2785. input expression \code{e}, the type checker either returns the type
  2786. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  2787. the type of an integer literal is \code{Integer} and the type of a
  2788. Boolean literal is \code{Boolean}. To handle variables, the type
  2789. checker, like the interpreter, uses an association list. However, in
  2790. this case the association list maps variables to types instead of
  2791. values. Consider the clause for \key{let}. We type check the
  2792. initializing expression to obtain its type \key{T} and then associate
  2793. type \code{T} with the variable \code{x}. When the type checker
  2794. encounters the use of a variable, it can lookup its type in the
  2795. association list.
  2796. \begin{figure}[tbp]
  2797. \begin{lstlisting}
  2798. (define (typecheck-R2 env)
  2799. (lambda (e)
  2800. (define recur (typecheck-R2 env e))
  2801. (match e
  2802. [(? fixnum?) 'Integer]
  2803. [(? boolean?) 'Boolean]
  2804. [(? symbol?) (lookup e env)]
  2805. [`(let ([,x ,(app recur T)]) ,body)
  2806. (define new-env (cons (cons x T) env))
  2807. (typecheck-R2 new-env body)]
  2808. ...
  2809. [`(not ,(app (typecheck-R2 env) T))
  2810. (match T
  2811. ['Boolean 'Boolean]
  2812. [else (error 'typecheck-R2 "'not' expects a Boolean" e)])]
  2813. ...
  2814. [`(program ,body)
  2815. (define ty ((typecheck-R2 '()) body))
  2816. `(program (type ,ty) ,body)]
  2817. )))
  2818. \end{lstlisting}
  2819. \caption{Skeleton of a type checker for the $R_2$ language.}
  2820. \label{fig:type-check-R2}
  2821. \end{figure}
  2822. To print the resulting value correctly, the overall type of the
  2823. program must be threaded through the remainder of the passes. We can
  2824. store the type within the \key{program} form as shown in Figure
  2825. \ref{fig:type-check-R2}. The syntax for post-typechecking $R_2$
  2826. programs as follows: \\
  2827. \fbox{
  2828. \begin{minipage}{0.87\textwidth}
  2829. \[
  2830. \begin{array}{lcl}
  2831. R_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  2832. \end{array}
  2833. \]
  2834. \end{minipage}
  2835. }
  2836. \begin{exercise}\normalfont
  2837. Complete the implementation of \code{typecheck-R2} and test it on 10
  2838. new example programs in $R_2$ that you choose based on how thoroughly
  2839. they test the type checking algorithm. Half of the example programs
  2840. should have a type error, to make sure that your type checker properly
  2841. rejects them. The other half of the example programs should not have
  2842. type errors. Your testing should check that the result of the type
  2843. checker agrees with the value returned by the interpreter, that is, if
  2844. the type checker returns \key{Integer}, then the interpreter should
  2845. return an integer. Likewise, if the type checker returns
  2846. \key{Boolean}, then the interpreter should return \code{\#t} or
  2847. \code{\#f}. Note that if your type checker does not signal an error
  2848. for a program, then interpreting that program should not encounter an
  2849. error. If it does, there is something wrong with your type checker.
  2850. \end{exercise}
  2851. \section{The $C_1$ Language}
  2852. \label{sec:c1}
  2853. The $R_2$ language adds Booleans and conditional expressions to $R_1$.
  2854. As with $R_1$, we shall compile to a C-like intermediate language, but
  2855. we need to grow that intermediate language to handle the new features
  2856. in $R_2$. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$;
  2857. we add logic and comparison operators to the $\Exp$ non-terminal, the
  2858. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal, and we
  2859. add an \key{if} statement. The \key{if} statement of $C_1$ includes an
  2860. \key{eq?} test, which is needed for improving code generation in
  2861. Section~\ref{sec:opt-if}. We do not include \key{and} in $C_1$
  2862. because it is not needed in the translation of the \key{and} of $R_2$.
  2863. \begin{figure}[tp]
  2864. \fbox{
  2865. \begin{minipage}{0.96\textwidth}
  2866. \[
  2867. \begin{array}{lcl}
  2868. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  2869. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2870. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  2871. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  2872. \Stmt &::=& \gray{\ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg}} \\
  2873. &\mid& \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} \\
  2874. C_1 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+})
  2875. \end{array}
  2876. \]
  2877. \end{minipage}
  2878. }
  2879. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  2880. \label{fig:c1-syntax}
  2881. \end{figure}
  2882. \section{Flatten Expressions}
  2883. \label{sec:flatten-r2}
  2884. We expand the \code{flatten} pass to handle the Boolean literals
  2885. \key{\#t} and \key{\#f}, the new logic and comparison operations, and
  2886. \key{if} expressions. We shall start with a simple example of
  2887. translating a \key{if} expression, shown below on the left. \\
  2888. \begin{tabular}{lll}
  2889. \begin{minipage}{0.4\textwidth}
  2890. \begin{lstlisting}
  2891. (program (if #f 0 42))
  2892. \end{lstlisting}
  2893. \end{minipage}
  2894. &
  2895. $\Rightarrow$
  2896. &
  2897. \begin{minipage}{0.4\textwidth}
  2898. \begin{lstlisting}
  2899. (program (if.1)
  2900. (if (eq? #t #f)
  2901. ((assign if.1 0))
  2902. ((assign if.1 42)))
  2903. (return if.1))
  2904. \end{lstlisting}
  2905. \end{minipage}
  2906. \end{tabular} \\
  2907. The value of the \key{if} expression is the value of the branch that
  2908. is selected. Recall that in the \code{flatten} pass we need to replace
  2909. arbitrary expressions with $\Arg$'s (variables or literals). In the
  2910. translation above, on the right, we have replaced the \key{if}
  2911. expression with a new variable \key{if.1}, inside \code{(return
  2912. if.1)}, and we have produced code that will assign the appropriate
  2913. value to \key{if.1} using an \code{if} statement prior to the
  2914. \code{return}. For $R_1$, the \code{flatten} pass returned a list of
  2915. assignment statements. Here, for $R_2$, we return a list of statements
  2916. that can include both \key{if} statements and assignment statements.
  2917. The next example is a bit more involved, showing what happens when
  2918. there are complex expressions (not variables or literals) in the
  2919. condition and branch expressions of an \key{if}, including nested
  2920. \key{if} expressions.
  2921. \begin{tabular}{lll}
  2922. \begin{minipage}{0.4\textwidth}
  2923. \begin{lstlisting}
  2924. (program
  2925. (if (eq? (read) 0)
  2926. 777
  2927. (+ 2 (if (eq? (read) 0)
  2928. 40
  2929. 444))))
  2930. \end{lstlisting}
  2931. \end{minipage}
  2932. &
  2933. $\Rightarrow$
  2934. &
  2935. \begin{minipage}{0.4\textwidth}
  2936. \begin{lstlisting}
  2937. (program (t.1 t.2 if.1 t.3 t.4
  2938. if.2 t.5)
  2939. (assign t.1 (read))
  2940. (assign t.2 (eq? t.1 0))
  2941. (if (eq? #t t.2)
  2942. ((assign if.1 777))
  2943. ((assign t.3 (read))
  2944. (assign t.4 (eq? t.3 0))
  2945. (if (eq? #t t.4)
  2946. ((assign if.2 40))
  2947. ((assign if.2 444)))
  2948. (assign t.5 (+ 2 if.2))
  2949. (assign if.1 t.5)))
  2950. (return if.1))
  2951. \end{lstlisting}
  2952. \end{minipage}
  2953. \end{tabular} \\
  2954. The \code{flatten} clauses for the Boolean literals and the operations
  2955. \key{not} and \key{eq?} are straightforward. However, the
  2956. \code{flatten} clause for \key{and} requires some care to properly
  2957. imitate the order of evaluation of the interpreter for $R_2$
  2958. (Figure~\ref{fig:interp-R2}). We recommend using an \key{if} statement
  2959. in the code you generate for \key{and}.
  2960. The \code{flatten} clause for \key{if} also requires some care because
  2961. the condition of the \key{if} can be an arbitrary expression in $R_2$,
  2962. but in $C_1$ the condition must be an equality predicate. For now we
  2963. recommend flattening the condition into an $\Arg$ and then comparing
  2964. it with \code{\#t}. We discuss a more efficient approach in
  2965. Section~\ref{sec:opt-if}.
  2966. \begin{exercise}\normalfont
  2967. Expand your \code{flatten} pass to handle $R_2$, that is, handle the
  2968. Boolean literals, the new logic and comparison operations, and the
  2969. \key{if} expressions. Create 4 more test cases that expose whether
  2970. your flattening code is correct. Test your \code{flatten} pass by
  2971. running the output programs with \code{interp-C}
  2972. (Appendix~\ref{appendix:interp}).
  2973. \end{exercise}
  2974. \section{XOR, Comparisons, and Control Flow in x86}
  2975. \label{sec:x86-1}
  2976. To implement the new logical operations, the comparison operations,
  2977. and the \key{if} statement, we need to delve further into the x86
  2978. language. Figure~\ref{fig:x86-2} defines the abstract syntax for a
  2979. larger subset of x86 that includes instructions for logical
  2980. operations, comparisons, and jumps.
  2981. One small challenge is that x86 does not provide an instruction that
  2982. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  2983. However, the \code{xorq} instruction can be used to encode \code{not}.
  2984. The \key{xorq} instruction takes two arguments, performs a pairwise
  2985. exclusive-or operation on each bit of its arguments, and writes the
  2986. results into its second argument. Recall the truth table for
  2987. exclusive-or:
  2988. \begin{center}
  2989. \begin{tabular}{l|cc}
  2990. & 0 & 1 \\ \hline
  2991. 0 & 0 & 1 \\
  2992. 1 & 1 & 0
  2993. \end{tabular}
  2994. \end{center}
  2995. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  2996. in row of the table for the bit $1$, the result is the opposite of the
  2997. second bit. Thus, the \code{not} operation can be implemented by
  2998. \code{xorq} with $1$ as the first argument: $0001
  2999. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3000. 0001 = 0000$.
  3001. \begin{figure}[tp]
  3002. \fbox{
  3003. \begin{minipage}{0.96\textwidth}
  3004. \[
  3005. \begin{array}{lcl}
  3006. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3007. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3008. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3009. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3010. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3011. (\key{subq} \; \Arg\; \Arg) \mid
  3012. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3013. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3014. (\key{pushq}\;\Arg) \mid
  3015. (\key{popq}\;\Arg) \mid
  3016. (\key{retq})} \\
  3017. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3018. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3019. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3020. \mid (\key{jmp} \; \itm{label})
  3021. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3022. &\mid& (\key{label} \; \itm{label}) \\
  3023. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3024. \end{array}
  3025. \]
  3026. \end{minipage}
  3027. }
  3028. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3029. \label{fig:x86-1}
  3030. \end{figure}
  3031. Next we consider the x86 instructions that are relevant for
  3032. compiling the comparison operations. The \key{cmpq} instruction
  3033. compares its two arguments to determine whether one argument is less
  3034. than, equal, or greater than the other argument. The \key{cmpq}
  3035. instruction is unusual regarding the order of its arguments and where
  3036. the result is placed. The argument order is backwards: if you want to
  3037. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3038. \key{cmpq} is placed in the special EFLAGS register. This register
  3039. cannot be accessed directly but it can be queried by a number of
  3040. instructions, including the \key{set} instruction. The \key{set}
  3041. instruction puts a \key{1} or \key{0} into its destination depending
  3042. on whether the comparison came out according to the condition code
  3043. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3044. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3045. The set instruction has an annoying quirk in that its destination
  3046. argument must be single byte register, such as \code{al}, which is
  3047. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3048. instruction can then be used to move from a single byte register to a
  3049. normal 64-bit register.
  3050. For compiling the \key{if} expression, the x86 instructions for
  3051. jumping are relevant. The \key{jmp} instruction updates the program
  3052. counter to point to the instruction after the indicated label. The
  3053. \key{jmp-if} instruction updates the program counter to point to the
  3054. instruction after the indicated label depending on whether the result
  3055. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3056. the \key{jmp-if} instruction falls through to the next
  3057. instruction. Our abstract syntax for \key{jmp-if} differs from the
  3058. concrete syntax for x86 to separate the instruction name from the
  3059. condition code. For example, \code{(jmp-if le foo)} corresponds to
  3060. \code{jle foo}.
  3061. \section{Select Instructions}
  3062. \label{sec:select-r2}
  3063. The \code{select-instructions} pass lowers from $C_1$ to another
  3064. intermediate representation suitable for conducting register
  3065. allocation, that is, a language close to x86$_1$.
  3066. We can take the usual approach of encoding Booleans as integers, with
  3067. true as 1 and false as 0.
  3068. \[
  3069. \key{\#t} \Rightarrow \key{1}
  3070. \qquad
  3071. \key{\#f} \Rightarrow \key{0}
  3072. \]
  3073. The \code{not} operation can be implemented in terms of \code{xorq}
  3074. as we discussed at the beginning of this section.
  3075. %% Can you think of a bit pattern that, when XOR'd with the bit
  3076. %% representation of 0 produces 1, and when XOR'd with the bit
  3077. %% representation of 1 produces 0?
  3078. Translating the \code{eq?} and the other comparison operations to x86
  3079. is slightly involved due to the unusual nature of the \key{cmpq}
  3080. instruction discussed above. We recommend translating an assignment
  3081. from \code{eq?} into the following sequence of three instructions. \\
  3082. \begin{tabular}{lll}
  3083. \begin{minipage}{0.4\textwidth}
  3084. \begin{lstlisting}
  3085. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3086. \end{lstlisting}
  3087. \end{minipage}
  3088. &
  3089. $\Rightarrow$
  3090. &
  3091. \begin{minipage}{0.4\textwidth}
  3092. \begin{lstlisting}
  3093. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3094. (set e (byte-reg al))
  3095. (movzbq (byte-reg al) |$\itm{lhs}$|)
  3096. \end{lstlisting}
  3097. \end{minipage}
  3098. \end{tabular} \\
  3099. % The translation of the \code{not} operator is not quite as simple
  3100. % as it seems. Recall that \key{notq} is a bitwise operator, not a boolean
  3101. % one. For example, the following program performs bitwise negation on
  3102. % the integer 1:
  3103. %
  3104. % \begin{tabular}{lll}
  3105. % \begin{minipage}{0.4\textwidth}
  3106. % \begin{lstlisting}
  3107. % (movq (int 1) (reg rax))
  3108. % (notq (reg rax))
  3109. % \end{lstlisting}
  3110. % \end{minipage}
  3111. % \end{tabular}
  3112. %
  3113. % After the program is run, \key{rax} does not contain 0, as you might
  3114. % hope -- it contains the binary value $111\ldots10$, which is the
  3115. % two's complement representation of $-2$. We recommend implementing boolean
  3116. % not by using \key{notq} and then masking the upper bits of the result with
  3117. % the \key{andq} instruction.
  3118. Regarding \key{if} statements, we recommend delaying when they are
  3119. lowered until the \code{patch-instructions} pass. The reason is that
  3120. for purposes of liveness analysis, \key{if} statements are easier to
  3121. deal with than jump instructions.
  3122. \begin{exercise}\normalfont
  3123. Expand your \code{select-instructions} pass to handle the new features
  3124. of the $R_2$ language. Test the pass on all the examples you have
  3125. created and make sure that you have some test programs that use the
  3126. \code{eq?} operator, creating some if necessary. Test the output of
  3127. \code{select-instructions} using the \code{interp-x86} interpreter
  3128. (Appendix~\ref{appendix:interp}).
  3129. \end{exercise}
  3130. \section{Register Allocation}
  3131. \label{sec:register-allocation-r2}
  3132. The changes required for $R_2$ affect the liveness analysis, building
  3133. the interference graph, and assigning homes, but the graph coloring
  3134. algorithm itself does not need to change.
  3135. \subsection{Liveness Analysis}
  3136. \label{sec:liveness-analysis-r2}
  3137. The addition of \key{if} statements brings up an interesting issue in
  3138. liveness analysis. Recall that liveness analysis works backwards
  3139. through the program, for each instruction it computes the variables
  3140. that are live before the instruction based on which variables are live
  3141. after the instruction. Now consider the situation for \code{(\key{if}
  3142. (\key{eq?} $e_1$ $e_2$) $\itm{thns}$ $\itm{elss}$)}, where we know
  3143. the $L_{\mathsf{after}}$ set and we need to produce the
  3144. $L_{\mathsf{before}}$ set. We can recursively perform liveness
  3145. analysis on the $\itm{thns}$ and $\itm{elss}$ branches, using
  3146. $L_{\mathsf{after}}$ as the starting point, to obtain
  3147. $L^{\mathsf{thns}}_{\mathsf{before}}$ and
  3148. $L^{\mathsf{elss}}_{\mathsf{before}}$ respectively. However, we do not
  3149. know, during compilation, which way the branch will go, so we do not
  3150. know whether to use $L^{\mathsf{thns}}_{\mathsf{before}}$ or
  3151. $L^{\mathsf{elss}}_{\mathsf{before}}$ as the $L_{\mathsf{before}}$ for
  3152. the entire \key{if} statement. The solution comes from the observation
  3153. that there is no harm in identifying more variables as live than
  3154. absolutely necessary. Thus, we can take the union of the live
  3155. variables from the two branches to be the live set for the whole
  3156. \key{if}, as shown below. Of course, we also need to include the
  3157. variables that are read in $e_1$ and $e_2$.
  3158. \[
  3159. L_{\mathsf{before}} = L^{\mathsf{thns}}_{\mathsf{before}} \cup
  3160. L^{\mathsf{elss}}_{\mathsf{before}} \cup
  3161. \mathit{Vars}(e_1) \cup \mathit{Vars}(e_2)
  3162. \]
  3163. We need the live-after sets for all the instructions in both branches
  3164. of the \key{if} when we build the interference graph, so I recommend
  3165. storing that data in the \key{if} statement AST as follows:
  3166. \begin{lstlisting}
  3167. (if (eq? |$e_1$| |$e_2$|) |$\itm{thns}$| |$\itm{thn{-}lives}$| |$\itm{elss}$| |$\itm{els{-}lives}$|)
  3168. \end{lstlisting}
  3169. If you wrote helper functions for computing the variables in an
  3170. instruction's argument and for computing the variables read-from ($R$)
  3171. or written-to ($W$) by an instruction, you need to be update them to
  3172. handle the new kinds of arguments and instructions in x86$_1$.
  3173. \subsection{Build Interference}
  3174. \label{sec:build-interference-r2}
  3175. Many of the new instructions, such as the logical operations, can be
  3176. handled in the same way as the arithmetic instructions. Thus, if your
  3177. code was already quite general, it will not need to be changed to
  3178. handle the logical operations. If not, I recommend that you change
  3179. your code to be more general. The \key{movzbq} instruction should be
  3180. handled like the \key{movq} instruction. The \key{if} statement is
  3181. straightforward to handle because we stored the live-after sets for
  3182. the two branches in the AST node as described above. Here we just need
  3183. to recursively process the two branches. The output of this pass can
  3184. discard the live after sets, as they are no longer needed.
  3185. \subsection{Assign Homes}
  3186. \label{sec:assign-homes-r2}
  3187. The \code{assign-homes} function (Section~\ref{sec:assign-s0}) needs
  3188. to be updated to handle the \key{if} statement, simply by recursively
  3189. processing the child nodes. Hopefully your code already handles the
  3190. other new instructions, but if not, you can generalize your code.
  3191. \begin{exercise}\normalfont
  3192. Implement the additions to the \code{register-allocation} pass so that
  3193. it works for $R_2$ and test your compiler using your previously
  3194. created programs on the \code{interp-x86} interpreter
  3195. (Appendix~\ref{appendix:interp}).
  3196. \end{exercise}
  3197. \section{Lower Conditionals (New Pass)}
  3198. \label{sec:lower-conditionals}
  3199. In the \code{select-instructions} pass we decided to procrastinate in
  3200. the lowering of the \key{if} statement, thereby making liveness
  3201. analysis easier. Now we need to make up for that and turn the \key{if}
  3202. statement into the appropriate instruction sequence. The following
  3203. translation gives the general idea. If the condition is true, we need
  3204. to execute the $\itm{thns}$ branch and otherwise we need to execute
  3205. the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3206. jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3207. is appropriate for the comparison operator \itm{cmp}. If the
  3208. condition is false, we fall through to the $\itm{elss}$ branch. At the
  3209. end of the $\itm{elss}$ branch we need to take care to not fall
  3210. through to the $\itm{thns}$ branch. So we jump to the
  3211. $\itm{endlabel}$. All of the labels in the generated code should be
  3212. created with \code{gensym}.
  3213. \begin{tabular}{lll}
  3214. \begin{minipage}{0.4\textwidth}
  3215. \begin{lstlisting}
  3216. (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3217. \end{lstlisting}
  3218. \end{minipage}
  3219. &
  3220. $\Rightarrow$
  3221. &
  3222. \begin{minipage}{0.4\textwidth}
  3223. \begin{lstlisting}
  3224. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3225. (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3226. |$\itm{elss}$|
  3227. (jmp |$\itm{endlabel}$|)
  3228. (label |$\itm{thenlabel}$|)
  3229. |$\itm{thns}$|
  3230. (label |$\itm{endlabel}$|)
  3231. \end{lstlisting}
  3232. \end{minipage}
  3233. \end{tabular}
  3234. \begin{exercise}\normalfont
  3235. Implement the \code{lower-conditionals} pass. Test your compiler using
  3236. your previously created programs on the \code{interp-x86} interpreter
  3237. (Appendix~\ref{appendix:interp}).
  3238. \end{exercise}
  3239. \section{Patch Instructions}
  3240. There are no special restrictions on the instructions \key{jmp-if},
  3241. \key{jmp}, and \key{label}, but there is an unusual restriction on
  3242. \key{cmpq}. The second argument is not allowed to be an immediate
  3243. value (such as a literal integer). If you are comparing two
  3244. immediates, you must insert another \key{movq} instruction to put the
  3245. second argument in \key{rax}.
  3246. \begin{exercise}\normalfont
  3247. Update \code{patch-instructions} to handle the new x86 instructions.
  3248. Test your compiler using your previously created programs on the
  3249. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3250. \end{exercise}
  3251. \section{An Example Translation}
  3252. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3253. $R_2$ translated to x86, showing the results of \code{flatten},
  3254. \code{select-instructions}, and the final x86 assembly.
  3255. \begin{figure}[tbp]
  3256. \begin{tabular}{lll}
  3257. \begin{minipage}{0.5\textwidth}
  3258. \begin{lstlisting}
  3259. (program
  3260. (if (eq? (read) 1) 42 0))
  3261. \end{lstlisting}
  3262. $\Downarrow$
  3263. \begin{lstlisting}
  3264. (program (t.1 t.2 if.1)
  3265. (assign t.1 (read))
  3266. (assign t.2 (eq? t.1 1))
  3267. (if (eq? #t t.2)
  3268. ((assign if.1 42))
  3269. ((assign if.1 0)))
  3270. (return if.1))
  3271. \end{lstlisting}
  3272. $\Downarrow$
  3273. \begin{lstlisting}
  3274. (program (t.1 t.2 if.1)
  3275. (callq read_int)
  3276. (movq (reg rax) (var t.1))
  3277. (cmpq (int 1) (var t.1))
  3278. (set e (byte-reg al))
  3279. (movzbq (byte-reg al) (var t.2))
  3280. (if (eq? (int 1) (var t.2))
  3281. ((movq (int 42) (var if.1)))
  3282. ((movq (int 0) (var if.1))))
  3283. (movq (var if.1) (reg rax)))
  3284. \end{lstlisting}
  3285. \end{minipage}
  3286. &
  3287. $\Rightarrow$
  3288. \begin{minipage}{0.4\textwidth}
  3289. \begin{lstlisting}
  3290. .globl _main
  3291. _main:
  3292. pushq %rbp
  3293. movq %rsp, %rbp
  3294. pushq %r15
  3295. pushq %r14
  3296. pushq %r13
  3297. pushq %r12
  3298. pushq %rbx
  3299. subq $8, %rsp
  3300. callq _read_int
  3301. movq %rax, %rcx
  3302. cmpq $1, %rcx
  3303. sete %al
  3304. movzbq %al, %rcx
  3305. cmpq $1, %rcx
  3306. je then21288
  3307. movq $0, %rbx
  3308. jmp if_end21289
  3309. then21288:
  3310. movq $42, %rbx
  3311. if_end21289:
  3312. movq %rbx, %rax
  3313. movq %rax, %rdi
  3314. callq _print_int
  3315. movq $0, %rax
  3316. addq $8, %rsp
  3317. popq %rbx
  3318. popq %r12
  3319. popq %r13
  3320. popq %r14
  3321. popq %r15
  3322. popq %rbp
  3323. retq
  3324. \end{lstlisting}
  3325. \end{minipage}
  3326. \end{tabular}
  3327. \caption{Example compilation of an \key{if} expression to x86.}
  3328. \label{fig:if-example-x86}
  3329. \end{figure}
  3330. \begin{figure}[p]
  3331. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3332. \node (R1) at (0,2) {\large $R_1$};
  3333. \node (R1-2) at (3,2) {\large $R_1$};
  3334. \node (R1-3) at (6,2) {\large $R_1$};
  3335. \node (C1-1) at (3,0) {\large $C_1$};
  3336. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3337. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3338. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3339. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  3340. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  3341. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3342. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3343. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R1-2);
  3344. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize uniquify} (R1-3);
  3345. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize\color{red} flatten} (C1-1);
  3346. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3347. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3348. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3349. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3350. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} lower-cond.} (x86-4);
  3351. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-5);
  3352. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  3353. \end{tikzpicture}
  3354. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3355. \label{fig:R2-passes}
  3356. \end{figure}
  3357. Figure~\ref{fig:R2-passes} gives an overview of all the passes needed
  3358. for the compilation of $R_2$.
  3359. \section{Challenge: Optimizing Conditions$^{*}$}
  3360. \label{sec:opt-if}
  3361. A close inspection of the x86 code generated in
  3362. Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3363. regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3364. twice using \key{cmpq} as follows.
  3365. % Wierd LaTeX bug if I remove the following. -Jeremy
  3366. % Does it have to do with page breaks?
  3367. \begin{lstlisting}
  3368. \end{lstlisting}
  3369. \begin{lstlisting}
  3370. cmpq $1, %rcx
  3371. sete %al
  3372. movzbq %al, %rcx
  3373. cmpq $1, %rcx
  3374. je then21288
  3375. \end{lstlisting}
  3376. The reason for this non-optimal code has to do with the \code{flatten}
  3377. pass earlier in this Chapter. We recommended flattening the condition
  3378. to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3379. is already an \code{eq?} test, then we would like to use that
  3380. directly. In fact, for many of the expressions of Boolean type, we can
  3381. generate more optimized code. For example, if the condition is
  3382. \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3383. all. If the condition is a \code{let}, we can optimize based on the
  3384. form of its body. If the condition is a \code{not}, then we can flip
  3385. the two branches.
  3386. %
  3387. \marginpar{\tiny We could do even better by converting to basic
  3388. blocks.\\ --Jeremy}
  3389. %
  3390. On the other hand, if the condition is a \code{and}
  3391. or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3392. code duplication.
  3393. Figure~\ref{fig:opt-if} shows an example program and the result of
  3394. applying the above suggested optimizations.
  3395. \begin{exercise}\normalfont
  3396. Change the \code{flatten} pass to improve the code that gets
  3397. generated for \code{if} expressions. We recommend writing a helper
  3398. function that recursively traverses the condition of the \code{if}.
  3399. \end{exercise}
  3400. \begin{figure}[tbp]
  3401. \begin{tabular}{lll}
  3402. \begin{minipage}{0.5\textwidth}
  3403. \begin{lstlisting}
  3404. (program
  3405. (if (let ([x 1])
  3406. (not (eq? 2 x)))
  3407. 42
  3408. 777))
  3409. \end{lstlisting}
  3410. $\Downarrow$
  3411. \begin{lstlisting}
  3412. (program (x.1 t.1 if.1)
  3413. (assign x.1 1)
  3414. (assign t.1 (read))
  3415. (if (eq? x.1 t.1)
  3416. ((assign if.1 42))
  3417. ((assign if.1 777)))
  3418. (return if.1))
  3419. \end{lstlisting}
  3420. $\Downarrow$
  3421. \begin{lstlisting}
  3422. (program (x.1 t.1 if.1)
  3423. (movq (int 1) (var x.1))
  3424. (callq read_int)
  3425. (movq (reg rax) (var t.1))
  3426. (if (eq? (var x.1) (var t.1))
  3427. ((movq (int 42) (var if.1)))
  3428. ((movq (int 777) (var if.1))))
  3429. (movq (var if.1) (reg rax)))
  3430. \end{lstlisting}
  3431. \end{minipage}
  3432. &
  3433. $\Rightarrow$
  3434. \begin{minipage}{0.4\textwidth}
  3435. \begin{lstlisting}
  3436. .globl _main
  3437. _main:
  3438. pushq %rbp
  3439. movq %rsp, %rbp
  3440. pushq %r15
  3441. pushq %r14
  3442. pushq %r13
  3443. pushq %r12
  3444. pushq %rbx
  3445. subq $8, %rsp
  3446. movq $1, %rbx
  3447. callq _read_int
  3448. movq %rax, %rcx
  3449. cmpq %rbx, %rcx
  3450. je then21288
  3451. movq $777, %r12
  3452. jmp if_end21289
  3453. then21288:
  3454. movq $42, %r12
  3455. if_end21289:
  3456. movq %r12, %rax
  3457. movq %rax, %rdi
  3458. callq _print_int
  3459. movq $0, %rax
  3460. addq $8, %rsp
  3461. popq %rbx
  3462. popq %r12
  3463. popq %r13
  3464. popq %r14
  3465. popq %r15
  3466. popq %rbp
  3467. retq
  3468. \end{lstlisting}
  3469. \end{minipage}
  3470. \end{tabular}
  3471. \caption{Example program with optimized conditionals.}
  3472. \label{fig:opt-if}
  3473. \end{figure}
  3474. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3475. \chapter{Tuples and Garbage Collection}
  3476. \label{ch:tuples}
  3477. \marginpar{\scriptsize To do: look through Andre's code comments for extra
  3478. things to discuss in this chapter. \\ --Jeremy}
  3479. \marginpar{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3480. all the IR grammars are spelled out! \\ --Jeremy}
  3481. \marginpar{\scriptsize Introduce has-type, but after flatten, remove it,
  3482. but keep type annotations on vector creation and local variables, function
  3483. parameters, etc. \\ --Jeremy}
  3484. In this chapter we study the implementation of mutable tuples (called
  3485. ``vectors'' in Racket). This language feature is the first to use the
  3486. computer's \emph{heap} because the lifetime of a Racket tuple is
  3487. indefinite, that is, a tuple does not follow a stack (FIFO) discipline
  3488. but instead lives forever from the programmer's viewpoint. Of course,
  3489. from an implementor's viewpoint, it is important to reclaim the space
  3490. associated with tuples when they are no longer needed, which is why we
  3491. also study \emph{garbage collection} techniques in this chapter.
  3492. Section~\ref{sec:r3} introduces the $R_3$ language including its
  3493. interpreter and type checker. The $R_3$ language extends the $R_2$
  3494. language of Chapter~\ref{ch:bool-types} with vectors and void values
  3495. (because the \code{vector-set!} operation returns a void
  3496. value). Section~\ref{sec:GC} describes a garbage collection algorithm
  3497. based on copying live objects back and forth between two halves of the
  3498. heap. The garbage collector requires coordination with the compiler so
  3499. that it can see all of the \emph{root} pointers, that is, pointers in
  3500. registers or on the procedure call stack.
  3501. Section~\ref{sec:code-generation-gc} discusses all the necessary
  3502. changes and additions to the compiler passes, including type checking,
  3503. instruction selection, register allocation, and a new compiler pass
  3504. named \code{expose-allocation}.
  3505. \section{The $R_3$ Language}
  3506. \label{sec:r3}
  3507. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  3508. includes three new forms for creating a tuple, reading an element of a
  3509. tuple, and writing to an element of a tuple. The program in
  3510. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  3511. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3512. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  3513. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  3514. ``then'' branch is taken. The element at index $0$ of \code{t} is
  3515. $40$, to which we add the $2$, the element at index $0$ of the
  3516. 1-tuple.
  3517. \begin{figure}[tbp]
  3518. \begin{lstlisting}
  3519. (let ([t (vector 40 #t (vector 2))])
  3520. (if (vector-ref t 1)
  3521. (+ (vector-ref t 0)
  3522. (vector-ref (vector-ref t 2) 0))
  3523. 44))
  3524. \end{lstlisting}
  3525. \caption{Example program that creates tuples and reads from them.}
  3526. \label{fig:vector-eg}
  3527. \end{figure}
  3528. \begin{figure}[tbp]
  3529. \centering
  3530. \fbox{
  3531. \begin{minipage}{0.96\textwidth}
  3532. \[
  3533. \begin{array}{lcl}
  3534. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  3535. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  3536. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  3537. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \\
  3538. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  3539. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  3540. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) }\\
  3541. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} } \\
  3542. &\mid& (\key{vector}\;\Exp^{+}) \mid
  3543. (\key{vector-ref}\;\Exp\;\Int) \\
  3544. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  3545. &\mid& (\key{void}) \\
  3546. R_3 &::=& (\key{program} \;(\key{type}\;\itm{type})\; \Exp)
  3547. \end{array}
  3548. \]
  3549. \end{minipage}
  3550. }
  3551. \caption{The syntax of $R_3$, extending $R_2$ with tuples.}
  3552. \label{fig:r3-syntax}
  3553. \end{figure}
  3554. Tuples are our first encounter with heap-allocated data, which raises
  3555. several interesting issues. First, variable binding performs a
  3556. shallow-copy when dealing with tuples, which means that different
  3557. variables can refer to the same tuple, i.e., different variables can
  3558. be \emph{aliases} for the same thing. Consider the following example
  3559. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  3560. the mutation through \code{t2} is visible when referencing the tuple
  3561. from \code{t1}, so the result of this program is \code{42}.
  3562. \begin{lstlisting}
  3563. (let ([t1 (vector 3 7)])
  3564. (let ([t2 t1])
  3565. (let ([_ (vector-set! t2 0 42)])
  3566. (vector-ref t1 0))))
  3567. \end{lstlisting}
  3568. The next issue concerns the lifetime of tuples. Of course, they are
  3569. created by the \code{vector} form, but when does their lifetime end?
  3570. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  3571. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  3572. is not tied to any notion of static scoping. For example, the
  3573. following program returns \code{3} even though the variable \code{t}
  3574. goes out of scope prior to accessing the vector.
  3575. \begin{lstlisting}
  3576. (vector-ref
  3577. (let ([t (vector 3 7)])
  3578. t)
  3579. 0)
  3580. \end{lstlisting}
  3581. From the perspective of programmer-observable behavior, tuples live
  3582. forever. Of course, if they really lived forever, then many programs
  3583. would run out of memory.\footnote{The $R_3$ language does not have
  3584. looping or recursive function, so it is nigh impossible to write a
  3585. program in $R_3$ that will run out of memory. However, we add
  3586. recursive functions in the next Chapter!} A Racket implementation
  3587. must therefore perform automatic garbage collection.
  3588. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  3589. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  3590. checker. The additions to the interpreter are straightforward but the
  3591. updates to the type checker deserve some explanation. As we shall see
  3592. in Section~\ref{sec:GC}, we need to know which variables are pointers
  3593. into the heap, that is, which variables are vectors. Also, when
  3594. allocating a vector, we shall need to know which elements of the
  3595. vector are pointers. We can obtain this information during type
  3596. checking and flattening. The type checker in
  3597. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  3598. expression, it also wraps every sub-expression $e$ with the form
  3599. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  3600. the flatten pass (Section~\ref{sec:flatten-gc}) this type information is
  3601. propagated to all variables (including temporaries generated during
  3602. flattening).
  3603. \begin{figure}[tbp]
  3604. \begin{lstlisting}
  3605. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  3606. (define (interp-op op)
  3607. (match op
  3608. ...
  3609. ['vector vector]
  3610. ['vector-ref vector-ref]
  3611. ['vector-set! vector-set!]
  3612. [else (error 'interp-op "unknown operator")]))
  3613. (define (interp-R3 env)
  3614. (lambda (e)
  3615. (match e
  3616. ...
  3617. [else (error 'interp-R3 "unrecognized expression")]
  3618. )))
  3619. \end{lstlisting}
  3620. \caption{Interpreter for the $R_3$ language.}
  3621. \label{fig:interp-R3}
  3622. \end{figure}
  3623. \begin{figure}[tbp]
  3624. \begin{lstlisting}
  3625. (define (typecheck-R3 env)
  3626. (lambda (e)
  3627. (match e
  3628. ...
  3629. ['(void) (values '(has-type (void) Void) 'Void)]
  3630. [`(vector ,(app (type-check env) e* t*) ...)
  3631. (let ([t `(Vector ,@t*)])
  3632. (values `(has-type (vector ,@e*) ,t) t))]
  3633. [`(vector-ref ,(app (type-check env) e t) ,i)
  3634. (match t
  3635. [`(Vector ,ts ...)
  3636. (unless (and (exact-nonnegative-integer? i)
  3637. (i . < . (length ts)))
  3638. (error 'type-check "invalid index ~a" i))
  3639. (let ([t (list-ref ts i)])
  3640. (values `(has-type (vector-ref ,e (has-type ,i Integer)) ,t)
  3641. t))]
  3642. [else (error "expected a vector in vector-ref, not" t)])]
  3643. [`(vector-set! ,(app (type-check env) e-vec^ t-vec) ,i
  3644. ,(app (type-check env) e-arg^ t-arg))
  3645. (match t-vec
  3646. [`(Vector ,ts ...)
  3647. (unless (and (exact-nonnegative-integer? i)
  3648. (i . < . (length ts)))
  3649. (error 'type-check "invalid index ~a" i))
  3650. (unless (equal? (list-ref ts i) t-arg)
  3651. (error 'type-check "type mismatch in vector-set! ~a ~a"
  3652. (list-ref ts i) t-arg))
  3653. (values `(has-type (vector-set! ,e-vec^
  3654. (has-type ,i Integer)
  3655. ,e-arg^) Void) 'Void)]
  3656. [else (error 'type-check
  3657. "expected a vector in vector-set!, not ~a" t-vec)])]
  3658. [`(eq? ,(app (type-check env) e1 t1)
  3659. ,(app (type-check env) e2 t2))
  3660. (match* (t1 t2)
  3661. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  3662. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  3663. [(other wise) ((super type-check env) e)])]
  3664. )))
  3665. \end{lstlisting}
  3666. \caption{Type checker for the $R_3$ language.}
  3667. \label{fig:typecheck-R3}
  3668. \end{figure}
  3669. \section{Garbage Collection}
  3670. \label{sec:GC}
  3671. Here we study a relatively simple algorithm for garbage collection
  3672. that is the basis of state-of-the-art garbage
  3673. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  3674. particular, we describe a two-space copying
  3675. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  3676. perform the
  3677. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  3678. coarse-grained depiction of what happens in a two-space collector,
  3679. showing two time steps, prior to garbage collection on the top and
  3680. after garbage collection on the bottom. In a two-space collector, the
  3681. heap is divided into two parts, the FromSpace and the
  3682. ToSpace. Initially, all allocations go to the FromSpace until there is
  3683. not enough room for the next allocation request. At that point, the
  3684. garbage collector goes to work to make more room.
  3685. The garbage collector must be careful not to reclaim tuples that will
  3686. be used by the program in the future. Of course, it is impossible in
  3687. general to predict what a program will do, but we can overapproximate
  3688. the will-be-used tuples by preserving all tuples that could be
  3689. accessed by \emph{any} program given the current computer state. A
  3690. program could access any tuple whose address is in a register or on
  3691. the procedure call stack. These addresses are called the \emph{root
  3692. set}. In addition, a program could access any tuple that is
  3693. transitively reachable from the root set. Thus, it is safe for the
  3694. garbage collector to reclaim the tuples that are not reachable in this
  3695. way.
  3696. %
  3697. \footnote{The sitation in Figure~\ref{fig:copying-collector}, with a
  3698. cycle, cannot be created by a well-typed program in $R_3$. However,
  3699. creating cycles will be possible once we get to $R_6$. We design
  3700. the garbage collector to deal with cycles to begin with, so we will
  3701. not need to revisit this issue.}
  3702. So the goal of the garbage collector is twofold:
  3703. \begin{enumerate}
  3704. \item preserve all tuple that are reachable from the root set via a
  3705. path of pointers, that is, the \emph{live} tuples, and
  3706. \item reclaim the memory of everything else, that is, the
  3707. \emph{garbage}.
  3708. \end{enumerate}
  3709. A copying collector accomplishes this by copying all of the live
  3710. objects into the ToSpace and then performs a slight of hand, treating
  3711. the ToSpace as the new FromSpace and the old FromSpace as the new
  3712. ToSpace. In the example of Figure~\ref{fig:copying-collector}, there
  3713. are three pointers in the root set, one in a register and two on the
  3714. stack. All of the live objects have been copied to the ToSpace (the
  3715. right-hand side of Figure~\ref{fig:copying-collector}) in a way that
  3716. preserves the pointer relationships. For example, the pointer in the
  3717. register still points to a 2-tuple whose first element is a 3-tuple
  3718. and second element is a 2-tuple. There are four tuples that are not
  3719. reachable from the root set and therefore do not get copied into the
  3720. ToSpace.
  3721. \begin{figure}[tbp]
  3722. \centering
  3723. \includegraphics[width=\textwidth]{copy-collect-1} \\[5ex]
  3724. \includegraphics[width=\textwidth]{copy-collect-2}
  3725. \caption{A copying collector in action.}
  3726. \label{fig:copying-collector}
  3727. \end{figure}
  3728. %% \marginpar{\tiny Need to add comment somewhere about the goodness
  3729. %% of copying collection, especially that it doesn't touch
  3730. %% the garbage, so its time complexity only depends on the
  3731. %% amount of live data.\\ --Jeremy}
  3732. There are many alternatives to copying collectors (and their older
  3733. siblings, the generational collectors) when its comes to garbage
  3734. collection, such as mark-and-sweep and reference counting. The
  3735. strengths of copying collectors are that allocation is fast (just a
  3736. test and pointer increment), there is no fragmentation, cyclic garbage
  3737. is collected, and the time complexity of collection only depends on
  3738. the amount of live data, and not on the amount of
  3739. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  3740. copying collectors is that they use a lot of space, though that
  3741. problem is ameliorated in generational collectors. Racket and Scheme
  3742. programs tend to allocate many small objects and generate a lot of
  3743. garbage, so copying and generational collectors are a good fit. Of
  3744. course, garbage collection is an active research topic, especially
  3745. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  3746. continuously developing new techniques and revisiting old
  3747. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  3748. \subsection{Graph Copying via Cheney's Algorithm}
  3749. \label{sec:cheney}
  3750. Let us take a closer look at how the copy works. The allocated objects
  3751. and pointers can be viewed as a graph and we need to copy the part of
  3752. the graph that is reachable from the root set. To make sure we copy
  3753. all of the reachable vertices in the graph, we need an exhaustive
  3754. graph traversal algorithm, such as depth-first search or breadth-first
  3755. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  3756. take into account the possibility of cycles by marking which vertices
  3757. have already been visited, so as to ensure termination of the
  3758. algorithm. These search algorithms also use a data structure such as a
  3759. stack or queue as a to-do list to keep track of the vertices that need
  3760. to be visited. We shall use breadth-first search and a trick due to
  3761. \citet{Cheney:1970aa} for simultaneously representing the queue and
  3762. copying tuples into the ToSpace.
  3763. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  3764. copy progresses. The queue is represented by a chunk of contiguous
  3765. memory at the beginning of the ToSpace, using two pointers to track
  3766. the front and the back of the queue. The algorithm starts by copying
  3767. all tuples that are immediately reachable from the root set into the
  3768. ToSpace to form the initial queue. When we copy a tuple, we mark the
  3769. old tuple to indicate that it has been visited. (We discuss the
  3770. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  3771. inside the copied tuples in the queue still point back to the
  3772. FromSpace. Once the initial queue has been created, the algorithm
  3773. enters a loop in which it repeatedly processes the tuple at the front
  3774. of the queue and pops it off the queue. To process a tuple, the
  3775. algorithm copies all the tuple that are directly reachable from it to
  3776. the ToSpace, placing them at the back of the queue. The algorithm then
  3777. updates the pointers in the popped tuple so they point to the newly
  3778. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  3779. step we copy the tuple whose second element is $42$ to the back of the
  3780. queue. The other pointer goes to a tuple that has already been copied,
  3781. so we do not need to copy it again, but we do need to update the
  3782. pointer to the new location. This can be accomplished by storing a
  3783. \emph{forwarding} pointer to the new location in the old tuple, back
  3784. when we initially copied the tuple into the ToSpace. This completes
  3785. one step of the algorithm. The algorithm continues in this way until
  3786. the front of the queue is empty, that is, until the front catches up
  3787. with the back.
  3788. \begin{figure}[tbp]
  3789. \centering \includegraphics[width=0.9\textwidth]{cheney}
  3790. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  3791. \label{fig:cheney}
  3792. \end{figure}
  3793. \subsection{Data Representation}
  3794. \label{sec:data-rep-gc}
  3795. The garbage collector places some requirements on the data
  3796. representations used by our compiler. First, the garbage collector
  3797. needs to distinguish between pointers and other kinds of data. There
  3798. are several ways to accomplish this.
  3799. \begin{enumerate}
  3800. \item Attached a tag to each object that identifies what type of
  3801. object it is~\citep{McCarthy:1960dz}.
  3802. \item Store different types of objects in different
  3803. regions~\citep{Steele:1977ab}.
  3804. \item Use type information from the program to either generate
  3805. type-specific code for collecting or to generate tables that can
  3806. guide the
  3807. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  3808. \end{enumerate}
  3809. Dynamically typed languages, such as Lisp, need to tag objects
  3810. anyways, so option 1 is a natural choice for those languages.
  3811. However, $R_3$ is a statically typed language, so it would be
  3812. unfortunate to require tags on every object, especially small and
  3813. pervasive objects like integers and Booleans. Option 3 is the
  3814. best-performing choice for statically typed languages, but comes with
  3815. a relatively high implementation complexity. To keep this chapter to a
  3816. 2-week time budget, we recommend a combination of options 1 and 2,
  3817. with separate strategies used for the stack and the heap.
  3818. Regarding the stack, we recommend using a separate stack for
  3819. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  3820. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  3821. local variable needs to be spilled and is of type \code{(Vector
  3822. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  3823. of the normal procedure call stack. Furthermore, we always spill
  3824. vector-typed variables if they are live during a call to the
  3825. collector, thereby ensuring that no pointers are in registers during a
  3826. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  3827. Figure~\ref{fig:copying-collector} and contrasts it with the data
  3828. layout using a root stack. The root stack contains the two pointers
  3829. from the regular stack and also the pointer in the second
  3830. register.
  3831. \begin{figure}[tbp]
  3832. \centering \includegraphics[width=0.7\textwidth]{root-stack}
  3833. \caption{Maintaining a root stack to facilitate garbage collection.}
  3834. \label{fig:shadow-stack}
  3835. \end{figure}
  3836. The problem of distinguishing between pointers and other kinds of data
  3837. also arises inside of each tuple. We solve this problem by attaching a
  3838. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  3839. in on the tags for two of the tuples in the example from
  3840. Figure~\ref{fig:copying-collector}. Part of each tag is dedicated to
  3841. specifying which elements of the tuple are pointers, the part labeled
  3842. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  3843. a pointer and a 0 bit indicates some other kind of data. The pointer
  3844. mask starts at bit location 7. We have limited tuples to a maximum
  3845. size of 50 elements, so we just need 50 bits for the pointer mask. The
  3846. tag also contains two other pieces of information. The length of the
  3847. tuple (number of elements) is stored in bits location 1 through
  3848. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  3849. to be copied to the FromSpace. If the bit has value 1, then this
  3850. tuple has not yet been copied. If the bit has value 0 then the entire
  3851. tag is in fact a forwarding pointer. (The lower 3 bits of an pointer
  3852. are always zero anyways because our tuples are 8-byte aligned.)
  3853. \begin{figure}[tbp]
  3854. \centering \includegraphics[width=0.8\textwidth]{tuple-rep}
  3855. \caption{Representation for tuples in the heap.}
  3856. \label{fig:tuple-rep}
  3857. \end{figure}
  3858. \subsection{Implementation of the Garbage Collector}
  3859. \label{sec:organize-gz}
  3860. The implementation of the garbage collector needs to do a lot of
  3861. bit-level data manipulation and we need to link it with our
  3862. compiler-generated x86 code. Thus, we recommend implementing the
  3863. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  3864. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  3865. interface to the garbage collector. The \code{initialize} function
  3866. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  3867. function is meant to be called near the beginning of \code{main},
  3868. before the rest of the program executes. The \code{initialize}
  3869. function puts the address of the beginning of the FromSpace into the
  3870. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  3871. points to the address that is 1-past the last element of the
  3872. FromSpace. (We use half-open intervals to represent chunks of
  3873. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  3874. points to the first element of the root stack.
  3875. As long as there is room left in the FromSpace, your generated code
  3876. can allocate tuples simply by moving the \code{free\_ptr} forward.
  3877. %
  3878. \marginpar{\tiny Should we dedicate a register to the free pointer? \\
  3879. --Jeremy}
  3880. %
  3881. The amount of room left in FromSpace is the difference between the
  3882. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  3883. function should be called when there is not enough room left in the
  3884. FromSpace for the next allocation. The \code{collect} function takes
  3885. a pointer to the current top of the root stack (one past the last item
  3886. that was pushed) and the number of bytes that need to be
  3887. allocated. The \code{collect} function performs the copying collection
  3888. and leaves the heap in a state such that the next allocation will
  3889. succeed.
  3890. \begin{figure}[tbp]
  3891. \begin{lstlisting}
  3892. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  3893. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  3894. int64_t* free_ptr;
  3895. int64_t* fromspace_begin;
  3896. int64_t* fromspace_end;
  3897. int64_t** rootstack_begin;
  3898. \end{lstlisting}
  3899. \caption{The compiler's interface to the garbage collector.}
  3900. \label{fig:gc-header}
  3901. \end{figure}
  3902. \begin{exercise}
  3903. In the file \code{runtime.c} you will find the implementation of
  3904. \code{initialize} and a partial implementation of \code{collect}.
  3905. The \code{collect} function calls another function, \code{cheney},
  3906. to perform the actual copy, and that function is left to the reader
  3907. to implement. The following is the prototype for \code{cheney}.
  3908. \begin{lstlisting}
  3909. static void cheney(int64_t** rootstack_ptr);
  3910. \end{lstlisting}
  3911. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  3912. rootstack (which is array of pointers). The \code{cheney} function
  3913. also communicates with \code{collect} through several global
  3914. variables, the \code{framespace\_begin} and \code{framespace\_end}
  3915. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  3916. the ToSpace:
  3917. \begin{lstlisting}
  3918. static int64_t* tospace_begin;
  3919. static int64_t* tospace_end;
  3920. \end{lstlisting}
  3921. The job of the \code{cheney} function is to copy all the live
  3922. objects (reachable from the root stack) into the ToSpace, update
  3923. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  3924. update the root stack so that it points to the objects in the
  3925. ToSpace, and finally to swap the global pointers for the FromSpace
  3926. and ToSpace.
  3927. \end{exercise}
  3928. \section{Compiler Passes}
  3929. \label{sec:code-generation-gc}
  3930. The introduction of garbage collection has a non-trivial impact on our
  3931. compiler passes. We introduce one new compiler pass called
  3932. \code{expose-allocation} and make non-trivial changes to
  3933. \code{type-check}, \code{flatten}, \code{select-instructions},
  3934. \code{allocate-registers}, and \code{print-x86}. The following
  3935. program will serve as our running example. It creates two tuples, one
  3936. nested inside the other. Both tuples have length one. The example then
  3937. accesses the element in the inner tuple tuple via two vector
  3938. references.
  3939. % tests/s2_17.rkt
  3940. \begin{lstlisting}
  3941. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  3942. \end{lstlisting}
  3943. We already discuss the changes to \code{type-check} in
  3944. Section~\ref{sec:r3}, including the addition of \code{has-type}, so we
  3945. proceed to discuss the new \code{expose-allocation} pass.
  3946. \subsection{Expose Allocation (New)}
  3947. \label{sec:expose-allocation}
  3948. The pass \code{expose-allocation} lowers the \code{vector} creation
  3949. form into a conditional call to the collector followed by the
  3950. allocation. We choose to place the \code{expose-allocation} pass
  3951. before \code{flatten} because \code{expose-allocation} introduces new
  3952. variables, which can be done locally with \code{let}, but \code{let}
  3953. is gone after \code{flatten}. In the following, we show the
  3954. transformation for the \code{vector} form into let-bindings for the
  3955. intializing expressions, by a conditional \code{collect}, an
  3956. \code{allocate}, and the initialization of the vector.
  3957. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  3958. total bytes need to be allocated for the vector, which is 8 for the
  3959. tag plus \itm{len} times 8.)
  3960. \begin{lstlisting}
  3961. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  3962. |$\Longrightarrow$|
  3963. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  3964. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  3965. (global-value fromspace_end))
  3966. (void)
  3967. (collect |\itm{bytes}|))])
  3968. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  3969. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  3970. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  3971. |$v$|) ... )))) ...)
  3972. \end{lstlisting}
  3973. (In the above, we suppressed all of the \code{has-type} forms in the
  3974. output for the sake of readability.) The ordering of the initializing
  3975. expressions ($e_0,\ldots,e_{n-1}$) prior to the \code{allocate} is
  3976. important, as those expressions may trigger garbage collection and we
  3977. do not want an allocated but uninitialized tuple to be present during
  3978. a garbage collection.
  3979. The output of \code{expose-allocation} is a language that extends
  3980. $R_3$ with the three new forms that we use above in the translation of
  3981. \code{vector}.
  3982. \[
  3983. \begin{array}{lcl}
  3984. \Exp &::=& \cdots
  3985. \mid (\key{collect} \,\itm{int})
  3986. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  3987. \mid (\key{global-value} \,\itm{name})
  3988. \end{array}
  3989. \]
  3990. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  3991. %% the beginning of the program which will instruct the garbage collector
  3992. %% to set up the FromSpace, ToSpace, and all the global variables. The
  3993. %% two arguments of \code{initialize} specify the initial allocated space
  3994. %% for the root stack and for the heap.
  3995. %
  3996. %% The \code{expose-allocation} pass annotates all of the local variables
  3997. %% in the \code{program} form with their type.
  3998. Figure~\ref{fig:expose-alloc-output} shows the output of the
  3999. \code{expose-allocation} pass on our running example.
  4000. \begin{figure}[tbp]
  4001. \begin{lstlisting}
  4002. (program (type Integer)
  4003. (vector-ref
  4004. (vector-ref
  4005. (let ((vecinit32990
  4006. (let ([vecinit32986 42])
  4007. (let ((collectret32988
  4008. (if (< (+ (global-value free_ptr) 16)
  4009. (global-value fromspace_end))
  4010. (void)
  4011. (collect 16))))
  4012. (let ([alloc32985
  4013. (allocate 1 (Vector Integer))])
  4014. (let ([initret32987
  4015. (vector-set! alloc32985 0 vecinit32986)])
  4016. alloc32985))))))
  4017. (let ([collectret32992
  4018. (if (< (+ (global-value free_ptr) 16)
  4019. (global-value fromspace_end))
  4020. (void)
  4021. (collect 16))])
  4022. (let ([alloc32989 (allocate 1 (Vector (Vector Integer)))])
  4023. (let ([initret32991 (vector-set! alloc32989 0 vecinit32990)])
  4024. alloc32989))))
  4025. 0)
  4026. 0))
  4027. \end{lstlisting}
  4028. \caption{Output of the \code{expose-allocation} pass, minus
  4029. all of the \code{has-type} forms.}
  4030. \label{fig:expose-alloc-output}
  4031. \end{figure}
  4032. \clearpage
  4033. \subsection{Flatten and the $C_2$ intermediate language}
  4034. \label{sec:flatten-gc}
  4035. \begin{figure}[tp]
  4036. \fbox{
  4037. \begin{minipage}{0.96\textwidth}
  4038. \[
  4039. \begin{array}{lcl}
  4040. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4041. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4042. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4043. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4044. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4045. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4046. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4047. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4048. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4049. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4050. &\mid& (\key{collect} \,\itm{int}) \\
  4051. C_2 & ::= & \gray{ (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+}) }
  4052. \end{array}
  4053. \]
  4054. \end{minipage}
  4055. }
  4056. \caption{The $C_2$ language, extending $C_1$ with support for tuples.}
  4057. \label{fig:c2-syntax}
  4058. \end{figure}
  4059. The output of \code{flatten} is a program in the intermediate language
  4060. $C_2$, whose syntax is defined in Figure~\ref{fig:c2-syntax}. The new
  4061. forms of $C_2$ include the expressions \key{allocate},
  4062. \key{vector-ref}, and \key{vector-set!}, and \key{global-value} and
  4063. the statement \code{collect}. The \code{flatten} pass can treat these
  4064. new forms much like the other forms.
  4065. Recall that the \code{flatten} function collects all of the local
  4066. variables so that it can decorate the \code{program} form with
  4067. them. Also recall that we need to know the types of all the local
  4068. variables for purposes of identifying the root set for the garbage
  4069. collector. Thus, we change \code{flatten} to collect not just the
  4070. variables, but the variables and their types in the form of an
  4071. association list. Thanks to the \code{has-type} forms, the types are
  4072. readily available. For example, consider the translation of the
  4073. \code{let} form.
  4074. \begin{lstlisting}
  4075. (let ([|$x$| (has-type |\itm{rhs}| |\itm{type}|)]) |\itm{body}|)
  4076. |$\Longrightarrow$|
  4077. (values |\itm{body'}|
  4078. (|\itm{ss_1}| (assign |$x$| |\itm{rhs'}|) |\itm{ss_2}|)
  4079. ((|$x$| . |\itm{type}|) |\itm{xt_1}| |\itm{xt_2}|))
  4080. \end{lstlisting}
  4081. where \itm{rhs'}, \itm{ss_1}, and \itm{xs_1} are the results of
  4082. recursively flattening \itm{rhs} and \itm{body'}, \itm{ss_2}, and
  4083. \itm{xs_2} are the results of recursively flattening \itm{body}. The
  4084. output on our running example is shown in Figure~\ref{fig:flatten-gc}.
  4085. \begin{figure}[tbp]
  4086. \begin{lstlisting}
  4087. '(program
  4088. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4089. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void)
  4090. (tmp94 . Integer) (tmp93 . Integer) (tmp95 . Integer)
  4091. (tmp85 Vector Integer) (tmp87 . Void) (tmp92 . Void)
  4092. (tmp00 . Void) (tmp98 . Integer) (tmp97 . Integer)
  4093. (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4094. (tmp91 . Void))
  4095. (type Integer)
  4096. (assign tmp86 42)
  4097. (assign tmp93 (global-value free_ptr))
  4098. (assign tmp94 (+ tmp93 16))
  4099. (assign tmp95 (global-value fromspace_end))
  4100. (if (< tmp94 tmp95)
  4101. ((assign tmp96 (void)))
  4102. ((collect 16) (assign tmp96 (void))))
  4103. (assign tmp88 tmp96)
  4104. (assign tmp85 (allocate 1 (Vector Integer)))
  4105. (assign tmp87 (vector-set! tmp85 0 tmp86))
  4106. (assign tmp90 tmp85)
  4107. (assign tmp97 (global-value free_ptr))
  4108. (assign tmp98 (+ tmp97 16))
  4109. (assign tmp99 (global-value fromspace_end))
  4110. (if (< tmp98 tmp99)
  4111. ((assign tmp00 (void)))
  4112. ((collect 16) (assign tmp00 (void))))
  4113. (assign tmp92 tmp00)
  4114. (assign tmp89 (allocate 1 (Vector (Vector Integer))))
  4115. (assign tmp91 (vector-set! tmp89 0 tmp90))
  4116. (assign tmp01 (vector-ref tmp89 0))
  4117. (assign tmp02 (vector-ref tmp01 0))
  4118. (return tmp02))
  4119. \end{lstlisting}
  4120. \caption{Output of \code{flatten} for the running example.}
  4121. \label{fig:flatten-gc}
  4122. \end{figure}
  4123. \clearpage
  4124. \subsection{Select Instructions}
  4125. \label{sec:select-instructions-gc}
  4126. %% void (rep as zero)
  4127. %% allocate
  4128. %% collect (callq collect)
  4129. %% vector-ref
  4130. %% vector-set!
  4131. %% global-value (postpone)
  4132. In this pass we generate x86 code for most of the new operations that
  4133. were needed to compile tuples, including \code{allocate},
  4134. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4135. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4136. The \code{vector-ref} and \code{vector-set!} forms translate into
  4137. \code{movq} instructions with the appropriate \key{deref}. (The
  4138. plus one is to get past the tag at the beginning of the tuple
  4139. representation.)
  4140. \begin{lstlisting}
  4141. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4142. |$\Longrightarrow$|
  4143. (movq |$\itm{vec}'$| (reg r11))
  4144. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4145. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4146. |$\Longrightarrow$|
  4147. (movq |$\itm{vec}'$| (reg r11))
  4148. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4149. (movq (int 0) |$\itm{lhs}$|)
  4150. \end{lstlisting}
  4151. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4152. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4153. register \code{r11} ensures that offsets are only performed with
  4154. register operands. This requires removing \code{r11} from
  4155. consideration by the register allocating.
  4156. We compile the \code{allocate} form to operations on the
  4157. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4158. is the next free address in the FromSpace, so we move it into the
  4159. \itm{lhs} and then move it forward by enough space for the tuple being
  4160. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4161. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4162. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4163. how the tag is organized. We recommend using the Racket operations
  4164. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4165. The type annoation in the \code{vector} form is used to determine the
  4166. pointer mask region of the tag.
  4167. \begin{lstlisting}
  4168. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4169. |$\Longrightarrow$|
  4170. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4171. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4172. (movq |$\itm{lhs}'$| (reg r11))
  4173. (movq (int |$\itm{tag}$|) (deref r11 0))
  4174. \end{lstlisting}
  4175. The \code{collect} form is compiled to a call to the \code{collect}
  4176. function in the runtime. The arguments to \code{collect} are the top
  4177. of the root stack and the number of bytes that need to be allocated.
  4178. We shall use a dedicated register, \code{r15}, to store the pointer to
  4179. the top of the root stack. So \code{r15} is not available for use by
  4180. the register allocator.
  4181. \begin{lstlisting}
  4182. (collect |$\itm{bytes}$|)
  4183. |$\Longrightarrow$|
  4184. (movq (reg 15) (reg rdi))
  4185. (movq |\itm{bytes}| (reg rsi))
  4186. (callq collect)
  4187. \end{lstlisting}
  4188. \begin{figure}[tp]
  4189. \fbox{
  4190. \begin{minipage}{0.96\textwidth}
  4191. \[
  4192. \begin{array}{lcl}
  4193. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4194. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4195. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4196. \mid (\key{global-value}\; \itm{name}) \\
  4197. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4198. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4199. (\key{subq} \; \Arg\; \Arg) \mid
  4200. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4201. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4202. (\key{pushq}\;\Arg) \mid
  4203. (\key{popq}\;\Arg) \mid
  4204. (\key{retq})} \\
  4205. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4206. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4207. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4208. \mid (\key{jmp} \; \itm{label})
  4209. \mid (\key{j}\itm{cc} \; \itm{label})
  4210. \mid (\key{label} \; \itm{label}) } \\
  4211. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4212. \end{array}
  4213. \]
  4214. \end{minipage}
  4215. }
  4216. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4217. \label{fig:x86-2}
  4218. \end{figure}
  4219. The syntax of the $x86_2$ language is defined in
  4220. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4221. of the form for global variables.
  4222. %
  4223. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4224. \code{select-instructions} pass on the running example.
  4225. \begin{figure}[tbp]
  4226. \centering
  4227. \begin{minipage}{0.75\textwidth}
  4228. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4229. (program
  4230. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4231. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void) (tmp94 . Integer)
  4232. (tmp93 . Integer) (tmp95 . Integer) (tmp85 Vector Integer)
  4233. (tmp87 . Void) (tmp92 . Void) (tmp00 . Void) (tmp98 . Integer)
  4234. (tmp97 . Integer) (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4235. (tmp91 . Void)) (type Integer)
  4236. (movq (int 42) (var tmp86))
  4237. (movq (global-value free_ptr) (var tmp93))
  4238. (movq (var tmp93) (var tmp94))
  4239. (addq (int 16) (var tmp94))
  4240. (movq (global-value fromspace_end) (var tmp95))
  4241. (if (< (var tmp94) (var tmp95))
  4242. ((movq (int 0) (var tmp96)))
  4243. ((movq (reg r15) (reg rdi))
  4244. (movq (int 16) (reg rsi))
  4245. (callq collect)
  4246. (movq (int 0) (var tmp96))))
  4247. (movq (var tmp96) (var tmp88))
  4248. (movq (global-value free_ptr) (var tmp85))
  4249. (addq (int 16) (global-value free_ptr))
  4250. (movq (var tmp85) (reg r11))
  4251. (movq (int 3) (deref r11 0))
  4252. (movq (var tmp85) (reg r11))
  4253. (movq (var tmp86) (deref r11 8))
  4254. (movq (int 0) (var tmp87))
  4255. (movq (var tmp85) (var tmp90))
  4256. (movq (global-value free_ptr) (var tmp97))
  4257. (movq (var tmp97) (var tmp98))
  4258. (addq (int 16) (var tmp98))
  4259. (movq (global-value fromspace_end) (var tmp99))
  4260. (if (< (var tmp98) (var tmp99))
  4261. ((movq (int 0) (var tmp00)))
  4262. ((movq (reg r15) (reg rdi))
  4263. (movq (int 16) (reg rsi))
  4264. (callq collect)
  4265. (movq (int 0) (var tmp00))))
  4266. (movq (var tmp00) (var tmp92))
  4267. (movq (global-value free_ptr) (var tmp89))
  4268. (addq (int 16) (global-value free_ptr))
  4269. (movq (var tmp89) (reg r11))
  4270. (movq (int 131) (deref r11 0))
  4271. (movq (var tmp89) (reg r11))
  4272. (movq (var tmp90) (deref r11 8))
  4273. (movq (int 0) (var tmp91))
  4274. (movq (var tmp89) (reg r11))
  4275. (movq (deref r11 8) (var tmp01))
  4276. (movq (var tmp01) (reg r11))
  4277. (movq (deref r11 8) (var tmp02))
  4278. (movq (var tmp02) (reg rax)))
  4279. \end{lstlisting}
  4280. \end{minipage}
  4281. \caption{Output of the \code{select-instructions} pass.}
  4282. \label{fig:select-instr-output-gc}
  4283. \end{figure}
  4284. \clearpage
  4285. \subsection{Register Allocation}
  4286. \label{sec:reg-alloc-gc}
  4287. As discussed earlier in this chapter, the garbage collector needs to
  4288. access all the pointers in the root set, that is, all variables that
  4289. are vectors. It will be the responsibility of the register allocator
  4290. to make sure that:
  4291. \begin{enumerate}
  4292. \item the root stack is used for spilling vector-typed variables, and
  4293. \item if a vector-typed variable is live during a call to the
  4294. collector, it must be spilled to ensure it is visible to the
  4295. collector.
  4296. \end{enumerate}
  4297. The later responsibility can be handled during construction of the
  4298. inference graph, by adding interference edges between the call-live
  4299. vector-typed variables and all the callee-save registers. (They
  4300. already interfere with the caller-save registers.) The type
  4301. information for variables is in the \code{program} form, so we
  4302. recommend adding another parameter to the \code{build-interference}
  4303. function to communicate this association list.
  4304. The spilling of vector-typed variables to the root stack can be
  4305. handled after graph coloring, when choosing how to assign the colors
  4306. (integers) to registers and stack locations. The \code{program} output
  4307. of this pass changes to also record the number of spills to the root
  4308. stack.
  4309. \[
  4310. \begin{array}{lcl}
  4311. x86_2 &::= & (\key{program} \;(\itm{stackSpills} \; \itm{rootstackSpills}) \;(\key{type}\;\itm{type})\; \Instr^{+})
  4312. \end{array}
  4313. \]
  4314. % build-interference
  4315. %
  4316. % callq
  4317. % extra parameter for var->type assoc. list
  4318. % update 'program' and 'if'
  4319. % allocate-registers
  4320. % allocate spilled vectors to the rootstack
  4321. % don't change color-graph
  4322. \subsection{Print x86}
  4323. \label{sec:print-x86-gc}
  4324. \marginpar{\scriptsize We need to show the translation to x86 and what
  4325. to do about global-value. \\ --Jeremy}
  4326. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4327. \code{print-x86} pass.
  4328. \begin{figure}[htbp]
  4329. \begin{minipage}[t]{0.5\textwidth}
  4330. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4331. .globl _main
  4332. _main:
  4333. pushq %rbp
  4334. movq %rsp, %rbp
  4335. pushq %r14
  4336. pushq %r13
  4337. pushq %r12
  4338. pushq %rbx
  4339. subq $0, %rsp
  4340. movq $16384, %rdi
  4341. movq $16, %rsi
  4342. callq _initialize
  4343. movq _rootstack_begin(%rip), %r15
  4344. movq _free_ptr(%rip), %rbx
  4345. addq $16, %rbx
  4346. cmpq _fromspace_end(%rip), %rbx
  4347. setl %al
  4348. movzbq %al, %rbx
  4349. cmpq $0, %rbx
  4350. je then30964
  4351. jmp if_end30965
  4352. then30964:
  4353. movq %r15, %rdi
  4354. movq $16, %rsi
  4355. callq _collect
  4356. if_end30965:
  4357. movq _free_ptr(%rip), %rbx
  4358. addq $16, _free_ptr(%rip)
  4359. movq %rbx, %r11
  4360. movq $3, 0(%r11)
  4361. movq %rbx, %r11
  4362. movq $42, 8(%r11)
  4363. movq _free_ptr(%rip), %rcx
  4364. addq $16, %rcx
  4365. cmpq _fromspace_end(%rip), %rcx
  4366. setl %al
  4367. movzbq %al, %rcx
  4368. cmpq $0, %rcx
  4369. je then30966
  4370. jmp if_end30967
  4371. \end{lstlisting}
  4372. \end{minipage}
  4373. \begin{minipage}[t]{0.45\textwidth}
  4374. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4375. then30966:
  4376. movq %rbx, 0(%r15)
  4377. addq $8, %r15
  4378. movq %r15, %rdi
  4379. movq $16, %rsi
  4380. callq _collect
  4381. subq $8, %r15
  4382. movq 0(%r15), %rbx
  4383. if_end30967:
  4384. movq _free_ptr(%rip), %rcx
  4385. addq $16, _free_ptr(%rip)
  4386. movq %rcx, %r11
  4387. movq $131, 0(%r11)
  4388. movq %rcx, %r11
  4389. movq %rbx, 8(%r11)
  4390. movq %rcx, %r11
  4391. movq 8(%r11), %rbx
  4392. movq %rbx, %r11
  4393. movq 8(%r11), %rbx
  4394. movq %rbx, %rax
  4395. movq %rax, %rdi
  4396. callq _print_int
  4397. movq $0, %rax
  4398. addq $0, %rsp
  4399. popq %rbx
  4400. popq %r12
  4401. popq %r13
  4402. popq %r14
  4403. popq %rbp
  4404. retq
  4405. \end{lstlisting}
  4406. \end{minipage}
  4407. \caption{Output of the \code{print-x86} pass.}
  4408. \label{fig:print-x86-output-gc}
  4409. \end{figure}
  4410. \marginpar{\scriptsize Suggest an implementation strategy
  4411. in which the students first do the code gen and test that
  4412. without GC (just use a big heap), then after that is debugged,
  4413. implement the GC. \\ --Jeremy}
  4414. \begin{figure}[p]
  4415. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4416. \node (R1) at (0,2) {\large $R_1$};
  4417. \node (R1-2) at (3,2) {\large $R_1$};
  4418. \node (R1-3) at (6,2) {\large $R_1$};
  4419. \node (C1-1) at (9,0) {\large $C_1$};
  4420. \node (C1-2) at (6,0) {\large $C_1$};
  4421. \node (C1-3) at (3,0) {\large $C_1$};
  4422. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4423. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4424. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4425. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  4426. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  4427. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4428. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4429. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize typecheck} (R1-2);
  4430. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize uniquify} (R1-3);
  4431. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize flatten} (C1-1);
  4432. \path[->,bend left=15] (C1-1) edge [below] node {\ttfamily\footnotesize\color{red} expose-alloc.} (C1-2);
  4433. \path[->,bend left=15] (C1-2) edge [below] node {\ttfamily\footnotesize\color{red} uncover...roots} (C1-3);
  4434. \path[->,bend right=15] (C1-3) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4435. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4436. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4437. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4438. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize lower-cond.} (x86-4);
  4439. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-5);
  4440. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  4441. \end{tikzpicture}
  4442. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4443. \label{fig:R3-passes}
  4444. \end{figure}
  4445. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  4446. for the compilation of $R_3$.
  4447. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4448. \chapter{Functions}
  4449. \label{ch:functions}
  4450. This chapter studies the compilation of functions (aka. procedures) at
  4451. the level of abstraction of the C language. This corresponds to a
  4452. subset of Typed Racket in which only top-level function definitions
  4453. are allowed. This abstraction level is an important stepping stone to
  4454. implementing lexically-scoped functions in the form of \key{lambda}
  4455. abstractions (Chapter~\ref{ch:lambdas}).
  4456. \section{The $R_4$ Language}
  4457. The syntax for function definitions and function application
  4458. (aka. function call) is shown in Figure~\ref{fig:r4-syntax}, where we
  4459. define the $R_4$ language. Programs in $R_4$ start with zero or more
  4460. function definitions. The function names from these definitions are
  4461. in-scope for the entire program, including all other function
  4462. definitions (so the ordering of function definitions does not matter).
  4463. Functions are first-class in the sense that a function pointer is data
  4464. and can be stored in memory or passed as a parameter to another
  4465. function. Thus, we introduce a function type, written
  4466. \begin{lstlisting}
  4467. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4468. \end{lstlisting}
  4469. for a function whose $n$ parameters have the types $\Type_1$ through
  4470. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4471. these functions (with respect to Racket functions) is that they are
  4472. not lexically scoped. That is, the only external entities that can be
  4473. referenced from inside a function body are other globally-defined
  4474. functions. The syntax of $R_4$ prevents functions from being nested
  4475. inside each other; they can only be defined at the top level.
  4476. \begin{figure}[tp]
  4477. \centering
  4478. \fbox{
  4479. \begin{minipage}{0.96\textwidth}
  4480. \[
  4481. \begin{array}{lcl}
  4482. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4483. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4484. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4485. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4486. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4487. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4488. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4489. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4490. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4491. (\key{vector-ref}\;\Exp\;\Int)} \\
  4492. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4493. &\mid& (\Exp \; \Exp^{*}) \\
  4494. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4495. R_4 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4496. \end{array}
  4497. \]
  4498. \end{minipage}
  4499. }
  4500. \caption{Syntax of $R_4$, extending $R_3$ with functions.}
  4501. \label{fig:r4-syntax}
  4502. \end{figure}
  4503. The program in Figure~\ref{fig:r4-function-example} is a
  4504. representative example of defining and using functions in $R_4$. We
  4505. define a function \code{map-vec} that applies some other function
  4506. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  4507. vector containing the results. We also define a function \code{add1}
  4508. that does what its name suggests. The program then applies
  4509. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  4510. \code{(vector 1 42)}, from which we return the \code{42}.
  4511. \begin{figure}[tbp]
  4512. \begin{lstlisting}
  4513. (program
  4514. (define (map-vec [f : (Integer -> Integer)]
  4515. [v : (Vector Integer Integer)])
  4516. : (Vector Integer Integer)
  4517. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  4518. (define (add1 [x : Integer]) : Integer
  4519. (+ x 1))
  4520. (vector-ref (map-vec add1 (vector 0 41)) 1)
  4521. )
  4522. \end{lstlisting}
  4523. \caption{Example of using functions in $R_4$.}
  4524. \label{fig:r4-function-example}
  4525. \end{figure}
  4526. The definitional interpreter for $R_4$ is in
  4527. Figure~\ref{fig:interp-R4}.
  4528. \begin{figure}[tp]
  4529. \begin{lstlisting}
  4530. (define (interp-R4 env)
  4531. (lambda (e)
  4532. (match e
  4533. ....
  4534. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  4535. (cons f `(lambda ,xs ,body))]
  4536. [`(program ,ds ... ,body)
  4537. (let ([top-level (map (interp-R4 '()) ds)])
  4538. ((interp-R4 top-level) body))]
  4539. [`(,fun ,args ...)
  4540. (define arg-vals (map (interp-R4 env) args))
  4541. (define fun-val ((interp-R4 env) fun))
  4542. (match fun-val
  4543. [`(lambda (,xs ...) ,body)
  4544. (define new-env (append (map cons xs arg-vals) env))
  4545. ((interp-R4 new-env) body)]
  4546. [else (error "interp-R4, expected function, not" fun-val)]))]
  4547. [else (error 'interp-R4 "unrecognized expression")]
  4548. )))
  4549. \end{lstlisting}
  4550. \caption{Interpreter for the $R_4$ language.}
  4551. \label{fig:interp-R4}
  4552. \end{figure}
  4553. \section{Functions in x86}
  4554. \label{sec:fun-x86}
  4555. \marginpar{\tiny Make sure callee save registers are discussed
  4556. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  4557. \marginpar{\tiny Talk about the return address on the
  4558. stack and what callq and retq does.\\ --Jeremy }
  4559. The x86 architecture provides a few features to support the
  4560. implementation of functions. We have already seen that x86 provides
  4561. labels so that one can refer to the location of an instruction, as is
  4562. needed for jump instructions. Labels can also be used to mark the
  4563. beginning of the instructions for a function. Going further, we can
  4564. obtain the address of a label by using the \key{leaq} instruction and
  4565. \key{rip}-relative addressing. For example, the following puts the
  4566. address of the \code{add1} label into the \code{rbx} register.
  4567. \begin{lstlisting}
  4568. leaq add1(%rip), %rbx
  4569. \end{lstlisting}
  4570. In Sections~\ref{sec:x86} and \ref{sec:select-s0} we saw the use of
  4571. the \code{callq} instruction for jumping to a function as specified by
  4572. a label. The use of the instruction changes slightly if the function
  4573. is specified by an address in a register, that is, an \emph{indirect
  4574. function call}. The x86 syntax is to give the register name prefixed
  4575. with an asterisk.
  4576. \begin{lstlisting}
  4577. callq *%rbx
  4578. \end{lstlisting}
  4579. The x86 architecture does not directly support passing arguments to
  4580. functions; instead we use a combination of registers and stack
  4581. locations for passing arguments, following the conventions used by
  4582. \code{gcc} as described by \cite{Matz:2013aa}. Up to six arguments may
  4583. be passed in registers, using the registers \code{rdi}, \code{rsi},
  4584. \code{rdx}, \code{rcx}, \code{r8}, and \code{r9}, in that order. If
  4585. there are more than six arguments, then the rest must be placed on the
  4586. stack, which we call \emph{stack arguments}, which we discuss in later
  4587. paragraphs. The register \code{rax} is for the return value of the
  4588. function.
  4589. Recall from Section~\ref{sec:x86} that the stack is also used for
  4590. local variables and for storing the values of callee-save registers
  4591. (we shall refer to all of these collectively as ``locals''), and that
  4592. at the beginning of a function we move the stack pointer \code{rsp}
  4593. down to make room for them.
  4594. %% We recommend storing the local variables
  4595. %% first and then the callee-save registers, so that the local variables
  4596. %% can be accessed using \code{rbp} the same as before the addition of
  4597. %% functions.
  4598. To make additional room for passing arguments, we shall
  4599. move the stack pointer even further down. We count how many stack
  4600. arguments are needed for each function call that occurs inside the
  4601. body of the function and find their maximum. Adding this number to the
  4602. number of locals gives us how much the \code{rsp} should be moved at
  4603. the beginning of the function. In preparation for a function call, we
  4604. offset from \code{rsp} to set up the stack arguments. We put the first
  4605. stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  4606. so on.
  4607. Upon calling the function, the stack arguments are retrieved by the
  4608. callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  4609. is the location of the first stack argument, \code{24(\%rbp)} is the
  4610. address of the second, and so on. Figure~\ref{fig:call-frames} shows
  4611. the layout of the caller and callee frames. Notice how important it is
  4612. that we correctly compute the maximum number of arguments needed for
  4613. function calls; if that number is too small then the arguments and
  4614. local variables will smash into each other!
  4615. As discussed in Section~\ref{sec:print-x86-reg-alloc}, an x86 function
  4616. is responsible for following conventions regarding the use of
  4617. registers: the caller should assume that all the caller save registers
  4618. get overwritten with arbitrary values by the callee. Thus, the caller
  4619. should either 1) not put values that are live across a call in caller
  4620. save registers, or 2) save and restore values that are live across
  4621. calls. We shall recommend option 1). On the flip side, if the callee
  4622. wants to use a callee save register, the callee must arrange to put
  4623. the original value back in the register prior to returning to the
  4624. caller.
  4625. \begin{figure}[tbp]
  4626. \centering
  4627. \begin{tabular}{r|r|l|l} \hline
  4628. Caller View & Callee View & Contents & Frame \\ \hline
  4629. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  4630. 0(\key{\%rbp}) & & old \key{rbp} \\
  4631. -8(\key{\%rbp}) & & local $1$ \\
  4632. \ldots & & \ldots \\
  4633. $-8k$(\key{\%rbp}) & & local $k$ \\
  4634. & & \\
  4635. $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  4636. & \ldots & \ldots \\
  4637. 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\ \hline
  4638. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  4639. & 0(\key{\%rbp}) & old \key{rbp} \\
  4640. & -8(\key{\%rbp}) & local $1$ \\
  4641. & \ldots & \ldots \\
  4642. & $-8m$(\key{\%rsp}) & local $m$\\ \hline
  4643. \end{tabular}
  4644. \caption{Memory layout of caller and callee frames.}
  4645. \label{fig:call-frames}
  4646. \end{figure}
  4647. \section{The compilation of functions}
  4648. \marginpar{\scriptsize To do: discuss the need to push and
  4649. pop call-live pointers (vectors and functions)
  4650. to the root stack \\ --Jeremy}
  4651. Now that we have a good understanding of functions as they appear in
  4652. $R_4$ and the support for functions in x86, we need to plan the
  4653. changes to our compiler, that is, do we need any new passes and/or do
  4654. we need to change any existing passes? Also, do we need to add new
  4655. kinds of AST nodes to any of the intermediate languages?
  4656. \begin{figure}[tp]
  4657. \centering
  4658. \fbox{
  4659. \begin{minipage}{0.96\textwidth}
  4660. \[
  4661. \begin{array}{lcl}
  4662. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4663. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4664. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4665. &\mid& (\key{function-ref}\, \itm{label})
  4666. \mid \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4667. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4668. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4669. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4670. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4671. (\key{vector-ref}\;\Exp\;\Int)} \\
  4672. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4673. &\mid& (\key{app}\, \Exp \; \Exp^{*}) \\
  4674. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4675. F_1 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4676. \end{array}
  4677. \]
  4678. \end{minipage}
  4679. }
  4680. \caption{The $F_1$ language, an extension of $R_3$
  4681. (Figure~\ref{fig:r3-syntax}).}
  4682. \label{fig:f1-syntax}
  4683. \end{figure}
  4684. To begin with, the syntax of $R_4$ is inconvenient for purposes of
  4685. compilation because it conflates the use of function names and local
  4686. variables and it conflates the application of primitive operations and
  4687. the application of functions. This is a problem because we need to
  4688. compile the use of a function name differently than the use of a local
  4689. variable; we need to use \code{leaq} to move the function name to a
  4690. register. Similarly, the application of a function is going to require
  4691. a complex sequence of instructions, unlike the primitive
  4692. operations. Thus, it is a good idea to create a new pass that changes
  4693. function references from just a symbol $f$ to \code{(function-ref
  4694. $f$)} and that changes function application from \code{($e_0$ $e_1$
  4695. $\ldots$ $e_n$)} to the explicitly tagged AST \code{(app $e_0$ $e_1$
  4696. $\ldots$ $e_n$)}. A good name for this pass is
  4697. \code{reveal-functions} and the output language, $F_1$, is defined in
  4698. Figure~\ref{fig:f1-syntax}. Placing this pass after \code{uniquify} is
  4699. a good idea, because it will make sure that there are no local
  4700. variables and functions that share the same name. On the other hand,
  4701. \code{reveal-functions} needs to come before the \code{flatten} pass
  4702. because \code{flatten} will help us compile \code{function-ref}.
  4703. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  4704. \key{flatten}.
  4705. \begin{figure}[tp]
  4706. \fbox{
  4707. \begin{minipage}{0.96\textwidth}
  4708. \[
  4709. \begin{array}{lcl}
  4710. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  4711. \mid (\key{function-ref}\,\itm{label})\\
  4712. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4713. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4714. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4715. &\mid& \gray{ (\key{vector}\, \Arg^{+})
  4716. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  4717. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) } \\
  4718. &\mid& (\key{app} \,\Arg\,\Arg^{*}) \\
  4719. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4720. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4721. &\mid& \gray{ (\key{initialize}\,\itm{int}\,\itm{int}) }\\
  4722. &\mid& \gray{ \IF{(\key{collection-needed?}\,\itm{int})}{\Stmt^{*}}{\Stmt^{*}} } \\
  4723. &\mid& \gray{ (\key{collect} \,\itm{int}) }
  4724. \mid \gray{ (\key{allocate} \,\itm{int}) }\\
  4725. &\mid& \gray{ (\key{call-live-roots}\,(\Var^{*}) \,\Stmt^{*}) } \\
  4726. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Stmt^{+}) \\
  4727. C_3 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;(\key{defines}\,\Def^{*})\;\Stmt^{+})
  4728. \end{array}
  4729. \]
  4730. \end{minipage}
  4731. }
  4732. \caption{The $C_3$ language, extending $C_2$ with functions.}
  4733. \label{fig:c3-syntax}
  4734. \end{figure}
  4735. Because each \code{function-ref} needs to eventually become an
  4736. \code{leaq} instruction, it first needs to become an assignment
  4737. statement so there is a left-hand side in which to put the
  4738. result. This can be handled easily in the \code{flatten} pass by
  4739. categorizing \code{function-ref} as a complex expression. Then, in
  4740. the \code{select-instructions} pass, an assignment of
  4741. \code{function-ref} becomes a \code{leaq} instruction as follows: \\
  4742. \begin{tabular}{lll}
  4743. \begin{minipage}{0.45\textwidth}
  4744. \begin{lstlisting}
  4745. (assign |$\itm{lhs}$| (function-ref |$f$|))
  4746. \end{lstlisting}
  4747. \end{minipage}
  4748. &
  4749. $\Rightarrow$
  4750. &
  4751. \begin{minipage}{0.4\textwidth}
  4752. \begin{lstlisting}
  4753. (leaq (function-ref |$f$|) |$\itm{lhs}$|)
  4754. \end{lstlisting}
  4755. \end{minipage}
  4756. \end{tabular} \\
  4757. %
  4758. The output of select instructions is a program in the x86$_3$
  4759. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  4760. \begin{figure}[tp]
  4761. \fbox{
  4762. \begin{minipage}{0.96\textwidth}
  4763. \[
  4764. \begin{array}{lcl}
  4765. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4766. \mid (\key{deref}\,\itm{register}\,\Int) \mid (\key{byte-reg}\; \itm{register}) } \\
  4767. &\mid& \gray{ (\key{global-value}\; \itm{name}) } \\
  4768. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4769. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  4770. (\key{subq} \; \Arg\; \Arg) \mid
  4771. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  4772. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  4773. (\key{pushq}\;\Arg) \mid
  4774. (\key{popq}\;\Arg) \mid
  4775. (\key{retq}) } \\
  4776. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4777. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4778. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4779. \mid (\key{jmp} \; \itm{label})
  4780. \mid (\key{j}\itm{cc} \; \itm{label})
  4781. \mid (\key{label} \; \itm{label}) } \\
  4782. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{leaq}\;\Arg\;\Arg)\\
  4783. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{int} \;\itm{info}\; \Stmt^{+})\\
  4784. x86_3 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\;
  4785. (\key{defines}\,\Def^{*}) \; \Instr^{+})
  4786. \end{array}
  4787. \]
  4788. \end{minipage}
  4789. }
  4790. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  4791. \label{fig:x86-3}
  4792. \end{figure}
  4793. Next we consider compiling function definitions. The \code{flatten}
  4794. pass should handle function definitions a lot like a \code{program}
  4795. node; after all, the \code{program} node represents the \code{main}
  4796. function. So the \code{flatten} pass, in addition to flattening the
  4797. body of the function into a sequence of statements, should record the
  4798. local variables in the $\Var^{*}$ field as shown below.
  4799. \begin{lstlisting}
  4800. (define (|$f$| [|\itm{xs}| : |\itm{ts}|]|$^{*}$|) : |\itm{rt}| (|$\Var^{*}$|) |$\Stmt^{+}$|)
  4801. \end{lstlisting}
  4802. In the \code{select-instructions} pass, we need to encode the
  4803. parameter passing in terms of the conventions discussed in
  4804. Section~\ref{sec:fun-x86}. So depending on the length of the parameter
  4805. list \itm{xs}, some of them may be in registers and some of them may
  4806. be on the stack. I recommend generating \code{movq} instructions to
  4807. move the parameters from their registers and stack locations into the
  4808. variables \itm{xs}, then let register allocation handle the assignment
  4809. of those variables to homes. After this pass, the \itm{xs} can be
  4810. added to the list of local variables. As mentioned in
  4811. Section~\ref{sec:fun-x86}, we need to find out how far to move the
  4812. stack pointer to ensure we have enough space for stack arguments in
  4813. all the calls inside the body of this function. This pass is a good
  4814. place to do this and store the result in the \itm{maxStack} field of
  4815. the output \code{define} shown below.
  4816. \begin{lstlisting}
  4817. (define (|$f$|) |\itm{numParams}| (|$\Var^{*}$| |\itm{maxStack}|) |$\Instr^{+}$|)
  4818. \end{lstlisting}
  4819. Next, consider the compilation of function applications, which have
  4820. the following form at the start of \code{select-instructions}.
  4821. \begin{lstlisting}
  4822. (assign |\itm{lhs}| (app |\itm{fun}| |\itm{args}| |$\ldots$|))
  4823. \end{lstlisting}
  4824. In the mirror image of handling the parameters of function
  4825. definitions, some of the arguments \itm{args} need to be moved to the
  4826. argument passing registers and the rest should be moved to the
  4827. appropriate stack locations, as discussed in
  4828. Section~\ref{sec:fun-x86}.
  4829. %% You might want to introduce a new kind of AST node for stack
  4830. %% arguments, \code{(stack-arg $i$)} where $i$ is the index of this
  4831. %% argument with respect to the other stack arguments.
  4832. As you're generating the code for parameter passing, take note of how
  4833. many stack arguments are needed for purposes of computing the
  4834. \itm{maxStack} discussed above.
  4835. Once the instructions for parameter passing have been generated, the
  4836. function call itself can be performed with an indirect function call,
  4837. for which I recommend creating the new instruction
  4838. \code{indirect-callq}. Of course, the return value from the function
  4839. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  4840. \begin{lstlisting}
  4841. (indirect-callq |\itm{fun}|)
  4842. (movq (reg rax) |\itm{lhs}|)
  4843. \end{lstlisting}
  4844. The rest of the passes need only minor modifications to handle the new
  4845. kinds of AST nodes: \code{function-ref}, \code{indirect-callq}, and
  4846. \code{leaq}. Inside \code{uncover-live}, when computing the $W$ set
  4847. (written variables) for an \code{indirect-callq} instruction, I
  4848. recommend including all the caller save registers, which will have the
  4849. affect of making sure that no caller save register actually needs to be
  4850. saved. In \code{patch-instructions}, you should deal with the x86
  4851. idiosyncrasy that the destination argument of \code{leaq} must be a
  4852. register.
  4853. For the \code{print-x86} pass, I recommend the following translations:
  4854. \begin{lstlisting}
  4855. (function-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  4856. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  4857. \end{lstlisting}
  4858. For function definitions, the \code{print-x86} pass should add the
  4859. code for saving and restoring the callee save registers, if you
  4860. haven't already done that.
  4861. \section{An Example Translation}
  4862. Figure~\ref{fig:add-fun} shows an example translation of a simple
  4863. function in $R_4$ to x86. The figure includes the results of the
  4864. \code{flatten} and \code{select-instructions} passes. Can you see any
  4865. ways to improve the translation?
  4866. \begin{figure}[tbp]
  4867. \begin{tabular}{lll}
  4868. \begin{minipage}{0.5\textwidth}
  4869. \begin{lstlisting}
  4870. (program
  4871. (define (add [x : Integer]
  4872. [y : Integer])
  4873. : Integer (+ x y))
  4874. (add 40 2))
  4875. \end{lstlisting}
  4876. $\Downarrow$
  4877. \begin{lstlisting}
  4878. (program (t.1 t.2)
  4879. (defines
  4880. (define (add.1 [x.1 : Integer]
  4881. [y.1 : Integer])
  4882. : Integer (t.3)
  4883. (assign t.3 (+ x.1 y.1))
  4884. (return t.3)))
  4885. (assign t.1 (function-ref add.1))
  4886. (assign t.2 (app t.1 40 2))
  4887. (return t.2))
  4888. \end{lstlisting}
  4889. $\Downarrow$
  4890. \begin{lstlisting}
  4891. (program ((rs.1 t.1 t.2) 0)
  4892. (type Integer)
  4893. (defines
  4894. (define (add28545) 3
  4895. ((rs.2 x.2 y.3 t.4) 0)
  4896. (movq (reg rdi) (var rs.2))
  4897. (movq (reg rsi) (var x.2))
  4898. (movq (reg rdx) (var y.3))
  4899. (movq (var x.2) (var t.4))
  4900. (addq (var y.3) (var t.4))
  4901. (movq (var t.4) (reg rax))))
  4902. (movq (int 16384) (reg rdi))
  4903. (movq (int 16) (reg rsi))
  4904. (callq initialize)
  4905. (movq (global-value rootstack_begin)
  4906. (var rs.1))
  4907. (leaq (function-ref add28545) (var t.1))
  4908. (movq (var rs.1) (reg rdi))
  4909. (movq (int 40) (reg rsi))
  4910. (movq (int 2) (reg rdx))
  4911. (indirect-callq (var t.1))
  4912. (movq (reg rax) (var t.2))
  4913. (movq (var t.2) (reg rax)))
  4914. \end{lstlisting}
  4915. \end{minipage}
  4916. &
  4917. \begin{minipage}{0.4\textwidth}
  4918. $\Downarrow$
  4919. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4920. .globl add28545
  4921. add28545:
  4922. pushq %rbp
  4923. movq %rsp, %rbp
  4924. pushq %r15
  4925. pushq %r14
  4926. pushq %r13
  4927. pushq %r12
  4928. pushq %rbx
  4929. subq $8, %rsp
  4930. movq %rdi, %rbx
  4931. movq %rsi, %rbx
  4932. movq %rdx, %rcx
  4933. addq %rcx, %rbx
  4934. movq %rbx, %rax
  4935. addq $8, %rsp
  4936. popq %rbx
  4937. popq %r12
  4938. popq %r13
  4939. popq %r14
  4940. popq %r15
  4941. popq %rbp
  4942. retq
  4943. .globl _main
  4944. _main:
  4945. pushq %rbp
  4946. movq %rsp, %rbp
  4947. pushq %r15
  4948. pushq %r14
  4949. pushq %r13
  4950. pushq %r12
  4951. pushq %rbx
  4952. subq $8, %rsp
  4953. movq $16384, %rdi
  4954. movq $16, %rsi
  4955. callq _initialize
  4956. movq _rootstack_begin(%rip), %rcx
  4957. leaq add28545(%rip), %rbx
  4958. movq %rcx, %rdi
  4959. movq $40, %rsi
  4960. movq $2, %rdx
  4961. callq *%rbx
  4962. movq %rax, %rbx
  4963. movq %rbx, %rax
  4964. movq %rax, %rdi
  4965. callq _print_int
  4966. movq $0, %rax
  4967. addq $8, %rsp
  4968. popq %rbx
  4969. popq %r12
  4970. popq %r13
  4971. popq %r14
  4972. popq %r15
  4973. popq %rbp
  4974. retq
  4975. \end{lstlisting}
  4976. \end{minipage}
  4977. \end{tabular}
  4978. \caption{Example compilation of a simple function to x86.}
  4979. \label{fig:add-fun}
  4980. \end{figure}
  4981. \begin{exercise}\normalfont
  4982. Expand your compiler to handle $R_4$ as outlined in this section.
  4983. Create 5 new programs that use functions, including examples that pass
  4984. functions and return functions from other functions, and test your
  4985. compiler on these new programs and all of your previously created test
  4986. programs.
  4987. \end{exercise}
  4988. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4989. \chapter{Lexically Scoped Functions}
  4990. \label{ch:lambdas}
  4991. This chapter studies lexically scoped functions as they appear in
  4992. functional languages such as Racket. By lexical scoping we mean that a
  4993. function's body may refer to variables whose binding site is outside
  4994. of the function, in an enclosing scope.
  4995. %
  4996. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  4997. anonymous function defined using the \key{lambda} form. The body of
  4998. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  4999. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5000. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5001. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5002. returned from the function \code{f}. Below the definition of \code{f},
  5003. we have two calls to \code{f} with different arguments for \code{x},
  5004. first \code{5} then \code{3}. The functions returned from \code{f} are
  5005. bound to variables \code{g} and \code{h}. Even though these two
  5006. functions were created by the same \code{lambda}, they are really
  5007. different functions because they use different values for
  5008. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5009. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5010. the result of this program is \code{42}.
  5011. \begin{figure}[btp]
  5012. \begin{lstlisting}
  5013. (define (f [x : Integer]) : (Integer -> Integer)
  5014. (let ([y 4])
  5015. (lambda: ([z : Integer]) : Integer
  5016. (+ x (+ y z)))))
  5017. (let ([g (f 5)])
  5018. (let ([h (f 3)])
  5019. (+ (g 11) (h 15))))
  5020. \end{lstlisting}
  5021. \caption{Example of a lexically scoped function.}
  5022. \label{fig:lexical-scoping}
  5023. \end{figure}
  5024. \section{The $R_5$ Language}
  5025. The syntax for this language with anonymous functions and lexical
  5026. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5027. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5028. for function application. In this chapter we shall descibe how to
  5029. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5030. into a combination of functions (as in $R_4$) and tuples (as in
  5031. $R_3$).
  5032. \begin{figure}[tp]
  5033. \centering
  5034. \fbox{
  5035. \begin{minipage}{0.96\textwidth}
  5036. \[
  5037. \begin{array}{lcl}
  5038. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5039. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5040. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5041. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5042. \mid (\key{+} \; \Exp\;\Exp)} \\
  5043. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}
  5044. \mid \key{\#t} \mid \key{\#f} \mid
  5045. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5046. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5047. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5048. (\key{vector-ref}\;\Exp\;\Int)} \\
  5049. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5050. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5051. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5052. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5053. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5054. \end{array}
  5055. \]
  5056. \end{minipage}
  5057. }
  5058. \caption{Syntax of $R_5$, extending $R_4$ with \key{lambda}.}
  5059. \label{fig:r5-syntax}
  5060. \end{figure}
  5061. We shall describe how to compile $R_5$ to $R_4$, replacing anonymous
  5062. functions with top-level function definitions. However, our compiler
  5063. must provide special treatment to variable occurences such as \code{x}
  5064. and \code{y} in the body of the \code{lambda} of
  5065. Figure~\ref{fig:lexical-scoping}, for the functions of $R_4$ may not
  5066. refer to variables defined outside the function. To identify such
  5067. variable occurences, we review the standard notion of free variable.
  5068. \begin{definition}
  5069. A variable is \emph{free with respect to an expression} $e$ if the
  5070. variable occurs inside $e$ but does not have an enclosing binding in
  5071. $e$.
  5072. \end{definition}
  5073. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5074. free with respect to the expression \code{(+ x (+ y z))}. On the
  5075. other hand, only \code{x} and \code{y} are free with respect to the
  5076. following expression becuase \code{z} is bound by the \code{lambda}.
  5077. \begin{lstlisting}
  5078. (lambda: ([z : Integer]) : Integer
  5079. (+ x (+ y z)))
  5080. \end{lstlisting}
  5081. Once we have identified the free variables of a \code{lambda}, we need
  5082. to arrange for some way to transport, at runtime, the values of those
  5083. variables from the point where the \code{lambda} was created to the
  5084. point where the \code{lambda} is applied. Referring again to
  5085. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5086. needs to be used in the application of \code{g} to \code{11}, but the
  5087. binding of \code{x} to \code{3} needs to be used in the application of
  5088. \code{h} to \code{15}. The solution is to bundle the values of the
  5089. free variables together with the function pointer for the lambda's
  5090. code into a data structure called a \emph{closure}. Fortunately, we
  5091. already have the appropriate ingredients to make closures,
  5092. Chapter~\ref{ch:tuples} gave us tuples and Chapter~\ref{ch:functions}
  5093. gave us function pointers. The function pointer shall reside at index
  5094. $0$ and the values for free variables will fill in the rest of the
  5095. tuple. Figure~\ref{fig:closures} depicts the two closures created by
  5096. the two calls to \code{f} in Figure~\ref{fig:lexical-scoping}.
  5097. Because the two closures came from the same \key{lambda}, they share
  5098. the same code but differ in the values for free variable \code{x}.
  5099. \begin{figure}[tbp]
  5100. \centering \includegraphics[width=0.6\textwidth]{closures}
  5101. \caption{Example closure representation for the \key{lambda}'s
  5102. in Figure~\ref{fig:lexical-scoping}.}
  5103. \label{fig:closures}
  5104. \end{figure}
  5105. \section{Interpreting $R_5$}
  5106. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5107. $R_5$. There are several things to worth noting. First, and most
  5108. importantly, the match clause for \key{lambda} saves the current
  5109. environment inside the returned \key{lambda}. Then the clause for
  5110. \key{app} uses the environment from the \key{lambda}, the
  5111. \code{lam-env}, when interpreting the body of the \key{lambda}. Of
  5112. course, the \code{lam-env} environment is extending with the mapping
  5113. parameters to argument values. To enable mutual recursion and allow a
  5114. unified handling of functions created with \key{lambda} and with
  5115. \key{define}, the match clause for \key{program} includes a second
  5116. pass over the top-level functions to set their environments to be the
  5117. top-level environment.
  5118. \begin{figure}[tbp]
  5119. \begin{lstlisting}
  5120. (define (interp-R5 env)
  5121. (lambda (ast)
  5122. (match ast
  5123. ...
  5124. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5125. `(lambda ,xs ,body ,env)]
  5126. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5127. (mcons f `(lambda ,xs ,body))]
  5128. [`(program ,defs ... ,body)
  5129. (let ([top-level (map (interp-R5 '()) defs)])
  5130. (for/list ([b top-level])
  5131. (set-mcdr! b (match (mcdr b)
  5132. [`(lambda ,xs ,body)
  5133. `(lambda ,xs ,body ,top-level)])))
  5134. ((interp-R5 top-level) body))]
  5135. [`(,fun ,args ...)
  5136. (define arg-vals (map (interp-R5 env) args))
  5137. (define fun-val ((interp-R5 env) fun))
  5138. (match fun-val
  5139. [`(lambda (,xs ...) ,body ,lam-env)
  5140. (define new-env (append (map cons xs arg-vals) lam-env))
  5141. ((interp-R5 new-env) body)]
  5142. [else (error "interp-R5, expected function, not" fun-val)])]
  5143. )))
  5144. \end{lstlisting}
  5145. \caption{Interpreter for $R_5$.}
  5146. \label{fig:interp-R5}
  5147. \end{figure}
  5148. \section{Type Checking $R_5$}
  5149. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5150. \key{lambda} form. The body of the \key{lambda} is checked in an
  5151. environment that includes the current environment (because it is
  5152. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5153. require the body's type to match the declared return type.
  5154. \begin{figure}[tbp]
  5155. \begin{lstlisting}
  5156. (define (typecheck-R5 env)
  5157. (lambda (e)
  5158. (match e
  5159. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5160. (define new-env (append (map cons xs Ts) env))
  5161. (define bodyT ((typecheck-R5 new-env) body))
  5162. (cond [(equal? rT bodyT)
  5163. `(,@Ts -> ,rT)]
  5164. [else
  5165. (error "mismatch in return type" bodyT rT)])]
  5166. ...
  5167. )))
  5168. \end{lstlisting}
  5169. \caption{Type checking the \key{lambda}'s in $R_5$.}
  5170. \label{fig:typecheck-R5}
  5171. \end{figure}
  5172. \section{Closure Conversion}
  5173. The compiling of lexically-scoped functions into C-style functions is
  5174. accomplished in the pass \code{convert-to-closures} that comes after
  5175. \code{reveal-functions} and before flatten. This pass needs to treat
  5176. regular function calls differently from applying primitive operators,
  5177. and \code{reveal-functions} differentiates those two cases for us.
  5178. As usual, we shall implement the pass as a recursive function over the
  5179. AST. All of the action is in the clauses for \key{lambda} and
  5180. \key{app} (function application). We transform a \key{lambda}
  5181. expression into an expression that creates a closure, that is, creates
  5182. a vector whose first element is a function pointer and the rest of the
  5183. elements are the free variables of the \key{lambda}. The \itm{name}
  5184. is a unique symbol generated to identify the function.
  5185. \begin{tabular}{lll}
  5186. \begin{minipage}{0.4\textwidth}
  5187. \begin{lstlisting}
  5188. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  5189. \end{lstlisting}
  5190. \end{minipage}
  5191. &
  5192. $\Rightarrow$
  5193. &
  5194. \begin{minipage}{0.4\textwidth}
  5195. \begin{lstlisting}
  5196. (vector |\itm{name}| |\itm{fvs}| ...)
  5197. \end{lstlisting}
  5198. \end{minipage}
  5199. \end{tabular} \\
  5200. %
  5201. In addition to transforming each \key{lambda} into a \key{vector}, we
  5202. must create a top-level function definition for each \key{lambda}, as
  5203. shown below.
  5204. \begin{lstlisting}
  5205. (define (|\itm{name}| [clos : _] |\itm{ps}| ...)
  5206. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  5207. ...
  5208. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  5209. |\itm{body'}|)...))
  5210. \end{lstlisting}
  5211. The \code{clos} parameter refers to the closure whereas $\itm{ps}$ are
  5212. the normal parameters of the \key{lambda}. The sequence of \key{let}
  5213. forms being the free variables to their values obtained from the
  5214. closure.
  5215. We transform function application into code that retreives the
  5216. function pointer from the closure and then calls the function, passing
  5217. in the closure as the first argument. We bind $e'$ to a temporary
  5218. variable to avoid code duplication.
  5219. \begin{tabular}{lll}
  5220. \begin{minipage}{0.3\textwidth}
  5221. \begin{lstlisting}
  5222. (app |$e$| |\itm{es}| ...)
  5223. \end{lstlisting}
  5224. \end{minipage}
  5225. &
  5226. $\Rightarrow$
  5227. &
  5228. \begin{minipage}{0.5\textwidth}
  5229. \begin{lstlisting}
  5230. (let ([|\itm{tmp}| |$e'$|])
  5231. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  5232. \end{lstlisting}
  5233. \end{minipage}
  5234. \end{tabular} \\
  5235. There is also the question of what to do with top-level function
  5236. definitions. To maintain a uniform translation of function
  5237. application, we turn function references into closures.
  5238. \begin{tabular}{lll}
  5239. \begin{minipage}{0.3\textwidth}
  5240. \begin{lstlisting}
  5241. (function-ref |$f$|)
  5242. \end{lstlisting}
  5243. \end{minipage}
  5244. &
  5245. $\Rightarrow$
  5246. &
  5247. \begin{minipage}{0.5\textwidth}
  5248. \begin{lstlisting}
  5249. (vector (function-ref |$f$|))
  5250. \end{lstlisting}
  5251. \end{minipage}
  5252. \end{tabular} \\
  5253. %
  5254. The top-level function definitions need to be updated as well to take
  5255. an extra closure parameter.
  5256. \section{An Example Translation}
  5257. \label{sec:example-lambda}
  5258. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  5259. conversion for the example program demonstrating lexical scoping that
  5260. we discussed at the beginning of this chapter.
  5261. \begin{figure}[h]
  5262. \begin{minipage}{0.8\textwidth}
  5263. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5264. (program
  5265. (define (f [x : Integer]) : (Integer -> Integer)
  5266. (let ([y 4])
  5267. (lambda: ([z : Integer]) : Integer
  5268. (+ x (+ y z)))))
  5269. (let ([g (f 5)])
  5270. (let ([h (f 3)])
  5271. (+ (g 11) (h 15)))))
  5272. \end{lstlisting}
  5273. $\Downarrow$
  5274. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5275. (program (type Integer)
  5276. (define (f (x : Integer)) : (Integer -> Integer)
  5277. (let ((y 4))
  5278. (lambda: ((z : Integer)) : Integer
  5279. (+ x (+ y z)))))
  5280. (let ((g (app (function-ref f) 5)))
  5281. (let ((h (app (function-ref f) 3)))
  5282. (+ (app g 11) (app h 15)))))
  5283. \end{lstlisting}
  5284. $\Downarrow$
  5285. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5286. (program (type Integer)
  5287. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  5288. (let ((y 4))
  5289. (vector (function-ref lam.1) x y)))
  5290. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  5291. (let ((x (vector-ref clos.2 1)))
  5292. (let ((y (vector-ref clos.2 2)))
  5293. (+ x (+ y z)))))
  5294. (let ((g (let ((t.1 (vector (function-ref f))))
  5295. (app (vector-ref t.1 0) t.1 5))))
  5296. (let ((h (let ((t.2 (vector (function-ref f))))
  5297. (app (vector-ref t.2 0) t.2 3))))
  5298. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  5299. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  5300. \end{lstlisting}
  5301. \end{minipage}
  5302. \caption{Example of closure conversion.}
  5303. \label{fig:lexical-functions-example}
  5304. \end{figure}
  5305. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5306. \chapter{Dynamic Typing}
  5307. \label{ch:type-dynamic}
  5308. In this chapter we discuss the compilation of a dynamically typed
  5309. language, named $R_7$, that is a subset of the Racket language. (In
  5310. the previous chapters we have studied subsets of the \emph{Typed}
  5311. Racket language.) In dynamically typed languages, an expression may
  5312. produce values of differing type. Consider the following example with
  5313. a conditional expression that may return a Boolean or an integer
  5314. depending on the input to the program.
  5315. \begin{lstlisting}
  5316. (not (if (eq? (read) 1) #f 0))
  5317. \end{lstlisting}
  5318. Languages that allow expressions to produce different kinds of values
  5319. are called \emph{polymorphic}, and there are many kinds of
  5320. polymorphism, such as subtype polymorphism~\citep{Cardelli:1985kx} and
  5321. parametric polymorphism (Chapter~\ref{ch:parametric-polymorphism}).
  5322. Another characteristic of dynamically typed languages is that
  5323. primitive operations, such as \code{not}, are often defined to operate
  5324. on many different types of values. In fact, in Racket, the \code{not}
  5325. operator produces a result for any kind of value: given \code{\#f} it
  5326. returns \code{\#t} and given anything else it returns \code{\#f}.
  5327. Furthermore, even when primitive operations restrict their inputs to
  5328. values of a certain type, this restriction is enforced at runtime
  5329. instead of during compilation. For example, the following vector
  5330. reference results in a run-time contract violation.
  5331. \begin{lstlisting}
  5332. (vector-ref (vector 42) #t)
  5333. \end{lstlisting}
  5334. Let us consider how we might compile untyped Racket to x86, thinking
  5335. about the first example above. Our bit-level representation of the
  5336. Boolean \code{\#f} is zero and similarly for the integer \code{0}.
  5337. However, \code{(not \#f)} should produce \code{\#t} whereas \code{(not
  5338. 0)} should produce \code{\#f}. Furthermore, the behavior of
  5339. \code{not}, in general, cannot be determined at compile time, but
  5340. depends on the runtime type of its input, as in the example above that
  5341. depends on the result of \code{(read)}.
  5342. The way around this problem is to include information about a value's
  5343. runtime type in the value itself, so that this information can be
  5344. inspected by operators such as \code{not}. In particular, we shall
  5345. steal the 3 right-most bits from our 64-bit values to encode the
  5346. runtime type. We shall use $001$ to identify integers, $100$ for
  5347. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  5348. void value. We shall refer to these 3 bits as the \emph{tag} and we
  5349. define the following auxilliary function.
  5350. \begin{align*}
  5351. \itm{tagof}(\key{Integer}) &= 001 \\
  5352. \itm{tagof}(\key{Boolean}) &= 100 \\
  5353. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  5354. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  5355. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  5356. \itm{tagof}(\key{Void}) &= 101
  5357. \end{align*}
  5358. (We shall say more about the new \key{Vectorof} type shortly.)
  5359. This stealing of 3 bits comes at some
  5360. price: our integers are reduced to ranging from $-2^{60}$ to
  5361. $2^{60}$. The stealing does not adversely affect vectors and
  5362. procedures because those values are addresses, and our addresses are
  5363. 8-byte aligned so the rightmost 3 bits are unused, they are always
  5364. $000$. Thus, we do not lose information by overwriting the rightmost 3
  5365. bits with the tag and we can simply zero-out the tag to recover the
  5366. original address.
  5367. In some sense, these tagged values are a new kind of value. Indeed,
  5368. we can extend our \emph{typed} language with tagged values by adding a
  5369. new type to classify them, called \key{Any}, and with operations for
  5370. creating and using tagged values, creating the $R_6$ language defined
  5371. in Section~\ref{sec:r6-lang}. Thus, $R_6$ provides the fundamental
  5372. support for polymorphism and runtime types that we need to support
  5373. dynamic typing.
  5374. We shall implement our untyped language $R_7$ by compiling it to
  5375. $R_6$. We define $R_7$ in Section~\ref{sec:r7-lang} and describe the
  5376. compilation of $R_6$ and $R_7$ in the remainder of this chapter.
  5377. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  5378. \label{sec:r6-lang}
  5379. \begin{figure}[tp]
  5380. \centering
  5381. \fbox{
  5382. \begin{minipage}{0.97\textwidth}
  5383. \[
  5384. \begin{array}{lcl}
  5385. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5386. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  5387. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  5388. \FType &::=& \key{Integer} \mid \key{Boolean} \mid (\key{Vectorof}\;\key{Any})
  5389. \mid (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  5390. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5391. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5392. \mid (\key{+} \; \Exp\;\Exp)} \\
  5393. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  5394. &\mid& \gray{\key{\#t} \mid \key{\#f} \mid
  5395. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5396. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5397. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5398. (\key{vector-ref}\;\Exp\;\Int)} \\
  5399. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5400. &\mid& \gray{(\Exp \; \Exp^{*})
  5401. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5402. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  5403. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  5404. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  5405. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5406. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5407. \end{array}
  5408. \]
  5409. \end{minipage}
  5410. }
  5411. \caption{Syntax of $R_6$, extending $R_5$ with \key{Any}.}
  5412. \label{fig:r6-syntax}
  5413. \end{figure}
  5414. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  5415. $(\key{inject}\; e\; T)$ form converts the value produced by
  5416. expression $e$ of type $T$ into a tagged value. The
  5417. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  5418. expression $e$ into a value of type $T$ or else halts the program if
  5419. the type tag does not match $T$. Note that in both \key{inject} and
  5420. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  5421. which simplifies the implementation and corresponds with what is
  5422. needed for compiling untyped Racket. The type predicates,
  5423. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  5424. if the tag corresponds to the predicate, and return \key{\#t}
  5425. otherwise.
  5426. %
  5427. The type checker for $R_6$ is given in Figure~\ref{fig:typecheck-R6}.
  5428. \begin{figure}[tbp]
  5429. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5430. (define type-predicates
  5431. (set 'boolean? 'integer? 'vector? 'procedure?))
  5432. (define (typecheck-R6 env)
  5433. (lambda (e)
  5434. (define recur (typecheck-R6 env))
  5435. (match e
  5436. [`(inject ,(app recur new-e e-ty) ,ty)
  5437. (cond
  5438. [(equal? e-ty ty)
  5439. (values `(inject ,new-e ,ty) 'Any)]
  5440. [else
  5441. (error "inject expected ~a to have type ~a" e ty)])]
  5442. [`(project ,(app recur new-e e-ty) ,ty)
  5443. (cond
  5444. [(equal? e-ty 'Any)
  5445. (values `(project ,new-e ,ty) ty)]
  5446. [else
  5447. (error "project expected ~a to have type Any" e)])]
  5448. [`(,pred ,e) #:when (set-member? type-predicates pred)
  5449. (define-values (new-e e-ty) (recur e))
  5450. (cond
  5451. [(equal? e-ty 'Any)
  5452. (values `(,pred ,new-e) 'Boolean)]
  5453. [else
  5454. (error "predicate expected arg of type Any, not" e-ty)])]
  5455. [`(vector-ref ,(app recur e t) ,i)
  5456. (match t
  5457. [`(Vector ,ts ...) ...]
  5458. [`(Vectorof ,t)
  5459. (unless (exact-nonnegative-integer? i)
  5460. (error 'type-check "invalid index ~a" i))
  5461. (values `(vector-ref ,e ,i) t)]
  5462. [else (error "expected a vector in vector-ref, not" t)])]
  5463. [`(vector-set! ,(app recur e-vec^ t-vec) ,i
  5464. ,(app recur e-arg^ t-arg))
  5465. (match t-vec
  5466. [`(Vector ,ts ...) ...]
  5467. [`(Vectorof ,t)
  5468. (unless (exact-nonnegative-integer? i)
  5469. (error 'type-check "invalid index ~a" i))
  5470. (unless (equal? t t-arg)
  5471. (error 'type-check "type mismatch in vector-set! ~a ~a"
  5472. t t-arg))
  5473. (values `(vector-set! ,e-vec^
  5474. ,i
  5475. ,e-arg^) 'Void)]
  5476. [else (error 'type-check
  5477. "expected a vector in vector-set!, not ~a"
  5478. t-vec)])]
  5479. ...
  5480. )))
  5481. \end{lstlisting}
  5482. \caption{Type checker for the $R_6$ language.}
  5483. \label{fig:typecheck-R6}
  5484. \end{figure}
  5485. % to do: add rules for vector-ref, etc. for Vectorof
  5486. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  5487. Figure~\ref{fig:interp-R6} shows the definitional interpreter
  5488. for $R_6$.
  5489. \begin{figure}[tbp]
  5490. \begin{lstlisting}
  5491. (define primitives (set 'boolean? ...))
  5492. (define (interp-op op)
  5493. (match op
  5494. ['boolean? (lambda (v)
  5495. (match v
  5496. [`(tagged ,v1 Boolean) #t]
  5497. [else #f]))]
  5498. ...))
  5499. (define (interp-R6 env)
  5500. (lambda (ast)
  5501. (match ast
  5502. [`(inject ,e ,t)
  5503. `(tagged ,((interp-R6 env) e) ,t)]
  5504. [`(project ,e ,t2)
  5505. (define v ((interp-R6 env) e))
  5506. (match v
  5507. [`(tagged ,v1 ,t1)
  5508. (cond [(equal? t1 t2)
  5509. v1]
  5510. [else
  5511. (error "in project, type mismatch" t1 t2)])]
  5512. [else
  5513. (error "in project, expected tagged value" v)])]
  5514. ...)))
  5515. \end{lstlisting}
  5516. \caption{Interpreter for $R_6$.}
  5517. \label{fig:interp-R6}
  5518. \end{figure}
  5519. \section{The $R_7$ Language: Untyped Racket}
  5520. \label{sec:r7-lang}
  5521. \begin{figure}[tp]
  5522. \centering
  5523. \fbox{
  5524. \begin{minipage}{0.97\textwidth}
  5525. \[
  5526. \begin{array}{rcl}
  5527. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5528. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  5529. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  5530. &\mid& \key{\#t} \mid \key{\#f} \mid
  5531. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  5532. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  5533. &\mid& (\key{vector}\;\Exp^{+}) \mid
  5534. (\key{vector-ref}\;\Exp\;\Exp) \\
  5535. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  5536. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  5537. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  5538. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  5539. \end{array}
  5540. \]
  5541. \end{minipage}
  5542. }
  5543. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  5544. \label{fig:r7-syntax}
  5545. \end{figure}
  5546. The syntax of $R_7$, our subset of Racket, is defined in
  5547. Figure~\ref{fig:r7-syntax}.
  5548. %
  5549. The definitional interpreter for $R_7$ is given in
  5550. Figure~\ref{fig:interp-R7}.
  5551. \begin{figure}[tbp]
  5552. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5553. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  5554. (define (valid-op? op) (member op '(+ - and or not)))
  5555. (define (interp-r7 env)
  5556. (lambda (ast)
  5557. (define recur (interp-r7 env))
  5558. (match ast
  5559. [(? symbol?) (lookup ast env)]
  5560. [(? integer?) `(inject ,ast Integer)]
  5561. [#t `(inject #t Boolean)]
  5562. [#f `(inject #f Boolean)]
  5563. [`(read) `(inject ,(read-fixnum) Integer)]
  5564. [`(lambda (,xs ...) ,body)
  5565. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  5566. [`(define (,f ,xs ...) ,body)
  5567. (mcons f `(lambda ,xs ,body))]
  5568. [`(program ,ds ... ,body)
  5569. (let ([top-level (map (interp-r7 '()) ds)])
  5570. (for/list ([b top-level])
  5571. (set-mcdr! b (match (mcdr b)
  5572. [`(lambda ,xs ,body)
  5573. `(inject (lambda ,xs ,body ,top-level)
  5574. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  5575. ((interp-r7 top-level) body))]
  5576. [`(vector ,(app recur elts) ...)
  5577. (define tys (map get-tagged-type elts))
  5578. `(inject ,(apply vector elts) (Vector ,@tys))]
  5579. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  5580. (match v1
  5581. [`(inject ,vec ,ty)
  5582. (vector-set! vec n v2)
  5583. `(inject (void) Void)])]
  5584. [`(vector-ref ,(app recur v) ,n)
  5585. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  5586. [`(let ([,x ,(app recur v)]) ,body)
  5587. ((interp-r7 (cons (cons x v) env)) body)]
  5588. [`(,op ,es ...) #:when (valid-op? op)
  5589. (interp-r7-op op (map recur es))]
  5590. [`(eq? ,(app recur l) ,(app recur r))
  5591. `(inject ,(equal? l r) Boolean)]
  5592. [`(if ,(app recur q) ,t ,f)
  5593. (match q
  5594. [`(inject #f Boolean) (recur f)]
  5595. [else (recur t)])]
  5596. [`(,(app recur f-val) ,(app recur vs) ...)
  5597. (match f-val
  5598. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  5599. (define new-env (append (map cons xs vs) lam-env))
  5600. ((interp-r7 new-env) body)]
  5601. [else (error "interp-r7, expected function, not" f-val)])])))
  5602. \end{lstlisting}
  5603. \caption{Interpreter for the $R_7$ language.}
  5604. \label{fig:interp-R7}
  5605. \end{figure}
  5606. \section{Compiling $R_6$}
  5607. \label{sec:compile-r6}
  5608. Most of the compiler passes only require straightforward changes. The
  5609. interesting part is in instruction selection.
  5610. \paragraph{Inject}
  5611. We recommend compiling an \key{inject} as follows if the type is
  5612. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  5613. destination to the left by the number of bits specified by the source
  5614. ($2$) and it preserves the sign of the integer. We use the \key{orq}
  5615. instruction to combine the tag and the value to form the tagged value.
  5616. \\
  5617. \begin{tabular}{lll}
  5618. \begin{minipage}{0.4\textwidth}
  5619. \begin{lstlisting}
  5620. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5621. \end{lstlisting}
  5622. \end{minipage}
  5623. &
  5624. $\Rightarrow$
  5625. &
  5626. \begin{minipage}{0.5\textwidth}
  5627. \begin{lstlisting}
  5628. (movq |$e'$| |\itm{lhs}'|)
  5629. (salq (int 2) |\itm{lhs}'|)
  5630. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5631. \end{lstlisting}
  5632. \end{minipage}
  5633. \end{tabular} \\
  5634. The instruction selection for vectors and procedures is different
  5635. because their is no need to shift them to the left. The rightmost 3
  5636. bits are already zeros as described above. So we combine the value and
  5637. the tag using
  5638. \key{orq}. \\
  5639. \begin{tabular}{lll}
  5640. \begin{minipage}{0.4\textwidth}
  5641. \begin{lstlisting}
  5642. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5643. \end{lstlisting}
  5644. \end{minipage}
  5645. &
  5646. $\Rightarrow$
  5647. &
  5648. \begin{minipage}{0.5\textwidth}
  5649. \begin{lstlisting}
  5650. (movq |$e'$| |\itm{lhs}'|)
  5651. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5652. \end{lstlisting}
  5653. \end{minipage}
  5654. \end{tabular} \\
  5655. \paragraph{Project}
  5656. The instruction selection for \key{project} is a bit more involved.
  5657. Like \key{inject}, the instructions are different depending on whether
  5658. the type $T$ is a pointer (vector or procedure) or not (Integer or
  5659. Boolean). The following shows the instruction selection for Integer
  5660. and Boolean. We first check to see if the tag on the tagged value
  5661. matches the tag of the target type $T$. If not, we halt the program by
  5662. calling the \code{exit} function. If we have a match, we need to
  5663. produce an untagged value by shifting it to the right by 2 bits.
  5664. %
  5665. \\
  5666. \begin{tabular}{lll}
  5667. \begin{minipage}{0.4\textwidth}
  5668. \begin{lstlisting}
  5669. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5670. \end{lstlisting}
  5671. \end{minipage}
  5672. &
  5673. $\Rightarrow$
  5674. &
  5675. \begin{minipage}{0.5\textwidth}
  5676. \begin{lstlisting}
  5677. (movq |$e'$| |\itm{lhs}'|)
  5678. (andq (int 3) |\itm{lhs}'|)
  5679. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5680. ((movq |$e'$| |\itm{lhs}'|)
  5681. (sarq (int 2) |\itm{lhs}'|))
  5682. ((callq exit)))
  5683. \end{lstlisting}
  5684. \end{minipage}
  5685. \end{tabular} \\
  5686. %
  5687. The case for vectors and procedures begins in a similar way, checking
  5688. that the runtime tag matches the target type $T$ and exiting if there
  5689. is a mismatch. However, the way in which we convert the tagged value
  5690. to a value is different, as there is no need to shift. Instead we need
  5691. to zero-out the rightmost 2 bits. We accomplish this by creating the
  5692. bit pattern $\ldots 0011$, applying \code{notq} to obtain $\ldots
  5693. 1100$, and then applying \code{andq} with the tagged value get the
  5694. desired result. \\
  5695. %
  5696. \begin{tabular}{lll}
  5697. \begin{minipage}{0.4\textwidth}
  5698. \begin{lstlisting}
  5699. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5700. \end{lstlisting}
  5701. \end{minipage}
  5702. &
  5703. $\Rightarrow$
  5704. &
  5705. \begin{minipage}{0.5\textwidth}
  5706. \begin{lstlisting}
  5707. (movq |$e'$| |\itm{lhs}'|)
  5708. (andq (int 3) |\itm{lhs}'|)
  5709. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5710. ((movq (int 3) |\itm{lhs}'|)
  5711. (notq |\itm{lhs}'|)
  5712. (andq |$e'$| |\itm{lhs}'|))
  5713. ((callq exit)))
  5714. \end{lstlisting}
  5715. \end{minipage}
  5716. \end{tabular} \\
  5717. \paragraph{Type Predicates} We leave it to the reader to
  5718. devise a sequence of instructions to implement the type predicates
  5719. \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  5720. \section{Compiling $R_7$ to $R_6$}
  5721. \label{sec:compile-r7}
  5722. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  5723. $R_7$ forms into $R_6$. An important invariant of this pass is that
  5724. given a subexpression $e$ of $R_7$, the pass will produce an
  5725. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  5726. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  5727. the Boolean \code{\#t}, which must be injected to produce an
  5728. expression of type \key{Any}.
  5729. %
  5730. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  5731. addition, is representative of compilation for many operations: the
  5732. arguments have type \key{Any} and must be projected to \key{Integer}
  5733. before the addition can be performed.
  5734. %
  5735. The compilation of \key{lambda} (third row of
  5736. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  5737. produce type annotations, we simply use \key{Any}.
  5738. %
  5739. The compilation of \code{if}, \code{eq?}, and \code{and} all
  5740. demonstrate how this pass has to account for some differences in
  5741. behavior between $R_7$ and $R_6$. The $R_7$ language is more
  5742. permissive than $R_6$ regarding what kind of values can be used in
  5743. various places. For example, the condition of an \key{if} does not
  5744. have to be a Boolean. Similarly, the arguments of \key{and} do not
  5745. need to be Boolean. For \key{eq?}, the arguments need not be of the
  5746. same type.
  5747. \begin{figure}[tbp]
  5748. \centering
  5749. \begin{tabular}{|lll|} \hline
  5750. \begin{minipage}{0.25\textwidth}
  5751. \begin{lstlisting}
  5752. #t
  5753. \end{lstlisting}
  5754. \end{minipage}
  5755. &
  5756. $\Rightarrow$
  5757. &
  5758. \begin{minipage}{0.6\textwidth}
  5759. \begin{lstlisting}
  5760. (inject #t Boolean)
  5761. \end{lstlisting}
  5762. \end{minipage}
  5763. \\[2ex]\hline
  5764. \begin{minipage}{0.25\textwidth}
  5765. \begin{lstlisting}
  5766. (+ |$e_1$| |$e_2$|)
  5767. \end{lstlisting}
  5768. \end{minipage}
  5769. &
  5770. $\Rightarrow$
  5771. &
  5772. \begin{minipage}{0.6\textwidth}
  5773. \begin{lstlisting}
  5774. (inject
  5775. (+ (project |$e'_1$| Integer)
  5776. (project |$e'_2$| Integer))
  5777. Integer)
  5778. \end{lstlisting}
  5779. \end{minipage}
  5780. \\[2ex]\hline
  5781. \begin{minipage}{0.25\textwidth}
  5782. \begin{lstlisting}
  5783. (lambda (|$x_1 \ldots$|) |$e$|)
  5784. \end{lstlisting}
  5785. \end{minipage}
  5786. &
  5787. $\Rightarrow$
  5788. &
  5789. \begin{minipage}{0.6\textwidth}
  5790. \begin{lstlisting}
  5791. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  5792. (Any|$\ldots$|Any -> Any))
  5793. \end{lstlisting}
  5794. \end{minipage}
  5795. \\[2ex]\hline
  5796. \begin{minipage}{0.25\textwidth}
  5797. \begin{lstlisting}
  5798. (app |$e_0$| |$e_1 \ldots e_n$|)
  5799. \end{lstlisting}
  5800. \end{minipage}
  5801. &
  5802. $\Rightarrow$
  5803. &
  5804. \begin{minipage}{0.6\textwidth}
  5805. \begin{lstlisting}
  5806. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  5807. |$e'_1 \ldots e'_n$|)
  5808. \end{lstlisting}
  5809. \end{minipage}
  5810. \\[2ex]\hline
  5811. \begin{minipage}{0.25\textwidth}
  5812. \begin{lstlisting}
  5813. (vector-ref |$e_1$| |$e_2$|)
  5814. \end{lstlisting}
  5815. \end{minipage}
  5816. &
  5817. $\Rightarrow$
  5818. &
  5819. \begin{minipage}{0.6\textwidth}
  5820. \begin{lstlisting}
  5821. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  5822. (let ([tmp2 (project |$e'_2$| Integer)])
  5823. (vector-ref tmp1 tmp2)))
  5824. \end{lstlisting}
  5825. \end{minipage}
  5826. \\[2ex]\hline
  5827. \begin{minipage}{0.25\textwidth}
  5828. \begin{lstlisting}
  5829. (if |$e_1$| |$e_2$| |$e_3$|)
  5830. \end{lstlisting}
  5831. \end{minipage}
  5832. &
  5833. $\Rightarrow$
  5834. &
  5835. \begin{minipage}{0.6\textwidth}
  5836. \begin{lstlisting}
  5837. (if (eq? |$e'_1$| (inject #f Boolean))
  5838. |$e'_3$|
  5839. |$e'_2$|)
  5840. \end{lstlisting}
  5841. \end{minipage}
  5842. \\[2ex]\hline
  5843. \begin{minipage}{0.25\textwidth}
  5844. \begin{lstlisting}
  5845. (eq? |$e_1$| |$e_2$|)
  5846. \end{lstlisting}
  5847. \end{minipage}
  5848. &
  5849. $\Rightarrow$
  5850. &
  5851. \begin{minipage}{0.6\textwidth}
  5852. \begin{lstlisting}
  5853. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  5854. \end{lstlisting}
  5855. \end{minipage}
  5856. \\[2ex]\hline
  5857. \begin{minipage}{0.25\textwidth}
  5858. \begin{lstlisting}
  5859. (and |$e_1$| |$e_2$|)
  5860. \end{lstlisting}
  5861. \end{minipage}
  5862. &
  5863. $\Rightarrow$
  5864. &
  5865. \begin{minipage}{0.6\textwidth}
  5866. \begin{lstlisting}
  5867. (let ([tmp |$e'_1$|])
  5868. (if (eq? tmp (inject #f Boolean))
  5869. tmp
  5870. |$e'_2$|))
  5871. \end{lstlisting}
  5872. \end{minipage} \\\hline
  5873. \end{tabular} \\
  5874. \caption{Compiling $R_7$ to $R_6$.}
  5875. \label{fig:compile-r7-r6}
  5876. \end{figure}
  5877. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5878. \chapter{Gradual Typing}
  5879. \label{ch:gradual-typing}
  5880. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  5881. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5882. \chapter{Parametric Polymorphism}
  5883. \label{ch:parametric-polymorphism}
  5884. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  5885. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  5886. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5887. \chapter{High-level Optimization}
  5888. \label{ch:high-level-optimization}
  5889. This chapter will present a procedure inlining pass based on the
  5890. algorithm of \citet{Waddell:1997fk}.
  5891. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5892. \chapter{Appendix}
  5893. \section{Interpreters}
  5894. \label{appendix:interp}
  5895. We provide several interpreters in the \key{interp.rkt} file. The
  5896. \key{interp-scheme} function takes an AST in one of the Racket-like
  5897. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  5898. the program, returning the result value. The \key{interp-C} function
  5899. interprets an AST for a program in one of the C-like languages ($C_0,
  5900. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  5901. for an x86 program.
  5902. \section{Utility Functions}
  5903. \label{appendix:utilities}
  5904. The utility function described in this section can be found in the
  5905. \key{utilities.rkt} file.
  5906. The \key{read-program} function takes a file path and parses that file
  5907. (it must be a Racket program) into an abstract syntax tree (as an
  5908. S-expression) with a \key{program} AST at the top.
  5909. The \key{assert} function displays the error message \key{msg} if the
  5910. Boolean \key{bool} is false.
  5911. \begin{lstlisting}
  5912. (define (assert msg bool) ...)
  5913. \end{lstlisting}
  5914. The \key{lookup} function ...
  5915. The \key{map2} function ...
  5916. \subsection{Graphs}
  5917. \begin{itemize}
  5918. \item The \code{make-graph} function takes a list of vertices
  5919. (symbols) and returns a graph.
  5920. \item The \code{add-edge} function takes a graph and two vertices and
  5921. adds an edge to the graph that connects the two vertices. The graph
  5922. is updated in-place. There is no return value for this function.
  5923. \item The \code{adjacent} function takes a graph and a vertex and
  5924. returns the set of vertices that are adjacent to the given
  5925. vertex. The return value is a Racket \code{hash-set} so it can be
  5926. used with functions from the \code{racket/set} module.
  5927. \item The \code{vertices} function takes a graph and returns the list
  5928. of vertices in the graph.
  5929. \end{itemize}
  5930. \subsection{Testing}
  5931. The \key{interp-tests} function takes a compiler name (a string), a
  5932. description of the passes, an interpreter for the source language, a
  5933. test family name (a string), and a list of test numbers, and runs the
  5934. compiler passes and the interpreters to check whether the passes
  5935. correct. The description of the passes is a list with one entry per
  5936. pass. An entry is a list with three things: a string giving the name
  5937. of the pass, the function that implements the pass (a translator from
  5938. AST to AST), and a function that implements the interpreter (a
  5939. function from AST to result value) for the language of the output of
  5940. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  5941. good choice. The \key{interp-tests} function assumes that the
  5942. subdirectory \key{tests} has a bunch of Scheme programs whose names
  5943. all start with the family name, followed by an underscore and then the
  5944. test number, ending in \key{.scm}. Also, for each Scheme program there
  5945. is a file with the same number except that it ends with \key{.in} that
  5946. provides the input for the Scheme program.
  5947. \begin{lstlisting}
  5948. (define (interp-tests name passes test-family test-nums) ...
  5949. \end{lstlisting}
  5950. The compiler-tests function takes a compiler name (a string) a
  5951. description of the passes (see the comment for \key{interp-tests}) a
  5952. test family name (a string), and a list of test numbers (see the
  5953. comment for interp-tests), and runs the compiler to generate x86 (a
  5954. \key{.s} file) and then runs gcc to generate machine code. It runs
  5955. the machine code and checks that the output is 42.
  5956. \begin{lstlisting}
  5957. (define (compiler-tests name passes test-family test-nums) ...)
  5958. \end{lstlisting}
  5959. The compile-file function takes a description of the compiler passes
  5960. (see the comment for \key{interp-tests}) and returns a function that,
  5961. given a program file name (a string ending in \key{.scm}), applies all
  5962. of the passes and writes the output to a file whose name is the same
  5963. as the program file name but with \key{.scm} replaced with \key{.s}.
  5964. \begin{lstlisting}
  5965. (define (compile-file passes)
  5966. (lambda (prog-file-name) ...))
  5967. \end{lstlisting}
  5968. \section{x86 Instruction Set Quick-Reference}
  5969. \label{sec:x86-quick-reference}
  5970. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  5971. do. We write $A \to B$ to mean that the value of $A$ is written into
  5972. location $B$. Address offsets are given in bytes. The instruction
  5973. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  5974. registers (such as $\%rax$), or memory references (such as
  5975. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  5976. reference per instruction. Other operands must be immediates or
  5977. registers.
  5978. \begin{table}[tbp]
  5979. \centering
  5980. \begin{tabular}{l|l}
  5981. \textbf{Instruction} & \textbf{Operation} \\ \hline
  5982. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  5983. \texttt{negq} $A$ & $- A \to A$ \\
  5984. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  5985. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  5986. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  5987. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  5988. \texttt{retq} & Pops the return address and jumps to it \\
  5989. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  5990. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  5991. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  5992. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set flag \\
  5993. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag matches
  5994. the condition code, otherwise go to the next instructions.
  5995. The condition codes are \key{e} for ``equal'',
  5996. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  5997. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  5998. \texttt{jl} $L$ & \\
  5999. \texttt{jle} $L$ & \\
  6000. \texttt{jg} $L$ & \\
  6001. \texttt{jge} $L$ & \\
  6002. \texttt{jmp} $L$ & Jump to label $L$ \\
  6003. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6004. \texttt{movzbq} $A$, $B$ &
  6005. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6006. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6007. and the extra bytes of $B$ are set to zero.} \\
  6008. & \\
  6009. & \\
  6010. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6011. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6012. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6013. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6014. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6015. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6016. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6017. description of the condition codes. $A$ must be a single byte register
  6018. (e.g., \texttt{al} or \texttt{cl}).} \\
  6019. \texttt{setl} $A$ & \\
  6020. \texttt{setle} $A$ & \\
  6021. \texttt{setg} $A$ & \\
  6022. \texttt{setge} $A$ &
  6023. \end{tabular}
  6024. \vspace{5pt}
  6025. \caption{Quick-reference for the x86 instructions used in this book.}
  6026. \label{tab:x86-instr}
  6027. \end{table}
  6028. \bibliographystyle{plainnat}
  6029. \bibliography{all}
  6030. \end{document}
  6031. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6032. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6033. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6034. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6035. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6036. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6037. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6038. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6039. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6040. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6041. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6042. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6043. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6044. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6045. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6046. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6047. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6048. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6049. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6050. %% LocalWords: len prev rootlen heaplen setl lt