book.tex 248 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656
  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 early 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. \begin{figure}[tbp]
  1773. \hspace{20pt}
  1774. \begin{minipage}{0.45\textwidth}
  1775. \begin{lstlisting}[numbers=left]
  1776. (program (v w x y z t.1 t.2)
  1777. (movq (int 1) (var v))
  1778. (movq (int 46) (var w))
  1779. (movq (var v) (var x))
  1780. (addq (int 7) (var x))
  1781. (movq (var x) (var y))
  1782. (addq (int 4) (var y))
  1783. (movq (var x) (var z))
  1784. (addq (var w) (var z))
  1785. (movq (var y) (var t.1))
  1786. (negq (var t.1))
  1787. (movq (var z) (var t.2))
  1788. (addq (var t.1) (var t.2))
  1789. (movq (var t.2) (reg rax)))
  1790. \end{lstlisting}
  1791. \end{minipage}
  1792. \vrule\hspace{10pt}
  1793. \begin{minipage}{0.45\textwidth}
  1794. \begin{lstlisting}
  1795. |$\{ v \}$|
  1796. |$\{ v, w \}$|
  1797. |$\{ w, x \}$|
  1798. |$\{ w, x \}$|
  1799. |$\{ w, x, y\}$|
  1800. |$\{ w, x, y \}$|
  1801. |$\{ w, y, z \}$|
  1802. |$\{ y, z \}$|
  1803. |$\{ t.1, z \}$|
  1804. |$\{ t.1, z \}$|
  1805. |$\{t.1,t.2\}$|
  1806. |$\{t.2\}$|
  1807. |$\{\}$|
  1808. \end{lstlisting}
  1809. \end{minipage}
  1810. \caption{An example program annotated with live-after sets.}
  1811. \label{fig:live-eg}
  1812. \end{figure}
  1813. \begin{exercise}\normalfont
  1814. Implement the compiler pass named \code{uncover-live} that computes
  1815. the live-after sets. We recommend storing the live-after sets (a list
  1816. of lists of variables) in the $\itm{info}$ field of the \key{program}
  1817. node alongside the list of variables as follows.
  1818. \begin{lstlisting}
  1819. (program (|$\Var^{*}$| |$\itm{live{-}afters}$|) |$\Instr^{+}$|)
  1820. \end{lstlisting}
  1821. I recommend organizing your code to use a helper function that takes a
  1822. list of statements and an initial live-after set (typically empty) and
  1823. returns the list of statements and the list of live-after sets. For
  1824. this chapter, returning the list of statements is unnecessary, as they
  1825. awill be unchanged, but in Chapter~\ref{ch:bool-types} we introduce
  1826. \key{if} statements and will need to annotate them with the live-after
  1827. sets of the two branches.
  1828. I recommend creating helper functions to 1) compute the set of
  1829. variables that appear in an argument (of an instruction), 2) compute
  1830. the variables read by an instruction which corresponds to the $R$
  1831. function discussed above, and 3) the variables written by an
  1832. instruction which corresponds to $W$.
  1833. \end{exercise}
  1834. \section{Building the Interference Graph}
  1835. \label{sec:build-interference}
  1836. Based on the liveness analysis, we know where each variable is needed.
  1837. However, during register allocation, we need to answer questions of
  1838. the specific form: are variables $u$ and $v$ live at the same time?
  1839. (And therefore cannot be assigned to the same register.) To make this
  1840. question easier to answer, we create an explicit data structure, an
  1841. \emph{interference graph}. An interference graph is an undirected
  1842. graph that has an edge between two variables if they are live at the
  1843. same time, that is, if they interfere with each other.
  1844. The most obvious way to compute the interference graph is to look at
  1845. the set of live variables between each statement in the program, and
  1846. add an edge to the graph for every pair of variables in the same set.
  1847. This approach is less than ideal for two reasons. First, it can be
  1848. rather expensive because it takes $O(n^2)$ time to look at every pair
  1849. in a set of $n$ live variables. Second, there is a special case in
  1850. which two variables that are live at the same time do not actually
  1851. interfere with each other: when they both contain the same value
  1852. because we have assigned one to the other.
  1853. A better way to compute the interference graph is given by the
  1854. following.
  1855. \begin{itemize}
  1856. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  1857. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1858. d$ or $v = s$.
  1859. \item If instruction $I_k$ is not a move but some other arithmetic
  1860. instruction such as (\key{addq} $s$\, $d$), then add the edge $(d,v)$
  1861. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1862. \item If instruction $I_k$ is of the form (\key{callq}
  1863. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1864. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1865. \end{itemize}
  1866. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  1867. the following interference for the instruction at the specified line
  1868. number.
  1869. \begin{quote}
  1870. Line 2: no interference,\\
  1871. Line 3: $w$ interferes with $v$,\\
  1872. Line 4: $x$ interferes with $w$,\\
  1873. Line 5: $x$ interferes with $w$,\\
  1874. Line 6: $y$ interferes with $w$,\\
  1875. Line 7: $y$ interferes with $w$ and $x$,\\
  1876. Line 8: $z$ interferes with $w$ and $y$,\\
  1877. Line 9: $z$ interferes with $y$, \\
  1878. Line 10: $t.1$ interferes with $z$, \\
  1879. Line 11: $t.1$ interferes with $z$, \\
  1880. Line 12: $t.2$ interferes with $t.1$, \\
  1881. Line 13: no interference. \\
  1882. Line 14: no interference.
  1883. \end{quote}
  1884. The resulting interference graph is shown in
  1885. Figure~\ref{fig:interfere}.
  1886. \begin{figure}[tbp]
  1887. \large
  1888. \[
  1889. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1890. \node (v) at (0,0) {$v$};
  1891. \node (w) at (2,0) {$w$};
  1892. \node (x) at (4,0) {$x$};
  1893. \node (t1) at (6,0) {$t.1$};
  1894. \node (y) at (2,-2) {$y$};
  1895. \node (z) at (4,-2) {$z$};
  1896. \node (t2) at (6,-2) {$t.2$};
  1897. \draw (v) to (w);
  1898. \foreach \i in {w,x,y}
  1899. {
  1900. \foreach \j in {w,x,y}
  1901. {
  1902. \draw (\i) to (\j);
  1903. }
  1904. }
  1905. \draw (z) to (w);
  1906. \draw (z) to (y);
  1907. \draw (t1) to (z);
  1908. \draw (t2) to (t1);
  1909. \end{tikzpicture}
  1910. \]
  1911. \caption{The interference graph of the example program.}
  1912. \label{fig:interfere}
  1913. \end{figure}
  1914. Our next concern is to choose a data structure for representing the
  1915. interference graph. There are many standard choices for how to
  1916. represent a graph: \emph{adjacency matrix}, \emph{adjacency list}, and
  1917. \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a data
  1918. structure is to study the algorithm that uses the data structure,
  1919. determine what operations need to be performed, and then choose the
  1920. data structure that provide the most efficient implementations of
  1921. those operations. Often times the choice of data structure can have an
  1922. affect on the time complexity of the algorithm, as it does here. If
  1923. you skim the next section, you will see that the register allocation
  1924. algorithm needs to ask the graph for all of its vertices and, given a
  1925. vertex, it needs to known all of the adjacent vertices. Thus, the
  1926. correct choice of graph representation is that of an adjacency
  1927. list. There are helper functions in \code{utilities.rkt} for
  1928. representing graphs using the adjacency list representation:
  1929. \code{make-graph}, \code{add-edge}, and \code{adjacent}
  1930. (Appendix~\ref{appendix:utilities}). In particular, those functions
  1931. use a hash table to map each vertex to the set of adjacent vertices,
  1932. and the sets are represented using Racket's \key{set}, which is also a
  1933. hash table.
  1934. \begin{exercise}\normalfont
  1935. Implement the compiler pass named \code{build-interference} according
  1936. to the algorithm suggested above. The output of this pass should
  1937. replace the live-after sets with the interference $\itm{graph}$ as
  1938. follows.
  1939. \begin{lstlisting}
  1940. (program (|$\Var^{*}$| |$\itm{graph}$|) |$\Instr^{+}$|)
  1941. \end{lstlisting}
  1942. \end{exercise}
  1943. \section{Graph Coloring via Sudoku}
  1944. \label{sec:graph-coloring}
  1945. We now come to the main event, mapping variables to registers (or to
  1946. stack locations in the event that we run out of registers). We need
  1947. to make sure not to map two variables to the same register if the two
  1948. variables interfere with each other. In terms of the interference
  1949. graph, this means we cannot map adjacent nodes to the same register.
  1950. If we think of registers as colors, the register allocation problem
  1951. becomes the widely-studied graph coloring
  1952. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1953. The reader may be more familiar with the graph coloring problem then he
  1954. or she realizes; the popular game of Sudoku is an instance of the
  1955. graph coloring problem. The following describes how to build a graph
  1956. out of an initial Sudoku board.
  1957. \begin{itemize}
  1958. \item There is one node in the graph for each Sudoku square.
  1959. \item There is an edge between two nodes if the corresponding squares
  1960. are in the same row, in the same column, or if the squares are in
  1961. the same $3\times 3$ region.
  1962. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1963. \item Based on the initial assignment of numbers to squares in the
  1964. Sudoku board, assign the corresponding colors to the corresponding
  1965. nodes in the graph.
  1966. \end{itemize}
  1967. If you can color the remaining nodes in the graph with the nine
  1968. colors, then you have also solved the corresponding game of Sudoku.
  1969. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  1970. the corresponding graph with colored vertices. We map the Sudoku
  1971. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  1972. sampling of the vertices (those that are colored) because showing
  1973. edges for all of the vertices would make the graph unreadable.
  1974. \begin{figure}[tbp]
  1975. \includegraphics[width=0.45\textwidth]{sudoku}
  1976. \includegraphics[width=0.5\textwidth]{sudoku-graph}
  1977. \caption{A Sudoku game board and the corresponding colored graph.}
  1978. \label{fig:sudoku-graph}
  1979. \end{figure}
  1980. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1981. come up with an algorithm for allocating registers. For example, one
  1982. of the basic techniques for Sudoku is called Pencil Marks. The idea is
  1983. that you use a process of elimination to determine what numbers no
  1984. longer make sense for a square, and write down those numbers in the
  1985. square (writing very small). For example, if the number $1$ is
  1986. assigned to a square, then by process of elimination, you can write
  1987. the pencil mark $1$ in all the squares in the same row, column, and
  1988. region. Many Sudoku computer games provide automatic support for
  1989. Pencil Marks. This heuristic also reduces the degree of branching in
  1990. the search tree.
  1991. The Pencil Marks technique corresponds to the notion of color
  1992. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  1993. node, in Sudoku terms, is the set of colors that are no longer
  1994. available. In graph terminology, we have the following definition:
  1995. \begin{equation*}
  1996. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  1997. \text{ and } \mathrm{color}(v) = c \}
  1998. \end{equation*}
  1999. where $\mathrm{adjacent}(u)$ is the set of nodes adjacent to $u$.
  2000. Using the Pencil Marks technique leads to a simple strategy for
  2001. filling in numbers: if there is a square with only one possible number
  2002. left, then write down that number! But what if there are no squares
  2003. with only one possibility left? One brute-force approach is to just
  2004. make a guess. If that guess ultimately leads to a solution, great. If
  2005. not, backtrack to the guess and make a different guess. Of course,
  2006. backtracking can be horribly time consuming. One standard way to
  2007. reduce the amount of backtracking is to use the most-constrained-first
  2008. heuristic. That is, when making a guess, always choose a square with
  2009. the fewest possibilities left (the node with the highest saturation).
  2010. The idea is that choosing highly constrained squares earlier rather
  2011. than later is better because later there may not be any possibilities.
  2012. In some sense, register allocation is easier than Sudoku because we
  2013. can always cheat and add more numbers by mapping variables to the
  2014. stack. We say that a variable is \emph{spilled} when we decide to map
  2015. it to a stack location. We would like to minimize the time needed to
  2016. color the graph, and backtracking is expensive. Thus, it makes sense
  2017. to keep the most-constrained-first heuristic but drop the backtracking
  2018. in favor of greedy search (guess and just keep going).
  2019. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2020. greedy algorithm for register allocation based on saturation and the
  2021. most-constrained-first heuristic, which is roughly equivalent to the
  2022. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2023. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2024. as in Sudoku, the algorithm represents colors with integers, with the
  2025. first $k$ colors corresponding to the $k$ registers in a given machine
  2026. and the rest of the integers corresponding to stack locations.
  2027. \begin{figure}[btp]
  2028. \centering
  2029. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2030. Algorithm: DSATUR
  2031. Input: a graph |$G$|
  2032. Output: an assignment |$\mathrm{color}[v]$| for each node |$v \in G$|
  2033. |$W \gets \mathit{vertices}(G)$|
  2034. while |$W \neq \emptyset$| do
  2035. pick a node |$u$| from |$W$| with the highest saturation,
  2036. breaking ties randomly
  2037. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(v)\}$|
  2038. |$\mathrm{color}[u] \gets c$|
  2039. |$W \gets W - \{u\}$|
  2040. \end{lstlisting}
  2041. \caption{The saturation-based greedy graph coloring algorithm.}
  2042. \label{fig:satur-algo}
  2043. \end{figure}
  2044. With this algorithm in hand, let us return to the running example and
  2045. consider how to color the interference graph in
  2046. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2047. register allocation because we use it to patch instructions, so we
  2048. remove that vertex from the graph. Initially, all of the nodes are
  2049. not yet colored and they are unsaturated, so we annotate each of them
  2050. with a dash for their color and an empty set for the saturation.
  2051. \[
  2052. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2053. \node (v) at (0,0) {$v:-,\{\}$};
  2054. \node (w) at (3,0) {$w:-,\{\}$};
  2055. \node (x) at (6,0) {$x:-,\{\}$};
  2056. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2057. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2058. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2059. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2060. \draw (v) to (w);
  2061. \foreach \i in {w,x,y}
  2062. {
  2063. \foreach \j in {w,x,y}
  2064. {
  2065. \draw (\i) to (\j);
  2066. }
  2067. }
  2068. \draw (z) to (w);
  2069. \draw (z) to (y);
  2070. \draw (t1) to (z);
  2071. \draw (t2) to (t1);
  2072. \end{tikzpicture}
  2073. \]
  2074. We select a maximally saturated node and color it $0$. In this case we
  2075. have a 7-way tie, so we arbitrarily pick $y$. The then mark color $0$
  2076. as no longer available for $w$, $x$, and $z$ because they interfere
  2077. with $y$.
  2078. \[
  2079. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2080. \node (v) at (0,0) {$v:-,\{\}$};
  2081. \node (w) at (3,0) {$w:-,\{0\}$};
  2082. \node (x) at (6,0) {$x:-,\{0\}$};
  2083. \node (y) at (3,-1.5) {$y:0,\{\}$};
  2084. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  2085. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2086. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2087. \draw (v) to (w);
  2088. \foreach \i in {w,x,y}
  2089. {
  2090. \foreach \j in {w,x,y}
  2091. {
  2092. \draw (\i) to (\j);
  2093. }
  2094. }
  2095. \draw (z) to (w);
  2096. \draw (z) to (y);
  2097. \draw (t1) to (z);
  2098. \draw (t2) to (t1);
  2099. \end{tikzpicture}
  2100. \]
  2101. Now we repeat the process, selecting another maximally saturated node.
  2102. This time there is a three-way tie between $w$, $x$, and $z$. We color
  2103. $w$ with $1$.
  2104. \[
  2105. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2106. \node (v) at (0,0) {$v:-,\{1\}$};
  2107. \node (w) at (3,0) {$w:1,\{0\}$};
  2108. \node (x) at (6,0) {$x:-,\{0,1\}$};
  2109. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  2110. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2111. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2112. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2113. \draw (t1) to (z);
  2114. \draw (t2) to (t1);
  2115. \draw (v) to (w);
  2116. \foreach \i in {w,x,y}
  2117. {
  2118. \foreach \j in {w,x,y}
  2119. {
  2120. \draw (\i) to (\j);
  2121. }
  2122. }
  2123. \draw (z) to (w);
  2124. \draw (z) to (y);
  2125. \end{tikzpicture}
  2126. \]
  2127. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  2128. next available color which is $2$.
  2129. \[
  2130. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2131. \node (v) at (0,0) {$v:-,\{1\}$};
  2132. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2133. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2134. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2135. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2136. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2137. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2138. \draw (t1) to (z);
  2139. \draw (t2) to (t1);
  2140. \draw (v) to (w);
  2141. \foreach \i in {w,x,y}
  2142. {
  2143. \foreach \j in {w,x,y}
  2144. {
  2145. \draw (\i) to (\j);
  2146. }
  2147. }
  2148. \draw (z) to (w);
  2149. \draw (z) to (y);
  2150. \end{tikzpicture}
  2151. \]
  2152. Node $z$ is the next most highly saturated, so we color $z$ with $2$.
  2153. \[
  2154. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2155. \node (v) at (0,0) {$v:-,\{1\}$};
  2156. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2157. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2158. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2159. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2160. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2161. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2162. \draw (t1) to (z);
  2163. \draw (t2) to (t1);
  2164. \draw (v) to (w);
  2165. \foreach \i in {w,x,y}
  2166. {
  2167. \foreach \j in {w,x,y}
  2168. {
  2169. \draw (\i) to (\j);
  2170. }
  2171. }
  2172. \draw (z) to (w);
  2173. \draw (z) to (y);
  2174. \end{tikzpicture}
  2175. \]
  2176. We have a 2-way tie between $v$ and $t.1$. We choose to color $v$ with
  2177. $0$.
  2178. \[
  2179. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2180. \node (v) at (0,0) {$v:0,\{1\}$};
  2181. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2182. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2183. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2184. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2185. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2186. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2187. \draw (t1) to (z);
  2188. \draw (t2) to (t1);
  2189. \draw (v) to (w);
  2190. \foreach \i in {w,x,y}
  2191. {
  2192. \foreach \j in {w,x,y}
  2193. {
  2194. \draw (\i) to (\j);
  2195. }
  2196. }
  2197. \draw (z) to (w);
  2198. \draw (z) to (y);
  2199. \end{tikzpicture}
  2200. \]
  2201. In the last two steps of the algorithm, we color $t.1$ with $0$
  2202. then $t.2$ with $1$.
  2203. \[
  2204. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2205. \node (v) at (0,0) {$v:0,\{1\}$};
  2206. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2207. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2208. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2209. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2210. \node (t1) at (9,0) {$t.1:0,\{2,1\}$};
  2211. \node (t2) at (9,-1.5) {$t.2:1,\{0\}$};
  2212. \draw (t1) to (z);
  2213. \draw (t2) to (t1);
  2214. \draw (v) to (w);
  2215. \foreach \i in {w,x,y}
  2216. {
  2217. \foreach \j in {w,x,y}
  2218. {
  2219. \draw (\i) to (\j);
  2220. }
  2221. }
  2222. \draw (z) to (w);
  2223. \draw (z) to (y);
  2224. \end{tikzpicture}
  2225. \]
  2226. With the coloring complete, we can finalize the assignment of
  2227. variables to registers and stack locations. Recall that if we have $k$
  2228. registers, we map the first $k$ colors to registers and the rest to
  2229. stack locations. Suppose for the moment that we just have one extra
  2230. register to use for register allocation, just \key{rbx}. Then the
  2231. following is the mapping of colors to registers and stack allocations.
  2232. \[
  2233. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2234. \]
  2235. Putting this mapping together with the above coloring of the variables, we
  2236. arrive at the assignment:
  2237. \begin{gather*}
  2238. \{ v \mapsto \key{\%rbx}, \,
  2239. w \mapsto \key{-8(\%rbp)}, \,
  2240. x \mapsto \key{-16(\%rbp)}, \,
  2241. y \mapsto \key{\%rbx}, \,
  2242. z\mapsto \key{-16(\%rbp)}, \\
  2243. t.1\mapsto \key{\%rbx} ,\,
  2244. t.2\mapsto \key{-8(\%rbp)} \}
  2245. \end{gather*}
  2246. Applying this assignment to our running example
  2247. (Figure~\ref{fig:reg-eg}) yields the program on the right.\\
  2248. % why frame size of 32? -JGS
  2249. \begin{minipage}{0.4\textwidth}
  2250. \begin{lstlisting}
  2251. (program (v w x y z)
  2252. (movq (int 1) (var v))
  2253. (movq (int 46) (var w))
  2254. (movq (var v) (var x))
  2255. (addq (int 7) (var x))
  2256. (movq (var x) (var y))
  2257. (addq (int 4) (var y))
  2258. (movq (var x) (var z))
  2259. (addq (var w) (var z))
  2260. (movq (var y) (var t.1))
  2261. (negq (var t.1))
  2262. (movq (var z) (var t.2))
  2263. (addq (var t.1) (var t.2))
  2264. (movq (var t.2) (reg rax)))
  2265. \end{lstlisting}
  2266. \end{minipage}
  2267. $\Rightarrow$
  2268. \begin{minipage}{0.45\textwidth}
  2269. \begin{lstlisting}
  2270. (program 16
  2271. (movq (int 1) (reg rbx))
  2272. (movq (int 46) (deref rbp -8))
  2273. (movq (reg rbx) (deref rbp -16))
  2274. (addq (int 7) (deref rbp -16))
  2275. (movq (deref rbp -16) (reg rbx))
  2276. (addq (int 4) (reg rbx))
  2277. (movq (deref rbp -16) (deref rbp -16))
  2278. (addq (deref rbp -8) (deref rbp -16))
  2279. (movq (reg rbx) (reg rbx))
  2280. (negq (reg rbx))
  2281. (movq (deref rbp -16) (deref rbp -8))
  2282. (addq (reg rbx) (deref rbp -8))
  2283. (movq (deref rbp -8) (reg rax)))
  2284. \end{lstlisting}
  2285. \end{minipage}
  2286. The resulting program is almost an x86 program. The remaining step
  2287. is to apply the patch instructions pass. In this example, the trivial
  2288. move of \code{-16(\%rbp)} to itself is deleted and the addition of
  2289. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2290. \code{rax}. The following shows the portion of the program that
  2291. changed.
  2292. \begin{lstlisting}
  2293. (addq (int 4) (reg rbx))
  2294. (movq (deref rbp -8) (reg rax)
  2295. (addq (reg rax) (deref rbp -16))
  2296. \end{lstlisting}
  2297. An overview of all of the passes involved in register allocation is
  2298. shown in Figure~\ref{fig:reg-alloc-passes}.
  2299. \begin{figure}[p]
  2300. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2301. \node (R1) at (0,2) {\large $R_1$};
  2302. \node (R1-2) at (3,2) {\large $R_1$};
  2303. \node (C0-1) at (3,0) {\large $C_0$};
  2304. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2305. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2306. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2307. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2308. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2309. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2310. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2311. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  2312. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2313. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2314. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2315. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2316. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2317. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2318. \end{tikzpicture}
  2319. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2320. \label{fig:reg-alloc-passes}
  2321. \end{figure}
  2322. \begin{exercise}\normalfont
  2323. Implement the pass \code{allocate-registers} and test it by creating
  2324. new example programs that exercise all of the register allocation
  2325. algorithm, such as forcing variables to be spilled to the stack.
  2326. I recommend organizing our code by creating a helper function named
  2327. \code{color-graph} that takes an interference graph and a list of all
  2328. the variables in the program. This function should return a mapping of
  2329. variables to their colors. By creating this helper function, we will
  2330. be able to reuse it in Chapter~\ref{ch:functions} when we add support
  2331. for functions. Once you have obtained the coloring from
  2332. \code{color-graph}, you can assign the variables to registers or stack
  2333. locations based on their color and then use the \code{assign-homes}
  2334. function from Section~\ref{sec:assign-s0} to replace the variables
  2335. with their assigned location.
  2336. \end{exercise}
  2337. \section{Print x86 and Conventions for Registers}
  2338. \label{sec:print-x86-reg-alloc}
  2339. Recall the the \code{print-x86} pass generates the prelude and
  2340. conclusion instructions for the \code{main} function. The prelude
  2341. saved the values in \code{rbp} and \code{rsp} and the conclusion
  2342. returned those values to \code{rbp} and \code{rsp}. The reason for
  2343. this is that there are agreed-upon conventions for how different
  2344. functions share the same fixed set of registers. There is a function
  2345. inside the operating system (OS) that calls our \code{main} function,
  2346. and that OS function uses the same registers that we use in
  2347. \code{main}. The convention for x86 is that the caller is responsible
  2348. for freeing up some registers, the \emph{caller save registers}, prior
  2349. to the function call, and the callee is responsible for saving and
  2350. restoring some other registers, the \emph{callee save registers},
  2351. before and after using them. The caller save registers are
  2352. \begin{lstlisting}
  2353. rax rdx rcx rsi rdi r8 r9 r10 r11
  2354. \end{lstlisting}
  2355. while the callee save registers are
  2356. \begin{lstlisting}
  2357. rsp rbp rbx r12 r13 r14 r15
  2358. \end{lstlisting}
  2359. Another way to think about this caller/callee convention is the
  2360. following. The caller should assume that all the caller save registers
  2361. get overwritten with arbitrary values by the callee. On the other
  2362. hand, the caller can safely assume that all the callee save registers
  2363. contain the same values after the call that they did before the call.
  2364. The callee can freely use any of the caller save registers. However,
  2365. if the callee wants to use a callee save register, the callee must
  2366. arrange to put the original value back in the register prior to
  2367. returning to the caller, which is usually accomplished by saving and
  2368. restoring the value from the stack.
  2369. The upshot of these conventions is that the \code{main} function needs
  2370. to save (in the prelude) and restore (in the conclusion) any callee
  2371. save registers that get used during register allocation. The simplest
  2372. approach is to save and restore all the callee save registers. The
  2373. more efficient approach is to keep track of which callee save
  2374. registers were used and only save and restore them. Either way, make
  2375. sure to take this use of stack space into account when you round up
  2376. the size of the frame to make sure it is a multiple of 16 bytes.
  2377. \section{Challenge: Move Biasing$^{*}$}
  2378. \label{sec:move-biasing}
  2379. This section describes an optional enhancement to register allocation
  2380. for those students who are looking for an extra challenge or who have
  2381. a deeper interest in register allocation.
  2382. We return to the running example, but we remove the supposition that
  2383. we only have one register to use. So we have the following mapping of
  2384. color numbers to registers.
  2385. \[
  2386. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2387. \]
  2388. Using the same assignment that was produced by register allocator
  2389. described in the last section, we get the following program.
  2390. \begin{minipage}{0.45\textwidth}
  2391. \begin{lstlisting}
  2392. (program (v w x y z)
  2393. (movq (int 1) (var v))
  2394. (movq (int 46) (var w))
  2395. (movq (var v) (var x))
  2396. (addq (int 7) (var x))
  2397. (movq (var x) (var y))
  2398. (addq (int 4) (var y))
  2399. (movq (var x) (var z))
  2400. (addq (var w) (var z))
  2401. (movq (var y) (var t.1))
  2402. (negq (var t.1))
  2403. (movq (var z) (var t.2))
  2404. (addq (var t.1) (var t.2))
  2405. (movq (var t.2) (reg rax)))
  2406. \end{lstlisting}
  2407. \end{minipage}
  2408. $\Rightarrow$
  2409. \begin{minipage}{0.45\textwidth}
  2410. \begin{lstlisting}
  2411. (program 0
  2412. (movq (int 1) (reg rbx))
  2413. (movq (int 46) (reg rcx))
  2414. (movq (reg rbx) (reg rdx))
  2415. (addq (int 7) (reg rdx))
  2416. (movq (reg rdx) (reg rbx))
  2417. (addq (int 4) (reg rbx))
  2418. (movq (reg rdx) (reg rdx))
  2419. (addq (reg rcx) (reg rdx))
  2420. (movq (reg rbx) (reg rbx))
  2421. (negq (reg rbx))
  2422. (movq (reg rdx) (reg rcx))
  2423. (addq (reg rbx) (reg rcx))
  2424. (movq (reg rcx) (reg rax)))
  2425. \end{lstlisting}
  2426. \end{minipage}
  2427. While this allocation is quite good, we could do better. For example,
  2428. the variables \key{v} and \key{x} ended up in different registers, but
  2429. if they had been placed in the same register, then the move from
  2430. \key{v} to \key{x} could be removed.
  2431. We say that two variables $p$ and $q$ are \emph{move related} if they
  2432. participate together in a \key{movq} instruction, that is, \key{movq
  2433. p, q} or \key{movq q, p}. When the register allocator chooses a
  2434. color for a variable, it should prefer a color that has already been
  2435. used for a move-related variable (assuming that they do not
  2436. interfere). Of course, this preference should not override the
  2437. preference for registers over stack locations, but should only be used
  2438. as a tie breaker when choosing between registers or when choosing
  2439. between stack locations.
  2440. We recommend that you represent the move relationships in a graph,
  2441. similar to how we represented interference. The following is the
  2442. \emph{move graph} for our running example.
  2443. \[
  2444. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2445. \node (v) at (0,0) {$v$};
  2446. \node (w) at (3,0) {$w$};
  2447. \node (x) at (6,0) {$x$};
  2448. \node (y) at (3,-1.5) {$y$};
  2449. \node (z) at (6,-1.5) {$z$};
  2450. \node (t1) at (9,0) {$t.1$};
  2451. \node (t2) at (9,-1.5) {$t.2$};
  2452. \draw (t1) to (y);
  2453. \draw (t2) to (z);
  2454. \draw[bend left=20] (v) to (x);
  2455. \draw (x) to (y);
  2456. \draw (x) to (z);
  2457. \end{tikzpicture}
  2458. \]
  2459. Now we replay the graph coloring, pausing to see the coloring of $z$
  2460. and $v$. So we have the following coloring so far and the most
  2461. saturated vertex is $z$.
  2462. \[
  2463. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2464. \node (v) at (0,0) {$v:-,\{1\}$};
  2465. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2466. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2467. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2468. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2469. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2470. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2471. \draw (t1) to (z);
  2472. \draw (t2) to (t1);
  2473. \draw (v) to (w);
  2474. \foreach \i in {w,x,y}
  2475. {
  2476. \foreach \j in {w,x,y}
  2477. {
  2478. \draw (\i) to (\j);
  2479. }
  2480. }
  2481. \draw (z) to (w);
  2482. \draw (z) to (y);
  2483. \end{tikzpicture}
  2484. \]
  2485. Last time we chose to color $z$ with $2$, which so happens to be the
  2486. color of $x$, and $z$ is move related to $x$. This was rather lucky,
  2487. and if the program had been a little different, and say $x$ had been
  2488. already assigned to $3$, then $z$ would still get $2$ and our luck
  2489. would have run out. With move biasing, we use the fact that $z$ and
  2490. $x$ are move related to influence the choice of color for $z$, in this
  2491. case choosing $2$ because that's the color of $x$.
  2492. \[
  2493. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2494. \node (v) at (0,0) {$v:-,\{1\}$};
  2495. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2496. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2497. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2498. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2499. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2500. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2501. \draw (t1) to (z);
  2502. \draw (t2) to (t1);
  2503. \draw (v) to (w);
  2504. \foreach \i in {w,x,y}
  2505. {
  2506. \foreach \j in {w,x,y}
  2507. {
  2508. \draw (\i) to (\j);
  2509. }
  2510. }
  2511. \draw (z) to (w);
  2512. \draw (z) to (y);
  2513. \end{tikzpicture}
  2514. \]
  2515. Next we consider coloring the variable $v$, and we just need to avoid
  2516. choosing $1$ because of the interference with $w$. Last time we choose
  2517. the color $0$, simply because it was the lowest, but this time we know
  2518. that $v$ is move related to $x$, so we choose the color $2$.
  2519. \[
  2520. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2521. \node (v) at (0,0) {$v:2,\{1\}$};
  2522. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2523. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2524. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2525. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2526. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2527. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2528. \draw (t1) to (z);
  2529. \draw (t2) to (t1);
  2530. \draw (v) to (w);
  2531. \foreach \i in {w,x,y}
  2532. {
  2533. \foreach \j in {w,x,y}
  2534. {
  2535. \draw (\i) to (\j);
  2536. }
  2537. }
  2538. \draw (z) to (w);
  2539. \draw (z) to (y);
  2540. \end{tikzpicture}
  2541. \]
  2542. We apply this register assignment to the running example, on the left,
  2543. to obtain the code on right.
  2544. \begin{minipage}{0.45\textwidth}
  2545. \begin{lstlisting}
  2546. (program (v w x y z)
  2547. (movq (int 1) (var v))
  2548. (movq (int 46) (var w))
  2549. (movq (var v) (var x))
  2550. (addq (int 7) (var x))
  2551. (movq (var x) (var y))
  2552. (addq (int 4) (var y))
  2553. (movq (var x) (var z))
  2554. (addq (var w) (var z))
  2555. (movq (var y) (var t.1))
  2556. (negq (var t.1))
  2557. (movq (var z) (var t.2))
  2558. (addq (var t.1) (var t.2))
  2559. (movq (var t.2) (reg rax)))
  2560. \end{lstlisting}
  2561. \end{minipage}
  2562. $\Rightarrow$
  2563. \begin{minipage}{0.45\textwidth}
  2564. \begin{lstlisting}
  2565. (program 0
  2566. (movq (int 1) (reg rdx))
  2567. (movq (int 46) (reg rcx))
  2568. (movq (reg rdx) (reg rdx))
  2569. (addq (int 7) (reg rdx))
  2570. (movq (reg rdx) (reg rbx))
  2571. (addq (int 4) (reg rbx))
  2572. (movq (reg rdx) (reg rdx))
  2573. (addq (reg rcx) (reg rdx))
  2574. (movq (reg rbx) (reg rbx))
  2575. (negq (reg rbx))
  2576. (movq (reg rdx) (reg rcx))
  2577. (addq (reg rbx) (reg rcx))
  2578. (movq (reg rcx) (reg rax)))
  2579. \end{lstlisting}
  2580. \end{minipage}
  2581. The \code{patch-instructions} then removes the trivial moves from
  2582. \key{v} to \key{x}, from \key{x} to \key{z}, and from \key{y} to
  2583. \key{t.1}, to obtain the following result.
  2584. \begin{lstlisting}
  2585. (program 0
  2586. (movq (int 1) (reg rdx))
  2587. (movq (int 46) (reg rcx))
  2588. (addq (int 7) (reg rdx))
  2589. (movq (reg rdx) (reg rbx))
  2590. (addq (int 4) (reg rbx))
  2591. (addq (reg rcx) (reg rdx))
  2592. (negq (reg rbx))
  2593. (movq (reg rdx) (reg rcx))
  2594. (addq (reg rbx) (reg rcx))
  2595. (movq (reg rcx) (reg rax)))
  2596. \end{lstlisting}
  2597. \begin{exercise}\normalfont
  2598. Change your implementation of \code{allocate-registers} to take move
  2599. biasing into account. Make sure that your compiler still passes all of
  2600. the previous tests. Create two new tests that include at least one
  2601. opportunity for move biasing and visually inspect the output x86
  2602. programs to make sure that your move biasing is working properly.
  2603. \end{exercise}
  2604. \marginpar{\footnotesize To do: another neat challenge would be to do
  2605. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2606. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2607. \chapter{Booleans, Control Flow, and Type Checking}
  2608. \label{ch:bool-types}
  2609. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2610. integers. In this Chapter we add a second kind of value, the Booleans,
  2611. to create the $R_2$ language. The Boolean values \emph{true} and
  2612. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2613. Racket. We also introduce several operations that involve Booleans
  2614. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2615. \key{if} expression. With the addition of \key{if} expressions,
  2616. programs can have non-trivial control flow which has an impact on
  2617. several parts of the compiler. Also, because we now have two kinds of
  2618. values, we need to worry about programs that apply an operation to the
  2619. wrong kind of value, such as \code{(not 1)}.
  2620. There are two language design options for such situations. One option
  2621. is to signal an error and the other is to provide a wider
  2622. interpretation of the operation. The Racket language uses a mixture of
  2623. these two options, depending on the operation and the kind of
  2624. value. For example, the result of \code{(not 1)} in Racket is
  2625. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2626. the other hand, \code{(car 1)} results in a run-time error in Racket
  2627. stating that \code{car} expects a pair.
  2628. The Typed Racket language makes similar design choices as Racket,
  2629. except much of the error detection happens at compile time instead of
  2630. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2631. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2632. reports a compile-time error because the type of the argument is
  2633. expected to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2634. For the $R_2$ language we choose to be more like Typed Racket in that
  2635. we shall perform type checking during compilation. In
  2636. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2637. is, how to compile a dynamically typed language like Racket. The
  2638. $R_2$ language is a subset of Typed Racket but by no means includes
  2639. all of Typed Racket. Furthermore, for many of the operations we shall
  2640. take a narrower interpretation than Typed Racket, for example,
  2641. rejecting \code{(not 1)}.
  2642. This chapter is organized as follows. We begin by defining the syntax
  2643. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2644. then introduce the idea of type checking and build a type checker for
  2645. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2646. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2647. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2648. how our compiler passes need to change to accommodate Booleans and
  2649. conditional control flow.
  2650. \section{The $R_2$ Language}
  2651. \label{sec:r2-lang}
  2652. The syntax of the $R_2$ language is defined in
  2653. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray) ,
  2654. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  2655. \code{if} expression. Also, we expand the operators to include the
  2656. \key{and} and \key{not} on Booleans, the \key{eq?} operations for
  2657. comparing two integers or two Booleans, and the \key{<}, \key{<=},
  2658. \key{>}, and \key{>=} operations for comparing integers.
  2659. \begin{figure}[tp]
  2660. \centering
  2661. \fbox{
  2662. \begin{minipage}{0.96\textwidth}
  2663. \[
  2664. \begin{array}{lcl}
  2665. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2666. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  2667. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2668. &\mid& \key{\#t} \mid \key{\#f} \mid
  2669. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  2670. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2671. R_2 &::=& (\key{program} \; \Exp)
  2672. \end{array}
  2673. \]
  2674. \end{minipage}
  2675. }
  2676. \caption{The syntax of $R_2$, extending $R_1$ with Booleans and
  2677. conditionals.}
  2678. \label{fig:r2-syntax}
  2679. \end{figure}
  2680. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2681. the parts that are the same as the interpreter for $R_1$
  2682. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2683. simply evaluate to themselves. The conditional expression $(\key{if}\,
  2684. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  2685. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  2686. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  2687. operations \code{not} and \code{and} behave as you might expect, but
  2688. note that the \code{and} operation is short-circuiting. That is, given
  2689. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  2690. evaluated if $e_1$ evaluates to \code{\#f}.
  2691. With the addition of the comparison operations, there are quite a few
  2692. primitive operations and the interpreter code for them is somewhat
  2693. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2694. parts into the \code{interp-op} function and the similar parts into
  2695. the one match clause shown in Figure~\ref{fig:interp-R2}. It is
  2696. important for that match clause to come last because it matches
  2697. \emph{any} compound S-expression. We do not use \code{interp-op} for
  2698. the \code{and} operation because of the short-circuiting behavior in
  2699. the order of evaluation of its arguments.
  2700. \begin{figure}[tbp]
  2701. \begin{lstlisting}
  2702. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2703. (define (interp-op op)
  2704. (match op
  2705. ['+ fx+]
  2706. ['- (lambda (n) (fx- 0 n))]
  2707. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2708. ['read read-fixnum]
  2709. ['eq? (lambda (v1 v2)
  2710. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2711. (and (boolean? v1) (boolean? v2))
  2712. (and (vector? v1) (vector? v2)))
  2713. (eq? v1 v2)]))]
  2714. ['< (lambda (v1 v2)
  2715. (cond [(and (fixnum? v1) (fixnum? v2))
  2716. (< v1 v2)]))]
  2717. ['<= (lambda (v1 v2)
  2718. (cond [(and (fixnum? v1) (fixnum? v2))
  2719. (<= v1 v2)]))]
  2720. ['> (lambda (v1 v2)
  2721. (cond [(and (fixnum? v1) (fixnum? v2))
  2722. (<= v1 v2)]))]
  2723. ['>= (lambda (v1 v2)
  2724. (cond [(and (fixnum? v1) (fixnum? v2))
  2725. (<= v1 v2)]))]
  2726. [else (error 'interp-op "unknown operator")]))
  2727. (define (interp-R2 env)
  2728. (lambda (e)
  2729. (define recur (interp-R2 env))
  2730. (match e
  2731. ...
  2732. [(? boolean?) e]
  2733. [`(if ,(app recur cnd) ,thn ,els)
  2734. (match cnd
  2735. [#t (recur thn)]
  2736. [#f (recur els)])]
  2737. [`(not ,(app recur v))
  2738. (match v [#t #f] [#f #t])]
  2739. [`(and ,(app recur v1) ,e2)
  2740. (match v1
  2741. [#t (match (recur e2) [#t #t] [#f #f])]
  2742. [#f #f])]
  2743. [`(,op ,(app recur args) ...)
  2744. #:when (set-member? primitives op)
  2745. (apply (interp-op op) args)]
  2746. )))
  2747. \end{lstlisting}
  2748. \caption{Interpreter for the $R_2$ language.}
  2749. \label{fig:interp-R2}
  2750. \end{figure}
  2751. \section{Type Checking $R_2$ Programs}
  2752. \label{sec:type-check-r2}
  2753. It is helpful to think about type checking into two complementary
  2754. ways. A type checker predicts the \emph{type} of value that will be
  2755. produced by each expression in the program. For $R_2$, we have just
  2756. two types, \key{Integer} and \key{Boolean}. So a type checker should
  2757. predict that
  2758. \begin{lstlisting}
  2759. (+ 10 (- (+ 12 20)))
  2760. \end{lstlisting}
  2761. produces an \key{Integer} while
  2762. \begin{lstlisting}
  2763. (and (not #f) #t)
  2764. \end{lstlisting}
  2765. produces a \key{Boolean}.
  2766. As mentioned at the beginning of this chapter, a type checker also
  2767. rejects programs that apply operators to the wrong type of value. Our
  2768. type checker for $R_2$ will signal an error for the following
  2769. expression because, as we have seen above, the expression \code{(+ 10
  2770. ...)} has type \key{Integer}, and we require the argument of a
  2771. \code{not} to have type \key{Boolean}.
  2772. \begin{lstlisting}
  2773. (not (+ 10 (- (+ 12 20))))
  2774. \end{lstlisting}
  2775. The type checker for $R_2$ is best implemented as a structurally
  2776. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  2777. many of the clauses for the \code{typecheck-R2} function. Given an
  2778. input expression \code{e}, the type checker either returns the type
  2779. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  2780. the type of an integer literal is \code{Integer} and the type of a
  2781. Boolean literal is \code{Boolean}. To handle variables, the type
  2782. checker, like the interpreter, uses an association list. However, in
  2783. this case the association list maps variables to types instead of
  2784. values. Consider the clause for \key{let}. We type check the
  2785. initializing expression to obtain its type \key{T} and then associate
  2786. type \code{T} with the variable \code{x}. When the type checker
  2787. encounters the use of a variable, it can lookup its type in the
  2788. association list.
  2789. \begin{figure}[tbp]
  2790. \begin{lstlisting}
  2791. (define (typecheck-R2 env)
  2792. (lambda (e)
  2793. (define recur (typecheck-R2 env e))
  2794. (match e
  2795. [(? fixnum?) 'Integer]
  2796. [(? boolean?) 'Boolean]
  2797. [(? symbol?) (lookup e env)]
  2798. [`(let ([,x ,(app recur T)]) ,body)
  2799. (define new-env (cons (cons x T) env))
  2800. (typecheck-R2 new-env body)]
  2801. ...
  2802. [`(not ,(app (typecheck-R2 env) T))
  2803. (match T
  2804. ['Boolean 'Boolean]
  2805. [else (error 'typecheck-R2 "'not' expects a Boolean" e)])]
  2806. ...
  2807. [`(program ,body)
  2808. (define ty ((typecheck-R2 '()) body))
  2809. `(program (type ,ty) ,body)]
  2810. )))
  2811. \end{lstlisting}
  2812. \caption{Skeleton of a type checker for the $R_2$ language.}
  2813. \label{fig:type-check-R2}
  2814. \end{figure}
  2815. To print the resulting value correctly, the overall type of the
  2816. program must be threaded through the remainder of the passes. We can
  2817. store the type within the \key{program} form as shown in Figure
  2818. \ref{fig:type-check-R2}. The syntax for post-typechecking $R_2$
  2819. programs as follows: \\
  2820. \fbox{
  2821. \begin{minipage}{0.87\textwidth}
  2822. \[
  2823. \begin{array}{lcl}
  2824. R_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  2825. \end{array}
  2826. \]
  2827. \end{minipage}
  2828. }
  2829. \begin{exercise}\normalfont
  2830. Complete the implementation of \code{typecheck-R2} and test it on 10
  2831. new example programs in $R_2$ that you choose based on how thoroughly
  2832. they test the type checking algorithm. Half of the example programs
  2833. should have a type error, to make sure that your type checker properly
  2834. rejects them. The other half of the example programs should not have
  2835. type errors. Your testing should check that the result of the type
  2836. checker agrees with the value returned by the interpreter, that is, if
  2837. the type checker returns \key{Integer}, then the interpreter should
  2838. return an integer. Likewise, if the type checker returns
  2839. \key{Boolean}, then the interpreter should return \code{\#t} or
  2840. \code{\#f}. Note that if your type checker does not signal an error
  2841. for a program, then interpreting that program should not encounter an
  2842. error. If it does, there is something wrong with your type checker.
  2843. \end{exercise}
  2844. \section{The $C_1$ Language}
  2845. \label{sec:c1}
  2846. The $R_2$ language adds Booleans and conditional expressions to $R_1$.
  2847. As with $R_1$, we shall compile to a C-like intermediate language, but
  2848. we need to grow that intermediate language to handle the new features
  2849. in $R_2$. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$;
  2850. we add logic and comparison operators to the $\Exp$ non-terminal, the
  2851. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal, and we
  2852. add an \key{if} statement. The \key{if} statement of $C_1$ includes an
  2853. \key{eq?} test, which is needed for improving code generation in
  2854. Section~\ref{sec:opt-if}. We do not include \key{and} in $C_1$
  2855. because it is not needed in the translation of the \key{and} of $R_2$.
  2856. \begin{figure}[tp]
  2857. \fbox{
  2858. \begin{minipage}{0.96\textwidth}
  2859. \[
  2860. \begin{array}{lcl}
  2861. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  2862. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2863. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  2864. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  2865. \Stmt &::=& \gray{\ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg}} \\
  2866. &\mid& \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} \\
  2867. C_1 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+})
  2868. \end{array}
  2869. \]
  2870. \end{minipage}
  2871. }
  2872. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  2873. \label{fig:c1-syntax}
  2874. \end{figure}
  2875. \section{Flatten Expressions}
  2876. \label{sec:flatten-r2}
  2877. We expand the \code{flatten} pass to handle the Boolean literals
  2878. \key{\#t} and \key{\#f}, the new logic and comparison operations, and
  2879. \key{if} expressions. We shall start with a simple example of
  2880. translating a \key{if} expression, shown below on the left. \\
  2881. \begin{tabular}{lll}
  2882. \begin{minipage}{0.4\textwidth}
  2883. \begin{lstlisting}
  2884. (program (if #f 0 42))
  2885. \end{lstlisting}
  2886. \end{minipage}
  2887. &
  2888. $\Rightarrow$
  2889. &
  2890. \begin{minipage}{0.4\textwidth}
  2891. \begin{lstlisting}
  2892. (program (if.1)
  2893. (if (eq? #t #f)
  2894. ((assign if.1 0))
  2895. ((assign if.1 42)))
  2896. (return if.1))
  2897. \end{lstlisting}
  2898. \end{minipage}
  2899. \end{tabular} \\
  2900. The value of the \key{if} expression is the value of the branch that
  2901. is selected. Recall that in the \code{flatten} pass we need to replace
  2902. arbitrary expressions with $\Arg$'s (variables or literals). In the
  2903. translation above, on the right, we have replaced the \key{if}
  2904. expression with a new variable \key{if.1}, inside \code{(return
  2905. if.1)}, and we have produced code that will assign the appropriate
  2906. value to \key{if.1} using an \code{if} statement prior to the
  2907. \code{return}. For $R_1$, the \code{flatten} pass returned a list of
  2908. assignment statements. Here, for $R_2$, we return a list of statements
  2909. that can include both \key{if} statements and assignment statements.
  2910. The next example is a bit more involved, showing what happens when
  2911. there are complex expressions (not variables or literals) in the
  2912. condition and branch expressions of an \key{if}, including nested
  2913. \key{if} expressions.
  2914. \begin{tabular}{lll}
  2915. \begin{minipage}{0.4\textwidth}
  2916. \begin{lstlisting}
  2917. (program
  2918. (if (eq? (read) 0)
  2919. 777
  2920. (+ 2 (if (eq? (read) 0)
  2921. 40
  2922. 444))))
  2923. \end{lstlisting}
  2924. \end{minipage}
  2925. &
  2926. $\Rightarrow$
  2927. &
  2928. \begin{minipage}{0.4\textwidth}
  2929. \begin{lstlisting}
  2930. (program (t.1 t.2 if.1 t.3 t.4
  2931. if.2 t.5)
  2932. (assign t.1 (read))
  2933. (assign t.2 (eq? t.1 0))
  2934. (if (eq? #t t.2)
  2935. ((assign if.1 777))
  2936. ((assign t.3 (read))
  2937. (assign t.4 (eq? t.3 0))
  2938. (if (eq? #t t.4)
  2939. ((assign if.2 40))
  2940. ((assign if.2 444)))
  2941. (assign t.5 (+ 2 if.2))
  2942. (assign if.1 t.5)))
  2943. (return if.1))
  2944. \end{lstlisting}
  2945. \end{minipage}
  2946. \end{tabular} \\
  2947. The \code{flatten} clauses for the Boolean literals and the operations
  2948. \key{not} and \key{eq?} are straightforward. However, the
  2949. \code{flatten} clause for \key{and} requires some care to properly
  2950. imitate the order of evaluation of the interpreter for $R_2$
  2951. (Figure~\ref{fig:interp-R2}). We recommend using an \key{if} statement
  2952. in the code you generate for \key{and}.
  2953. The \code{flatten} clause for \key{if} also requires some care because
  2954. the condition of the \key{if} can be an arbitrary expression in $R_2$,
  2955. but in $C_1$ the condition must be an equality predicate. For now we
  2956. recommend flattening the condition into an $\Arg$ and then comparing
  2957. it with \code{\#t}. We discuss a more efficient approach in
  2958. Section~\ref{sec:opt-if}.
  2959. \begin{exercise}\normalfont
  2960. Expand your \code{flatten} pass to handle $R_2$, that is, handle the
  2961. Boolean literals, the new logic and comparison operations, and the
  2962. \key{if} expressions. Create 4 more test cases that expose whether
  2963. your flattening code is correct. Test your \code{flatten} pass by
  2964. running the output programs with \code{interp-C}
  2965. (Appendix~\ref{appendix:interp}).
  2966. \end{exercise}
  2967. \section{XOR, Comparisons, and Control Flow in x86}
  2968. \label{sec:x86-1}
  2969. To implement the new logical operations, the comparison operations,
  2970. and the \key{if} statement, we need to delve further into the x86
  2971. language. Figure~\ref{fig:x86-2} defines the abstract syntax for a
  2972. larger subset of x86 that includes instructions for logical
  2973. operations, comparisons, and jumps.
  2974. One small challenge is that x86 does not provide an instruction that
  2975. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  2976. However, the \code{xorq} instruction can be used to encode \code{not}.
  2977. The \key{xorq} instruction takes two arguments, performs a pairwise
  2978. exclusive-or operation on each bit of its arguments, and writes the
  2979. results into its second argument. Recall the truth table for
  2980. exclusive-or:
  2981. \begin{center}
  2982. \begin{tabular}{l|cc}
  2983. & 0 & 1 \\ \hline
  2984. 0 & 0 & 1 \\
  2985. 1 & 1 & 0
  2986. \end{tabular}
  2987. \end{center}
  2988. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  2989. in row of the table for the bit $1$, the result is the opposite of the
  2990. second bit. Thus, the \code{not} operation can be implemented by
  2991. \code{xorq} with $1$ as the first argument: $0001
  2992. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  2993. 0001 = 0000$.
  2994. \begin{figure}[tp]
  2995. \fbox{
  2996. \begin{minipage}{0.96\textwidth}
  2997. \[
  2998. \begin{array}{lcl}
  2999. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3000. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3001. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3002. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3003. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3004. (\key{subq} \; \Arg\; \Arg) \mid
  3005. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3006. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3007. (\key{pushq}\;\Arg) \mid
  3008. (\key{popq}\;\Arg) \mid
  3009. (\key{retq})} \\
  3010. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3011. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3012. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3013. \mid (\key{jmp} \; \itm{label})
  3014. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3015. &\mid& (\key{label} \; \itm{label}) \\
  3016. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3017. \end{array}
  3018. \]
  3019. \end{minipage}
  3020. }
  3021. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3022. \label{fig:x86-1}
  3023. \end{figure}
  3024. Next we consider the x86 instructions that are relevant for
  3025. compiling the comparison operations. The \key{cmpq} instruction
  3026. compares its two arguments to determine whether one argument is less
  3027. than, equal, or greater than the other argument. The \key{cmpq}
  3028. instruction is unusual regarding the order of its arguments and where
  3029. the result is placed. The argument order is backwards: if you want to
  3030. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3031. \key{cmpq} is placed in the special EFLAGS register. This register
  3032. cannot be accessed directly but it can be queried by a number of
  3033. instructions, including the \key{set} instruction. The \key{set}
  3034. instruction puts a \key{1} or \key{0} into its destination depending
  3035. on whether the comparison came out according to the condition code
  3036. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3037. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3038. The set instruction has an annoying quirk in that its destination
  3039. argument must be single byte register, such as \code{al}, which is
  3040. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3041. instruction can then be used to move from a single byte register to a
  3042. normal 64-bit register.
  3043. For compiling the \key{if} expression, the x86 instructions for
  3044. jumping are relevant. The \key{jmp} instruction updates the program
  3045. counter to point to the instruction after the indicated label. The
  3046. \key{jmp-if} instruction updates the program counter to point to the
  3047. instruction after the indicated label depending on whether the result
  3048. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3049. the \key{jmp-if} instruction falls through to the next
  3050. instruction. Our abstract syntax for \key{jmp-if} differs from the
  3051. concrete syntax for x86 to separate the instruction name from the
  3052. condition code. For example, \code{(jmp-if le foo)} corresponds to
  3053. \code{jle foo}.
  3054. \section{Select Instructions}
  3055. \label{sec:select-r2}
  3056. The \code{select-instructions} pass lowers from $C_1$ to another
  3057. intermediate representation suitable for conducting register
  3058. allocation, that is, a language close to x86$_1$.
  3059. We can take the usual approach of encoding Booleans as integers, with
  3060. true as 1 and false as 0.
  3061. \[
  3062. \key{\#t} \Rightarrow \key{1}
  3063. \qquad
  3064. \key{\#f} \Rightarrow \key{0}
  3065. \]
  3066. The \code{not} operation can be implemented in terms of \code{xorq}
  3067. as we discussed at the beginning of this section.
  3068. %% Can you think of a bit pattern that, when XOR'd with the bit
  3069. %% representation of 0 produces 1, and when XOR'd with the bit
  3070. %% representation of 1 produces 0?
  3071. Translating the \code{eq?} and the other comparison operations to x86
  3072. is slightly involved due to the unusual nature of the \key{cmpq}
  3073. instruction discussed above. We recommend translating an assignment
  3074. from \code{eq?} into the following sequence of three instructions. \\
  3075. \begin{tabular}{lll}
  3076. \begin{minipage}{0.4\textwidth}
  3077. \begin{lstlisting}
  3078. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3079. \end{lstlisting}
  3080. \end{minipage}
  3081. &
  3082. $\Rightarrow$
  3083. &
  3084. \begin{minipage}{0.4\textwidth}
  3085. \begin{lstlisting}
  3086. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3087. (set e (byte-reg al))
  3088. (movzbq (byte-reg al) |$\itm{lhs}$|)
  3089. \end{lstlisting}
  3090. \end{minipage}
  3091. \end{tabular} \\
  3092. % The translation of the \code{not} operator is not quite as simple
  3093. % as it seems. Recall that \key{notq} is a bitwise operator, not a boolean
  3094. % one. For example, the following program performs bitwise negation on
  3095. % the integer 1:
  3096. %
  3097. % \begin{tabular}{lll}
  3098. % \begin{minipage}{0.4\textwidth}
  3099. % \begin{lstlisting}
  3100. % (movq (int 1) (reg rax))
  3101. % (notq (reg rax))
  3102. % \end{lstlisting}
  3103. % \end{minipage}
  3104. % \end{tabular}
  3105. %
  3106. % After the program is run, \key{rax} does not contain 0, as you might
  3107. % hope -- it contains the binary value $111\ldots10$, which is the
  3108. % two's complement representation of $-2$. We recommend implementing boolean
  3109. % not by using \key{notq} and then masking the upper bits of the result with
  3110. % the \key{andq} instruction.
  3111. Regarding \key{if} statements, we recommend delaying when they are
  3112. lowered until the \code{patch-instructions} pass. The reason is that
  3113. for purposes of liveness analysis, \key{if} statements are easier to
  3114. deal with than jump instructions.
  3115. \begin{exercise}\normalfont
  3116. Expand your \code{select-instructions} pass to handle the new features
  3117. of the $R_2$ language. Test the pass on all the examples you have
  3118. created and make sure that you have some test programs that use the
  3119. \code{eq?} operator, creating some if necessary. Test the output of
  3120. \code{select-instructions} using the \code{interp-x86} interpreter
  3121. (Appendix~\ref{appendix:interp}).
  3122. \end{exercise}
  3123. \section{Register Allocation}
  3124. \label{sec:register-allocation-r2}
  3125. The changes required for $R_2$ affect the liveness analysis, building
  3126. the interference graph, and assigning homes, but the graph coloring
  3127. algorithm itself does not need to change.
  3128. \subsection{Liveness Analysis}
  3129. \label{sec:liveness-analysis-r2}
  3130. The addition of \key{if} statements brings up an interesting issue in
  3131. liveness analysis. Recall that liveness analysis works backwards
  3132. through the program, for each instruction it computes the variables
  3133. that are live before the instruction based on which variables are live
  3134. after the instruction. Now consider the situation for \code{(\key{if}
  3135. (\key{eq?} $e_1$ $e_2$) $\itm{thns}$ $\itm{elss}$)}, where we know
  3136. the $L_{\mathsf{after}}$ set and we need to produce the
  3137. $L_{\mathsf{before}}$ set. We can recursively perform liveness
  3138. analysis on the $\itm{thns}$ and $\itm{elss}$ branches, using
  3139. $L_{\mathsf{after}}$ as the starting point, to obtain
  3140. $L^{\mathsf{thns}}_{\mathsf{before}}$ and
  3141. $L^{\mathsf{elss}}_{\mathsf{before}}$ respectively. However, we do not
  3142. know, during compilation, which way the branch will go, so we do not
  3143. know whether to use $L^{\mathsf{thns}}_{\mathsf{before}}$ or
  3144. $L^{\mathsf{elss}}_{\mathsf{before}}$ as the $L_{\mathsf{before}}$ for
  3145. the entire \key{if} statement. The solution comes from the observation
  3146. that there is no harm in identifying more variables as live than
  3147. absolutely necessary. Thus, we can take the union of the live
  3148. variables from the two branches to be the live set for the whole
  3149. \key{if}, as shown below. Of course, we also need to include the
  3150. variables that are read in $e_1$ and $e_2$.
  3151. \[
  3152. L_{\mathsf{before}} = L^{\mathsf{thns}}_{\mathsf{before}} \cup
  3153. L^{\mathsf{elss}}_{\mathsf{before}} \cup
  3154. \mathit{Vars}(e_1) \cup \mathit{Vars}(e_2)
  3155. \]
  3156. We need the live-after sets for all the instructions in both branches
  3157. of the \key{if} when we build the interference graph, so I recommend
  3158. storing that data in the \key{if} statement AST as follows:
  3159. \begin{lstlisting}
  3160. (if (eq? |$e_1$| |$e_2$|) |$\itm{thns}$| |$\itm{thn{-}lives}$| |$\itm{elss}$| |$\itm{els{-}lives}$|)
  3161. \end{lstlisting}
  3162. If you wrote helper functions for computing the variables in an
  3163. instruction's argument and for computing the variables read-from ($R$)
  3164. or written-to ($W$) by an instruction, you need to be update them to
  3165. handle the new kinds of arguments and instructions in x86$_1$.
  3166. \subsection{Build Interference}
  3167. \label{sec:build-interference-r2}
  3168. Many of the new instructions, such as the logical operations, can be
  3169. handled in the same way as the arithmetic instructions. Thus, if your
  3170. code was already quite general, it will not need to be changed to
  3171. handle the logical operations. If not, I recommend that you change
  3172. your code to be more general. The \key{movzbq} instruction should be
  3173. handled like the \key{movq} instruction. The \key{if} statement is
  3174. straightforward to handle because we stored the live-after sets for
  3175. the two branches in the AST node as described above. Here we just need
  3176. to recursively process the two branches. The output of this pass can
  3177. discard the live after sets, as they are no longer needed.
  3178. \subsection{Assign Homes}
  3179. \label{sec:assign-homes-r2}
  3180. The \code{assign-homes} function (Section~\ref{sec:assign-s0}) needs
  3181. to be updated to handle the \key{if} statement, simply by recursively
  3182. processing the child nodes. Hopefully your code already handles the
  3183. other new instructions, but if not, you can generalize your code.
  3184. \begin{exercise}\normalfont
  3185. Implement the additions to the \code{register-allocation} pass so that
  3186. it works for $R_2$ and test your compiler using your previously
  3187. created programs on the \code{interp-x86} interpreter
  3188. (Appendix~\ref{appendix:interp}).
  3189. \end{exercise}
  3190. \section{Lower Conditionals (New Pass)}
  3191. \label{sec:lower-conditionals}
  3192. In the \code{select-instructions} pass we decided to procrastinate in
  3193. the lowering of the \key{if} statement, thereby making liveness
  3194. analysis easier. Now we need to make up for that and turn the \key{if}
  3195. statement into the appropriate instruction sequence. The following
  3196. translation gives the general idea. If the condition is true, we need
  3197. to execute the $\itm{thns}$ branch and otherwise we need to execute
  3198. the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3199. jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3200. is appropriate for the comparison operator \itm{cmp}. If the
  3201. condition is false, we fall through to the $\itm{elss}$ branch. At the
  3202. end of the $\itm{elss}$ branch we need to take care to not fall
  3203. through to the $\itm{thns}$ branch. So we jump to the
  3204. $\itm{endlabel}$. All of the labels in the generated code should be
  3205. created with \code{gensym}.
  3206. \begin{tabular}{lll}
  3207. \begin{minipage}{0.4\textwidth}
  3208. \begin{lstlisting}
  3209. (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3210. \end{lstlisting}
  3211. \end{minipage}
  3212. &
  3213. $\Rightarrow$
  3214. &
  3215. \begin{minipage}{0.4\textwidth}
  3216. \begin{lstlisting}
  3217. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3218. (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3219. |$\itm{elss}$|
  3220. (jmp |$\itm{endlabel}$|)
  3221. (label |$\itm{thenlabel}$|)
  3222. |$\itm{thns}$|
  3223. (label |$\itm{endlabel}$|)
  3224. \end{lstlisting}
  3225. \end{minipage}
  3226. \end{tabular}
  3227. \begin{exercise}\normalfont
  3228. Implement the \code{lower-conditionals} pass. Test your compiler using
  3229. your previously created programs on the \code{interp-x86} interpreter
  3230. (Appendix~\ref{appendix:interp}).
  3231. \end{exercise}
  3232. \section{Patch Instructions}
  3233. There are no special restrictions on the instructions \key{jmp-if},
  3234. \key{jmp}, and \key{label}, but there is an unusual restriction on
  3235. \key{cmpq}. The second argument is not allowed to be an immediate
  3236. value (such as a literal integer). If you are comparing two
  3237. immediates, you must insert another \key{movq} instruction to put the
  3238. second argument in \key{rax}.
  3239. \begin{exercise}\normalfont
  3240. Update \code{patch-instructions} to handle the new x86 instructions.
  3241. Test your compiler using your previously created programs on the
  3242. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3243. \end{exercise}
  3244. \section{An Example Translation}
  3245. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3246. $R_2$ translated to x86, showing the results of \code{flatten},
  3247. \code{select-instructions}, and the final x86 assembly.
  3248. \begin{figure}[tbp]
  3249. \begin{tabular}{lll}
  3250. \begin{minipage}{0.5\textwidth}
  3251. \begin{lstlisting}
  3252. (program
  3253. (if (eq? (read) 1) 42 0))
  3254. \end{lstlisting}
  3255. $\Downarrow$
  3256. \begin{lstlisting}
  3257. (program (t.1 t.2 if.1)
  3258. (assign t.1 (read))
  3259. (assign t.2 (eq? t.1 1))
  3260. (if (eq? #t t.2)
  3261. ((assign if.1 42))
  3262. ((assign if.1 0)))
  3263. (return if.1))
  3264. \end{lstlisting}
  3265. $\Downarrow$
  3266. \begin{lstlisting}
  3267. (program (t.1 t.2 if.1)
  3268. (callq read_int)
  3269. (movq (reg rax) (var t.1))
  3270. (cmpq (int 1) (var t.1))
  3271. (set e (byte-reg al))
  3272. (movzbq (byte-reg al) (var t.2))
  3273. (if (eq? (int 1) (var t.2))
  3274. ((movq (int 42) (var if.1)))
  3275. ((movq (int 0) (var if.1))))
  3276. (movq (var if.1) (reg rax)))
  3277. \end{lstlisting}
  3278. \end{minipage}
  3279. &
  3280. $\Rightarrow$
  3281. \begin{minipage}{0.4\textwidth}
  3282. \begin{lstlisting}
  3283. .globl _main
  3284. _main:
  3285. pushq %rbp
  3286. movq %rsp, %rbp
  3287. pushq %r15
  3288. pushq %r14
  3289. pushq %r13
  3290. pushq %r12
  3291. pushq %rbx
  3292. subq $8, %rsp
  3293. callq _read_int
  3294. movq %rax, %rcx
  3295. cmpq $1, %rcx
  3296. sete %al
  3297. movzbq %al, %rcx
  3298. cmpq $1, %rcx
  3299. je then21288
  3300. movq $0, %rbx
  3301. jmp if_end21289
  3302. then21288:
  3303. movq $42, %rbx
  3304. if_end21289:
  3305. movq %rbx, %rax
  3306. movq %rax, %rdi
  3307. callq _print_int
  3308. movq $0, %rax
  3309. addq $8, %rsp
  3310. popq %rbx
  3311. popq %r12
  3312. popq %r13
  3313. popq %r14
  3314. popq %r15
  3315. popq %rbp
  3316. retq
  3317. \end{lstlisting}
  3318. \end{minipage}
  3319. \end{tabular}
  3320. \caption{Example compilation of an \key{if} expression to x86.}
  3321. \label{fig:if-example-x86}
  3322. \end{figure}
  3323. \begin{figure}[p]
  3324. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3325. \node (R1) at (0,2) {\large $R_1$};
  3326. \node (R1-2) at (3,2) {\large $R_1$};
  3327. \node (R1-3) at (6,2) {\large $R_1$};
  3328. \node (C1-1) at (3,0) {\large $C_1$};
  3329. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3330. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3331. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3332. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  3333. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  3334. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3335. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3336. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R1-2);
  3337. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize uniquify} (R1-3);
  3338. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize\color{red} flatten} (C1-1);
  3339. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3340. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3341. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3342. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3343. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} lower-cond.} (x86-4);
  3344. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-5);
  3345. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  3346. \end{tikzpicture}
  3347. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3348. \label{fig:R2-passes}
  3349. \end{figure}
  3350. Figure~\ref{fig:R2-passes} gives an overview of all the passes needed
  3351. for the compilation of $R_2$.
  3352. \section{Challenge: Optimizing Conditions$^{*}$}
  3353. \label{sec:opt-if}
  3354. A close inspection of the x86 code generated in
  3355. Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3356. regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3357. twice using \key{cmpq} as follows.
  3358. % Wierd LaTeX bug if I remove the following. -Jeremy
  3359. % Does it have to do with page breaks?
  3360. \begin{lstlisting}
  3361. \end{lstlisting}
  3362. \begin{lstlisting}
  3363. cmpq $1, %rcx
  3364. sete %al
  3365. movzbq %al, %rcx
  3366. cmpq $1, %rcx
  3367. je then21288
  3368. \end{lstlisting}
  3369. The reason for this non-optimal code has to do with the \code{flatten}
  3370. pass earlier in this Chapter. We recommended flattening the condition
  3371. to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3372. is already an \code{eq?} test, then we would like to use that
  3373. directly. In fact, for many of the expressions of Boolean type, we can
  3374. generate more optimized code. For example, if the condition is
  3375. \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3376. all. If the condition is a \code{let}, we can optimize based on the
  3377. form of its body. If the condition is a \code{not}, then we can flip
  3378. the two branches.
  3379. %
  3380. \marginpar{\tiny We could do even better by converting to basic
  3381. blocks.\\ --Jeremy}
  3382. %
  3383. On the other hand, if the condition is a \code{and}
  3384. or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3385. code duplication.
  3386. Figure~\ref{fig:opt-if} shows an example program and the result of
  3387. applying the above suggested optimizations.
  3388. \begin{exercise}\normalfont
  3389. Change the \code{flatten} pass to improve the code that gets
  3390. generated for \code{if} expressions. We recommend writing a helper
  3391. function that recursively traverses the condition of the \code{if}.
  3392. \end{exercise}
  3393. \begin{figure}[tbp]
  3394. \begin{tabular}{lll}
  3395. \begin{minipage}{0.5\textwidth}
  3396. \begin{lstlisting}
  3397. (program
  3398. (if (let ([x 1])
  3399. (not (eq? 2 x)))
  3400. 42
  3401. 777))
  3402. \end{lstlisting}
  3403. $\Downarrow$
  3404. \begin{lstlisting}
  3405. (program (x.1 t.1 if.1)
  3406. (assign x.1 1)
  3407. (assign t.1 (read))
  3408. (if (eq? x.1 t.1)
  3409. ((assign if.1 42))
  3410. ((assign if.1 777)))
  3411. (return if.1))
  3412. \end{lstlisting}
  3413. $\Downarrow$
  3414. \begin{lstlisting}
  3415. (program (x.1 t.1 if.1)
  3416. (movq (int 1) (var x.1))
  3417. (callq read_int)
  3418. (movq (reg rax) (var t.1))
  3419. (if (eq? (var x.1) (var t.1))
  3420. ((movq (int 42) (var if.1)))
  3421. ((movq (int 777) (var if.1))))
  3422. (movq (var if.1) (reg rax)))
  3423. \end{lstlisting}
  3424. \end{minipage}
  3425. &
  3426. $\Rightarrow$
  3427. \begin{minipage}{0.4\textwidth}
  3428. \begin{lstlisting}
  3429. .globl _main
  3430. _main:
  3431. pushq %rbp
  3432. movq %rsp, %rbp
  3433. pushq %r15
  3434. pushq %r14
  3435. pushq %r13
  3436. pushq %r12
  3437. pushq %rbx
  3438. subq $8, %rsp
  3439. movq $1, %rbx
  3440. callq _read_int
  3441. movq %rax, %rcx
  3442. cmpq %rbx, %rcx
  3443. je then21288
  3444. movq $777, %r12
  3445. jmp if_end21289
  3446. then21288:
  3447. movq $42, %r12
  3448. if_end21289:
  3449. movq %r12, %rax
  3450. movq %rax, %rdi
  3451. callq _print_int
  3452. movq $0, %rax
  3453. addq $8, %rsp
  3454. popq %rbx
  3455. popq %r12
  3456. popq %r13
  3457. popq %r14
  3458. popq %r15
  3459. popq %rbp
  3460. retq
  3461. \end{lstlisting}
  3462. \end{minipage}
  3463. \end{tabular}
  3464. \caption{Example program with optimized conditionals.}
  3465. \label{fig:opt-if}
  3466. \end{figure}
  3467. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3468. \chapter{Tuples and Garbage Collection}
  3469. \label{ch:tuples}
  3470. \marginpar{\scriptsize To do: look through Andre's code comments for extra
  3471. things to discuss in this chapter. \\ --Jeremy}
  3472. \marginpar{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3473. all the IR grammars are spelled out! \\ --Jeremy}
  3474. \marginpar{\scriptsize Introduce has-type, but after flatten, remove it,
  3475. but keep type annotations on vector creation and local variables, function
  3476. parameters, etc. \\ --Jeremy}
  3477. In this chapter we study the implementation of mutable tuples (called
  3478. ``vectors'' in Racket). This language feature is the first to use the
  3479. computer's \emph{heap} because the lifetime of a Racket tuple is
  3480. indefinite, that is, a tuple does not follow a stack (FIFO) discipline
  3481. but instead lives forever from the programmer's viewpoint. Of course,
  3482. from an implementor's viewpoint, it is important to reclaim the space
  3483. associated with tuples when they are no longer needed, which is why we
  3484. also study \emph{garbage collection} techniques in this chapter.
  3485. Section~\ref{sec:r3} introduces the $R_3$ language including its
  3486. interpreter and type checker. The $R_3$ language extends the $R_2$
  3487. language of Chapter~\ref{ch:bool-types} with vectors and void values
  3488. (because the \code{vector-set!} operation returns a void
  3489. value). Section~\ref{sec:GC} describes a garbage collection algorithm
  3490. based on copying live objects back and forth between two halves of the
  3491. heap. The garbage collector requires coordination with the compiler so
  3492. that it can see all of the \emph{root} pointers, that is, pointers in
  3493. registers or on the procedure call stack.
  3494. Section~\ref{sec:code-generation-gc} discusses all the necessary
  3495. changes and additions to the compiler passes, including type checking,
  3496. instruction selection, register allocation, and a new compiler pass
  3497. named \code{expose-allocation}.
  3498. \section{The $R_3$ Language}
  3499. \label{sec:r3}
  3500. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  3501. includes three new forms for creating a tuple, reading an element of a
  3502. tuple, and writing to an element of a tuple. The program in
  3503. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  3504. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3505. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  3506. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  3507. ``then'' branch is taken. The element at index $0$ of \code{t} is
  3508. $40$, to which we add the $2$, the element at index $0$ of the
  3509. 1-tuple.
  3510. \begin{figure}[tbp]
  3511. \begin{lstlisting}
  3512. (let ([t (vector 40 #t (vector 2))])
  3513. (if (vector-ref t 1)
  3514. (+ (vector-ref t 0)
  3515. (vector-ref (vector-ref t 2) 0))
  3516. 44))
  3517. \end{lstlisting}
  3518. \caption{Example program that creates tuples and reads from them.}
  3519. \label{fig:vector-eg}
  3520. \end{figure}
  3521. \begin{figure}[tbp]
  3522. \centering
  3523. \fbox{
  3524. \begin{minipage}{0.96\textwidth}
  3525. \[
  3526. \begin{array}{lcl}
  3527. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  3528. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  3529. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  3530. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \\
  3531. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  3532. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  3533. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) }\\
  3534. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} } \\
  3535. &\mid& (\key{vector}\;\Exp^{+}) \mid
  3536. (\key{vector-ref}\;\Exp\;\Int) \\
  3537. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  3538. &\mid& (\key{void}) \\
  3539. R_3 &::=& (\key{program} \;(\key{type}\;\itm{type})\; \Exp)
  3540. \end{array}
  3541. \]
  3542. \end{minipage}
  3543. }
  3544. \caption{The syntax of $R_3$, extending $R_2$ with tuples.}
  3545. \label{fig:r3-syntax}
  3546. \end{figure}
  3547. Tuples are our first encounter with heap-allocated data, which raises
  3548. several interesting issues. First, variable binding performs a
  3549. shallow-copy when dealing with tuples, which means that different
  3550. variables can refer to the same tuple, i.e., different variables can
  3551. be \emph{aliases} for the same thing. Consider the following example
  3552. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  3553. the mutation through \code{t2} is visible when referencing the tuple
  3554. from \code{t1}, so the result of this program is \code{42}.
  3555. \begin{lstlisting}
  3556. (let ([t1 (vector 3 7)])
  3557. (let ([t2 t1])
  3558. (let ([_ (vector-set! t2 0 42)])
  3559. (vector-ref t1 0))))
  3560. \end{lstlisting}
  3561. The next issue concerns the lifetime of tuples. Of course, they are
  3562. created by the \code{vector} form, but when does their lifetime end?
  3563. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  3564. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  3565. is not tied to any notion of static scoping. For example, the
  3566. following program returns \code{3} even though the variable \code{t}
  3567. goes out of scope prior to accessing the vector.
  3568. \begin{lstlisting}
  3569. (vector-ref
  3570. (let ([t (vector 3 7)])
  3571. t)
  3572. 0)
  3573. \end{lstlisting}
  3574. From the perspective of programmer-observable behavior, tuples live
  3575. forever. Of course, if they really lived forever, then many programs
  3576. would run out of memory.\footnote{The $R_3$ language does not have
  3577. looping or recursive function, so it is nigh impossible to write a
  3578. program in $R_3$ that will run out of memory. However, we add
  3579. recursive functions in the next Chapter!} A Racket implementation
  3580. must therefore perform automatic garbage collection.
  3581. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  3582. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  3583. checker. The additions to the interpreter are straightforward but the
  3584. updates to the type checker deserve some explanation. As we shall see
  3585. in Section~\ref{sec:GC}, we need to know which variables are pointers
  3586. into the heap, that is, which variables are vectors. Also, when
  3587. allocating a vector, we shall need to know which elements of the
  3588. vector are pointers. We can obtain this information during type
  3589. checking and flattening. The type checker in
  3590. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  3591. expression, it also wraps every sub-expression $e$ with the form
  3592. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  3593. the flatten pass (Section~\ref{sec:flatten-gc}) this type information is
  3594. propagated to all variables (including temporaries generated during
  3595. flattening).
  3596. \begin{figure}[tbp]
  3597. \begin{lstlisting}
  3598. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  3599. (define (interp-op op)
  3600. (match op
  3601. ...
  3602. ['vector vector]
  3603. ['vector-ref vector-ref]
  3604. ['vector-set! vector-set!]
  3605. [else (error 'interp-op "unknown operator")]))
  3606. (define (interp-R3 env)
  3607. (lambda (e)
  3608. (match e
  3609. ...
  3610. [else (error 'interp-R3 "unrecognized expression")]
  3611. )))
  3612. \end{lstlisting}
  3613. \caption{Interpreter for the $R_3$ language.}
  3614. \label{fig:interp-R3}
  3615. \end{figure}
  3616. \begin{figure}[tbp]
  3617. \begin{lstlisting}
  3618. (define (typecheck-R3 env)
  3619. (lambda (e)
  3620. (match e
  3621. ...
  3622. ['(void) (values '(has-type (void) Void) 'Void)]
  3623. [`(vector ,(app (type-check env) e* t*) ...)
  3624. (let ([t `(Vector ,@t*)])
  3625. (values `(has-type (vector ,@e*) ,t) t))]
  3626. [`(vector-ref ,(app (type-check env) e t) ,i)
  3627. (match t
  3628. [`(Vector ,ts ...)
  3629. (unless (and (exact-nonnegative-integer? i)
  3630. (i . < . (length ts)))
  3631. (error 'type-check "invalid index ~a" i))
  3632. (let ([t (list-ref ts i)])
  3633. (values `(has-type (vector-ref ,e (has-type ,i Integer)) ,t)
  3634. t))]
  3635. [else (error "expected a vector in vector-ref, not" t)])]
  3636. [`(vector-set! ,(app (type-check env) e-vec^ t-vec) ,i
  3637. ,(app (type-check env) e-arg^ t-arg))
  3638. (match t-vec
  3639. [`(Vector ,ts ...)
  3640. (unless (and (exact-nonnegative-integer? i)
  3641. (i . < . (length ts)))
  3642. (error 'type-check "invalid index ~a" i))
  3643. (unless (equal? (list-ref ts i) t-arg)
  3644. (error 'type-check "type mismatch in vector-set! ~a ~a"
  3645. (list-ref ts i) t-arg))
  3646. (values `(has-type (vector-set! ,e-vec^
  3647. (has-type ,i Integer)
  3648. ,e-arg^) Void) 'Void)]
  3649. [else (error 'type-check
  3650. "expected a vector in vector-set!, not ~a" t-vec)])]
  3651. [`(eq? ,(app (type-check env) e1 t1)
  3652. ,(app (type-check env) e2 t2))
  3653. (match* (t1 t2)
  3654. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  3655. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  3656. [(other wise) ((super type-check env) e)])]
  3657. )))
  3658. \end{lstlisting}
  3659. \caption{Type checker for the $R_3$ language.}
  3660. \label{fig:typecheck-R3}
  3661. \end{figure}
  3662. \section{Garbage Collection}
  3663. \label{sec:GC}
  3664. Here we study a relatively simple algorithm for garbage collection
  3665. that is the basis of state-of-the-art garbage
  3666. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  3667. particular, we describe a two-space copying
  3668. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  3669. perform the
  3670. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  3671. coarse-grained depiction of what happens in a two-space collector,
  3672. showing two time steps, prior to garbage collection on the top and
  3673. after garbage collection on the bottom. In a two-space collector, the
  3674. heap is divided into two parts, the FromSpace and the
  3675. ToSpace. Initially, all allocations go to the FromSpace until there is
  3676. not enough room for the next allocation request. At that point, the
  3677. garbage collector goes to work to make more room.
  3678. The garbage collector must be careful not to reclaim tuples that will
  3679. be used by the program in the future. Of course, it is impossible in
  3680. general to predict what a program will do, but we can overapproximate
  3681. the will-be-used tuples by preserving all tuples that could be
  3682. accessed by \emph{any} program given the current computer state. A
  3683. program could access any tuple whose address is in a register or on
  3684. the procedure call stack. These addresses are called the \emph{root
  3685. set}. In addition, a program could access any tuple that is
  3686. transitively reachable from the root set. Thus, it is safe for the
  3687. garbage collector to reclaim the tuples that are not reachable in this
  3688. way.
  3689. %
  3690. \footnote{The sitation in Figure~\ref{fig:copying-collector}, with a
  3691. cycle, cannot be created by a well-typed program in $R_3$. However,
  3692. creating cycles will be possible once we get to $R_6$. We design
  3693. the garbage collector to deal with cycles to begin with, so we will
  3694. not need to revisit this issue.}
  3695. So the goal of the garbage collector is twofold:
  3696. \begin{enumerate}
  3697. \item preserve all tuple that are reachable from the root set via a
  3698. path of pointers, that is, the \emph{live} tuples, and
  3699. \item reclaim the memory of everything else, that is, the
  3700. \emph{garbage}.
  3701. \end{enumerate}
  3702. A copying collector accomplishes this by copying all of the live
  3703. objects into the ToSpace and then performs a slight of hand, treating
  3704. the ToSpace as the new FromSpace and the old FromSpace as the new
  3705. ToSpace. In the example of Figure~\ref{fig:copying-collector}, there
  3706. are three pointers in the root set, one in a register and two on the
  3707. stack. All of the live objects have been copied to the ToSpace (the
  3708. right-hand side of Figure~\ref{fig:copying-collector}) in a way that
  3709. preserves the pointer relationships. For example, the pointer in the
  3710. register still points to a 2-tuple whose first element is a 3-tuple
  3711. and second element is a 2-tuple. There are four tuples that are not
  3712. reachable from the root set and therefore do not get copied into the
  3713. ToSpace.
  3714. \begin{figure}[tbp]
  3715. \centering
  3716. \includegraphics[width=\textwidth]{copy-collect-1} \\[5ex]
  3717. \includegraphics[width=\textwidth]{copy-collect-2}
  3718. \caption{A copying collector in action.}
  3719. \label{fig:copying-collector}
  3720. \end{figure}
  3721. %% \marginpar{\tiny Need to add comment somewhere about the goodness
  3722. %% of copying collection, especially that it doesn't touch
  3723. %% the garbage, so its time complexity only depends on the
  3724. %% amount of live data.\\ --Jeremy}
  3725. There are many alternatives to copying collectors (and their older
  3726. siblings, the generational collectors) when its comes to garbage
  3727. collection, such as mark-and-sweep and reference counting. The
  3728. strengths of copying collectors are that allocation is fast (just a
  3729. test and pointer increment), there is no fragmentation, cyclic garbage
  3730. is collected, and the time complexity of collection only depends on
  3731. the amount of live data, and not on the amount of
  3732. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  3733. copying collectors is that they use a lot of space, though that
  3734. problem is ameliorated in generational collectors. Racket and Scheme
  3735. programs tend to allocate many small objects and generate a lot of
  3736. garbage, so copying and generational collectors are a good fit. Of
  3737. course, garbage collection is an active research topic, especially
  3738. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  3739. continuously developing new techniques and revisiting old
  3740. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  3741. \subsection{Graph Copying via Cheney's Algorithm}
  3742. \label{sec:cheney}
  3743. Let us take a closer look at how the copy works. The allocated objects
  3744. and pointers can be viewed as a graph and we need to copy the part of
  3745. the graph that is reachable from the root set. To make sure we copy
  3746. all of the reachable vertices in the graph, we need an exhaustive
  3747. graph traversal algorithm, such as depth-first search or breadth-first
  3748. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  3749. take into account the possibility of cycles by marking which vertices
  3750. have already been visited, so as to ensure termination of the
  3751. algorithm. These search algorithms also use a data structure such as a
  3752. stack or queue as a to-do list to keep track of the vertices that need
  3753. to be visited. We shall use breadth-first search and a trick due to
  3754. \citet{Cheney:1970aa} for simultaneously representing the queue and
  3755. copying tuples into the ToSpace.
  3756. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  3757. copy progresses. The queue is represented by a chunk of contiguous
  3758. memory at the beginning of the ToSpace, using two pointers to track
  3759. the front and the back of the queue. The algorithm starts by copying
  3760. all tuples that are immediately reachable from the root set into the
  3761. ToSpace to form the initial queue. When we copy a tuple, we mark the
  3762. old tuple to indicate that it has been visited. (We discuss the
  3763. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  3764. inside the copied tuples in the queue still point back to the
  3765. FromSpace. Once the initial queue has been created, the algorithm
  3766. enters a loop in which it repeatedly processes the tuple at the front
  3767. of the queue and pops it off the queue. To process a tuple, the
  3768. algorithm copies all the tuple that are directly reachable from it to
  3769. the ToSpace, placing them at the back of the queue. The algorithm then
  3770. updates the pointers in the popped tuple so they point to the newly
  3771. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  3772. step we copy the tuple whose second element is $42$ to the back of the
  3773. queue. The other pointer goes to a tuple that has already been copied,
  3774. so we do not need to copy it again, but we do need to update the
  3775. pointer to the new location. This can be accomplished by storing a
  3776. \emph{forwarding} pointer to the new location in the old tuple, back
  3777. when we initially copied the tuple into the ToSpace. This completes
  3778. one step of the algorithm. The algorithm continues in this way until
  3779. the front of the queue is empty, that is, until the front catches up
  3780. with the back.
  3781. \begin{figure}[tbp]
  3782. \centering \includegraphics[width=0.9\textwidth]{cheney}
  3783. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  3784. \label{fig:cheney}
  3785. \end{figure}
  3786. \subsection{Data Representation}
  3787. \label{sec:data-rep-gc}
  3788. The garbage collector places some requirements on the data
  3789. representations used by our compiler. First, the garbage collector
  3790. needs to distinguish between pointers and other kinds of data. There
  3791. are several ways to accomplish this.
  3792. \begin{enumerate}
  3793. \item Attached a tag to each object that identifies what type of
  3794. object it is~\citep{McCarthy:1960dz}.
  3795. \item Store different types of objects in different
  3796. regions~\citep{Steele:1977ab}.
  3797. \item Use type information from the program to either generate
  3798. type-specific code for collecting or to generate tables that can
  3799. guide the
  3800. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  3801. \end{enumerate}
  3802. Dynamically typed languages, such as Lisp, need to tag objects
  3803. anyways, so option 1 is a natural choice for those languages.
  3804. However, $R_3$ is a statically typed language, so it would be
  3805. unfortunate to require tags on every object, especially small and
  3806. pervasive objects like integers and Booleans. Option 3 is the
  3807. best-performing choice for statically typed languages, but comes with
  3808. a relatively high implementation complexity. To keep this chapter to a
  3809. 2-week time budget, we recommend a combination of options 1 and 2,
  3810. with separate strategies used for the stack and the heap.
  3811. Regarding the stack, we recommend using a separate stack for
  3812. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  3813. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  3814. local variable needs to be spilled and is of type \code{(Vector
  3815. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  3816. of the normal procedure call stack. Furthermore, we always spill
  3817. vector-typed variables if they are live during a call to the
  3818. collector, thereby ensuring that no pointers are in registers during a
  3819. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  3820. Figure~\ref{fig:copying-collector} and contrasts it with the data
  3821. layout using a root stack. The root stack contains the two pointers
  3822. from the regular stack and also the pointer in the second
  3823. register.
  3824. \begin{figure}[tbp]
  3825. \centering \includegraphics[width=0.7\textwidth]{root-stack}
  3826. \caption{Maintaining a root stack to facilitate garbage collection.}
  3827. \label{fig:shadow-stack}
  3828. \end{figure}
  3829. The problem of distinguishing between pointers and other kinds of data
  3830. also arises inside of each tuple. We solve this problem by attaching a
  3831. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  3832. in on the tags for two of the tuples in the example from
  3833. Figure~\ref{fig:copying-collector}. Part of each tag is dedicated to
  3834. specifying which elements of the tuple are pointers, the part labeled
  3835. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  3836. a pointer and a 0 bit indicates some other kind of data. The pointer
  3837. mask starts at bit location 7. We have limited tuples to a maximum
  3838. size of 50 elements, so we just need 50 bits for the pointer mask. The
  3839. tag also contains two other pieces of information. The length of the
  3840. tuple (number of elements) is stored in bits location 1 through
  3841. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  3842. to be copied to the FromSpace. If the bit has value 1, then this
  3843. tuple has not yet been copied. If the bit has value 0 then the entire
  3844. tag is in fact a forwarding pointer. (The lower 3 bits of an pointer
  3845. are always zero anyways because our tuples are 8-byte aligned.)
  3846. \begin{figure}[tbp]
  3847. \centering \includegraphics[width=0.8\textwidth]{tuple-rep}
  3848. \caption{Representation for tuples in the heap.}
  3849. \label{fig:tuple-rep}
  3850. \end{figure}
  3851. \subsection{Implementation of the Garbage Collector}
  3852. \label{sec:organize-gz}
  3853. The implementation of the garbage collector needs to do a lot of
  3854. bit-level data manipulation and we need to link it with our
  3855. compiler-generated x86 code. Thus, we recommend implementing the
  3856. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  3857. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  3858. interface to the garbage collector. The \code{initialize} function
  3859. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  3860. function is meant to be called near the beginning of \code{main},
  3861. before the rest of the program executes. The \code{initialize}
  3862. function puts the address of the beginning of the FromSpace into the
  3863. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  3864. points to the address that is 1-past the last element of the
  3865. FromSpace. (We use half-open intervals to represent chunks of
  3866. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  3867. points to the first element of the root stack.
  3868. As long as there is room left in the FromSpace, your generated code
  3869. can allocate tuples simply by moving the \code{free\_ptr} forward.
  3870. %
  3871. \marginpar{\tiny Should we dedicate a register to the free pointer? \\
  3872. --Jeremy}
  3873. %
  3874. The amount of room left in FromSpace is the difference between the
  3875. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  3876. function should be called when there is not enough room left in the
  3877. FromSpace for the next allocation. The \code{collect} function takes
  3878. a pointer to the current top of the root stack (one past the last item
  3879. that was pushed) and the number of bytes that need to be
  3880. allocated. The \code{collect} function performs the copying collection
  3881. and leaves the heap in a state such that the next allocation will
  3882. succeed.
  3883. \begin{figure}[tbp]
  3884. \begin{lstlisting}
  3885. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  3886. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  3887. int64_t* free_ptr;
  3888. int64_t* fromspace_begin;
  3889. int64_t* fromspace_end;
  3890. int64_t** rootstack_begin;
  3891. \end{lstlisting}
  3892. \caption{The compiler's interface to the garbage collector.}
  3893. \label{fig:gc-header}
  3894. \end{figure}
  3895. \begin{exercise}
  3896. In the file \code{runtime.c} you will find the implementation of
  3897. \code{initialize} and a partial implementation of \code{collect}.
  3898. The \code{collect} function calls another function, \code{cheney},
  3899. to perform the actual copy, and that function is left to the reader
  3900. to implement. The following is the prototype for \code{cheney}.
  3901. \begin{lstlisting}
  3902. static void cheney(int64_t** rootstack_ptr);
  3903. \end{lstlisting}
  3904. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  3905. rootstack (which is array of pointers). The \code{cheney} function
  3906. also communicates with \code{collect} through several global
  3907. variables, the \code{framespace\_begin} and \code{framespace\_end}
  3908. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  3909. the ToSpace:
  3910. \begin{lstlisting}
  3911. static int64_t* tospace_begin;
  3912. static int64_t* tospace_end;
  3913. \end{lstlisting}
  3914. The job of the \code{cheney} function is to copy all the live
  3915. objects (reachable from the root stack) into the ToSpace, update
  3916. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  3917. update the root stack so that it points to the objects in the
  3918. ToSpace, and finally to swap the global pointers for the FromSpace
  3919. and ToSpace.
  3920. \end{exercise}
  3921. \section{Compiler Passes}
  3922. \label{sec:code-generation-gc}
  3923. The introduction of garbage collection has a non-trivial impact on our
  3924. compiler passes. We introduce one new compiler pass called
  3925. \code{expose-allocation} and make non-trivial changes to
  3926. \code{type-check}, \code{flatten}, \code{select-instructions},
  3927. \code{allocate-registers}, and \code{print-x86}. The following
  3928. program will serve as our running example. It creates two tuples, one
  3929. nested inside the other. Both tuples have length one. The example then
  3930. accesses the element in the inner tuple tuple via two vector
  3931. references.
  3932. % tests/s2_17.rkt
  3933. \begin{lstlisting}
  3934. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  3935. \end{lstlisting}
  3936. We already discuss the changes to \code{type-check} in
  3937. Section~\ref{sec:r3}, including the addition of \code{has-type}, so we
  3938. proceed to discuss the new \code{expose-allocation} pass.
  3939. \subsection{Expose Allocation (New)}
  3940. \label{sec:expose-allocation}
  3941. The pass \code{expose-allocation} lowers the \code{vector} creation
  3942. form into a conditional call to the collector followed by the
  3943. allocation. In the following, we show the transformation for the
  3944. \code{vector} form into a conditional \code{collect} followed by
  3945. \code{allocate} and then the initialization of the vector. (The
  3946. \itm{len} is the length of the vector and \itm{bytes} is how many
  3947. total bytes need to be allocated for the vector, which is 8 for the
  3948. tag plus \itm{len} times 8.)
  3949. \begin{lstlisting}
  3950. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  3951. |$\Longrightarrow$|
  3952. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  3953. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  3954. (global-value fromspace_end))
  3955. (void)
  3956. (collect |\itm{bytes}|))])
  3957. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  3958. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  3959. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  3960. |$v$|) ... )))) ...)
  3961. \end{lstlisting}
  3962. (In the above, we suppressed all of the \code{has-type} forms in the
  3963. output for the sake of readability.)
  3964. The output of \code{expose-allocation} is a language that extends
  3965. $R_3$ with the three new forms that we use above in the translation of
  3966. \code{vector}.
  3967. \[
  3968. \begin{array}{lcl}
  3969. \Exp &::=& \cdots
  3970. \mid (\key{collect} \,\itm{int})
  3971. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  3972. \mid (\key{global-value} \,\itm{name})
  3973. \end{array}
  3974. \]
  3975. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  3976. %% the beginning of the program which will instruct the garbage collector
  3977. %% to set up the FromSpace, ToSpace, and all the global variables. The
  3978. %% two arguments of \code{initialize} specify the initial allocated space
  3979. %% for the root stack and for the heap.
  3980. %
  3981. %% The \code{expose-allocation} pass annotates all of the local variables
  3982. %% in the \code{program} form with their type.
  3983. Figure~\ref{fig:expose-alloc-output} shows the output of the
  3984. \code{expose-allocation} pass on our running example.
  3985. \begin{figure}[tbp]
  3986. \begin{lstlisting}
  3987. (program (type Integer)
  3988. (vector-ref
  3989. (vector-ref
  3990. (let ((vecinit32990
  3991. (let ([vecinit32986 42])
  3992. (let ((collectret32988
  3993. (if (< (+ (global-value free_ptr) 16)
  3994. (global-value fromspace_end))
  3995. (void)
  3996. (collect 16))))
  3997. (let ([alloc32985
  3998. (allocate 1 (Vector Integer))])
  3999. (let ([initret32987
  4000. (vector-set! alloc32985 0 vecinit32986)])
  4001. alloc32985))))))
  4002. (let ([collectret32992
  4003. (if (< (+ (global-value free_ptr) 16)
  4004. (global-value fromspace_end))
  4005. (void)
  4006. (collect 16))])
  4007. (let ([alloc32989 (allocate 1 (Vector (Vector Integer)))])
  4008. (let ([initret32991 (vector-set! alloc32989 0 vecinit32990)])
  4009. alloc32989))))
  4010. 0)
  4011. 0))
  4012. \end{lstlisting}
  4013. \caption{Output of the \code{expose-allocation} pass, minus
  4014. all of the \code{has-type} forms.}
  4015. \label{fig:expose-alloc-output}
  4016. \end{figure}
  4017. \clearpage
  4018. \subsection{Flatten and the $C_2$ intermediate language}
  4019. \label{sec:flatten-gc}
  4020. \begin{figure}[tp]
  4021. \fbox{
  4022. \begin{minipage}{0.96\textwidth}
  4023. \[
  4024. \begin{array}{lcl}
  4025. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4026. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4027. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4028. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4029. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4030. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4031. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4032. \mid (\key{global-value} \,\itm{name}) \\
  4033. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4034. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4035. &\mid& (\key{collect} \,\itm{int}) \\
  4036. C_2 & ::= & \gray{ (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+}) }
  4037. \end{array}
  4038. \]
  4039. \end{minipage}
  4040. }
  4041. \caption{The $C_2$ language, extending $C_1$ with support for tuples.}
  4042. \label{fig:c2-syntax}
  4043. \end{figure}
  4044. The output of \code{flatten} is a program in the intermediate language
  4045. $C_2$, whose syntax is defined in Figure~\ref{fig:c2-syntax}. The new
  4046. forms of $C_2$ include the expressions \key{allocate},
  4047. \key{vector-ref}, and \key{vector-set!}, and \key{global-value} and
  4048. the statement \code{collect}. The \code{flatten} pass can treat these
  4049. new forms much like the other forms.
  4050. Recall that the \code{flatten} function collects all of the local
  4051. variables so that it can decorate the \code{program} form with
  4052. them. Also recall that we need to know the types of all the local
  4053. variables for purposes of identifying the root set for the garbage
  4054. collector. Thus, we change \code{flatten} to collect not just the
  4055. variables, but the variables and their types in the form of an
  4056. association list. Thanks to the \code{has-type} forms, the types are
  4057. readily available. For example, consider the translation of the
  4058. \code{let} form.
  4059. \begin{lstlisting}
  4060. (let ([|$x$| (has-type |\itm{rhs}| |\itm{type}|)]) |\itm{body}|)
  4061. |$\Longrightarrow$|
  4062. |\itm{body'}|
  4063. (|\itm{ss_1}| (assign |$x$| |\itm{rhs'}|) |\itm{ss_2}|)
  4064. ((|$x$| . |\itm{type}|) |\itm{xt_1}| |\itm{xt_2}|)
  4065. \end{lstlisting}
  4066. where \itm{rhs'}, \itm{ss_1}, and \itm{xs_1} are the results of
  4067. recursively flattening \itm{rhs} and \itm{body'}, \itm{ss_2}, and
  4068. \itm{xs_2} are the results of recursively flattening \itm{body}. The
  4069. output on our running example is shown in Figure~\ref{fig:flatten-gc}.
  4070. \begin{figure}[tbp]
  4071. \begin{lstlisting}
  4072. '(program
  4073. ((tmp33002 . Integer) (tmp33001 Vector Integer) (vecinit32990 Vector Integer)
  4074. (vecinit32986 . Integer) (collectret32988 . Void) (if32996 . Void)
  4075. (tmp32994 . Integer) (global32993 . Integer) (global32995 . Integer)
  4076. (alloc32985 Vector Integer) (initret32987 . Void) (collectret32992 . Void)
  4077. (if33000 . Void) (tmp32998 . Integer) (global32997 . Integer)
  4078. (global32999 . Integer) (alloc32989 Vector (Vector Integer))
  4079. (initret32991 . Void))
  4080. (type Integer)
  4081. (assign vecinit32986 42)
  4082. (assign global32993 (global-value free_ptr))
  4083. (assign tmp32994 (+ global32993 16))
  4084. (assign global32995 (global-value fromspace_end))
  4085. (if (< tmp32994 global32995)
  4086. ((assign if32996 (void)))
  4087. ((collect 16) (assign if32996 (void))))
  4088. (assign collectret32988 if32996)
  4089. (assign alloc32985 (allocate 1 (Vector Integer)))
  4090. (assign initret32987 (vector-set! alloc32985 0 vecinit32986))
  4091. (assign vecinit32990 alloc32985)
  4092. (assign global32997 (global-value free_ptr))
  4093. (assign tmp32998 (+ global32997 16))
  4094. (assign global32999 (global-value fromspace_end))
  4095. (if (< tmp32998 global32999)
  4096. ((assign if33000 (void)))
  4097. ((collect 16) (assign if33000 (void))))
  4098. (assign collectret32992 if33000)
  4099. (assign alloc32989 (allocate 1 (Vector (Vector Integer))))
  4100. (assign initret32991 (vector-set! alloc32989 0 vecinit32990))
  4101. (assign tmp33001 (vector-ref alloc32989 0))
  4102. (assign tmp33002 (vector-ref tmp33001 0))
  4103. (return tmp33002))
  4104. \end{lstlisting}
  4105. \caption{Output of \code{flatten} for the running example.}
  4106. \label{fig:flatten-gc}
  4107. \end{figure}
  4108. \subsection{Select Instructions}
  4109. \label{sec:select-instructions-gc}
  4110. In this pass we generate the code for explicitly manipulating the root
  4111. stack, lower the forms needed for garbage collection, and also lower
  4112. the \code{vector-ref} and \code{vector-set!} forms. We shall use a
  4113. register, \code{r15}, to store the pointer to the top of the root
  4114. stack. (So \code{r15} is no longer available for use by the register
  4115. allocator.) For readability, we shall refer to this register as the
  4116. \emph{rootstack}.
  4117. %
  4118. We shall obtain the top of the root stack to begin with from the
  4119. global variable \code{rootstack\_begin}.
  4120. The translation of the \code{call-live-roots} introduces the code that
  4121. manipulates the root stack. We push all of the call-live roots onto
  4122. the root stack prior to the call to \code{collect} and we move them
  4123. back afterwards.
  4124. %
  4125. \marginpar{\tiny I would prefer to instead have roots live solely on
  4126. the root stack and in registers, not on the normal stack. Then we
  4127. would only need to push the roots in registers, decreasing memory
  4128. traffic for function calls. (to do: next year)\\ --Jeremy}
  4129. %
  4130. \begin{lstlisting}
  4131. (call-live-roots (|$x_0 \ldots x_{n-1}$|) (collect |$\itm{bytes}$|))
  4132. |$\Longrightarrow$|
  4133. (movq (var |$x_0$|) (deref |$\itm{rootstack}$| |$0$|))
  4134. |$\ldots$|
  4135. (movq (var |$x_{n-1}$|) (deref |$\itm{rootstack}$| |$8(n-1)$|))
  4136. (addq |$n$| (reg |$\itm{rootstack}$|))
  4137. (movq (reg |$\itm{rootstack}$|) (reg rdi))
  4138. (movq (int |$\itm{bytes}$|) (reg rsi))
  4139. (callq collect)
  4140. (subq |$n$| (reg |$\itm{rootstack}$|))
  4141. (movq (deref |$\itm{rootstack}$| |$0$|) (var |$x_0$|))
  4142. |$\ldots$|
  4143. (movq (deref |$\itm{rootstack}$| |$8(n-1)$|) (var |$x_{n-1}$|))
  4144. \end{lstlisting}
  4145. \noindent We simply translate \code{initialize} into a call to the
  4146. function in \code{runtime.c}.
  4147. \begin{lstlisting}
  4148. (initialize |$\itm{rootlen}\;\itm{heaplen}$|)
  4149. |$\Longrightarrow$|
  4150. (movq (int |\itm{rootlen}|) (reg rdi))
  4151. (movq (int |\itm{heaplen}|) (reg rsi))
  4152. (callq initialize)
  4153. (movq (global-value rootstack_begin) (reg |\itm{rootstack}|))
  4154. \end{lstlisting}
  4155. %
  4156. We translate the special \code{collection-needed?} predicate into code
  4157. that compares the \code{free\_ptr} to the \code{fromspace\_end}.
  4158. %
  4159. \begin{lstlisting}
  4160. (if (collection-needed? |$\itm{bytes}$|) |$\itm{thn}$| |$\itm{els}$|)
  4161. |$\Longrightarrow$|
  4162. (movq (global-value free_ptr) (var end-data.1))
  4163. (addq (int |$\itm{bytes}$|) (var end-data.1))
  4164. (if (< (var end-data.1) (global-value fromspace_end))
  4165. |$\itm{thn}'$|
  4166. |$\itm{els}'$|)
  4167. \end{lstlisting}
  4168. The \code{allocate} form translates to operations on the
  4169. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4170. is the next free address in the FromSpace, so we move it into the
  4171. \itm{lhs} and then move it forward by enough space for the vector
  4172. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  4173. is 8 bytes (64 bits) and we use 8 bytes for the tag. Last but not
  4174. least, we need to initialize the \itm{tag}. Refer to
  4175. Figure~\ref{fig:tuple-rep} to see how the tag is organized. We
  4176. recommend using the Racket operations \code{bitwise-ior} and
  4177. \code{arithmetic-shift} to compute the tag. The \itm{types} in the
  4178. \code{has-type } annotation can be used to determine
  4179. the pointer mask region of the tag. The move of $ \itm{lhs}^\prime $ to
  4180. register \code{r11}, before the move to the offset of \code{r11}
  4181. ensures that if $ \itm{lhs}^\prime $ offsets are only performed with
  4182. register operands.
  4183. \begin{lstlisting}
  4184. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{types}$|)))
  4185. |$\Longrightarrow$|
  4186. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4187. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4188. (movq |$\itm{lhs}'$| (reg r11))
  4189. (movq (int |$\itm{tag}$|) (deref r11 0))
  4190. \end{lstlisting}
  4191. The \code{vector-ref} and \code{vector-set!} forms translate into
  4192. \code{movq} instructions with the appropriate \key{deref}. (The
  4193. plus one is to get past the tag at the beginning of the tuple
  4194. representation.)
  4195. \begin{lstlisting}
  4196. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4197. |$\Longrightarrow$|
  4198. (movq |$\itm{vec}'$| (reg r11))
  4199. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4200. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4201. |$\Longrightarrow$|
  4202. (movq |$\itm{vec}'$| (reg r11))
  4203. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4204. (movq (int 0) |$\itm{lhs}$|)
  4205. \end{lstlisting}
  4206. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4207. processing $\itm{vec}$ and $\itm{arg}$.
  4208. \begin{figure}[tp]
  4209. \fbox{
  4210. \begin{minipage}{0.96\textwidth}
  4211. \[
  4212. \begin{array}{lcl}
  4213. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4214. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4215. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4216. \mid (\key{global-value}\; \itm{name}) \\
  4217. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4218. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4219. (\key{subq} \; \Arg\; \Arg) \mid
  4220. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4221. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4222. (\key{pushq}\;\Arg) \mid
  4223. (\key{popq}\;\Arg) \mid
  4224. (\key{retq})} \\
  4225. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4226. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4227. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4228. \mid (\key{jmp} \; \itm{label})
  4229. \mid (\key{j}\itm{cc} \; \itm{label})
  4230. \mid (\key{label} \; \itm{label}) } \\
  4231. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4232. \end{array}
  4233. \]
  4234. \end{minipage}
  4235. }
  4236. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4237. \label{fig:x86-2}
  4238. \end{figure}
  4239. The syntax of the $x86_2$ language is defined in
  4240. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4241. of the form for global variables.
  4242. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4243. \code{select-instructions} pass on the running example.
  4244. \begin{figure}[tbp]
  4245. \centering
  4246. \begin{minipage}{0.75\textwidth}
  4247. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4248. (program (lt28655 end-data28654 lt28652 end-data28651 tmp28644
  4249. tmp28645 tmp28646 tmp28647 void28649 void28648)
  4250. (type Integer)
  4251. (movq (int 16384) (reg rdi))
  4252. (movq (int 16) (reg rsi))
  4253. (callq initialize)
  4254. (movq (global-value rootstack_begin) (reg r15))
  4255. (movq (global-value free_ptr) (var end-data28651))
  4256. (addq (int 16) (var end-data28651))
  4257. (cmpq (global-value fromspace_end) (var end-data28651))
  4258. (set l (byte-reg al))
  4259. (movzbq (byte-reg al) (var lt28652))
  4260. (if (eq? (int 0) (var lt28652))
  4261. ((movq (reg r15) (reg rdi))
  4262. (movq (int 16) (reg rsi))
  4263. (callq collect))
  4264. ())
  4265. (movq (global-value free_ptr) (var tmp28644))
  4266. (addq (int 16) (global-value free_ptr))
  4267. (movq (var tmp28644) (reg r11))
  4268. (movq (int 3) (deref r11 0))
  4269. (movq (var tmp28644) (reg r11))
  4270. (movq (int 42) (deref r11 8))
  4271. (movq (global-value free_ptr) (var end-data28654))
  4272. (addq (int 16) (var end-data28654))
  4273. (cmpq (global-value fromspace_end) (var end-data28654))
  4274. (set l (byte-reg al))
  4275. (movzbq (byte-reg al) (var lt28655))
  4276. (if (eq? (int 0) (var lt28655))
  4277. ((movq (var tmp28644) (deref r15 0))
  4278. (addq (int 8) (reg r15))
  4279. (movq (reg r15) (reg rdi))
  4280. (movq (int 16) (reg rsi))
  4281. (callq collect)
  4282. (subq (int 8) (reg r15))
  4283. (movq (deref r15 0) (var tmp28644)))
  4284. ())
  4285. (movq (global-value free_ptr) (var tmp28645))
  4286. (addq (int 16) (global-value free_ptr))
  4287. (movq (var tmp28645) (reg r11))
  4288. (movq (int 131) (deref r11 0))
  4289. (movq (var tmp28645) (reg r11))
  4290. (movq (var tmp28644) (deref r11 8))
  4291. (movq (var tmp28645) (reg r11))
  4292. (movq (deref r11 8) (var tmp28646))
  4293. (movq (var tmp28646) (reg r11))
  4294. (movq (deref r11 8) (var tmp28647))
  4295. (movq (var tmp28647) (reg rax)))
  4296. \end{lstlisting}
  4297. \end{minipage}
  4298. \caption{Output of the \code{select-instructions} pass.}
  4299. \label{fig:select-instr-output-gc}
  4300. \end{figure}
  4301. \subsection{Register Allocation}
  4302. \label{sec:reg-alloc-gc}
  4303. UNDER CONSTRUCTION
  4304. \subsection{Print x86}
  4305. \label{sec:print-x86-gc}
  4306. \marginpar{\scriptsize We need to show the translation to x86 and what
  4307. to do about global-value. \\ --Jeremy}
  4308. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4309. \code{print-x86} pass.
  4310. \begin{figure}[htbp]
  4311. \begin{minipage}[t]{0.5\textwidth}
  4312. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4313. .globl _main
  4314. _main:
  4315. pushq %rbp
  4316. movq %rsp, %rbp
  4317. pushq %r14
  4318. pushq %r13
  4319. pushq %r12
  4320. pushq %rbx
  4321. subq $0, %rsp
  4322. movq $16384, %rdi
  4323. movq $16, %rsi
  4324. callq _initialize
  4325. movq _rootstack_begin(%rip), %r15
  4326. movq _free_ptr(%rip), %rbx
  4327. addq $16, %rbx
  4328. cmpq _fromspace_end(%rip), %rbx
  4329. setl %al
  4330. movzbq %al, %rbx
  4331. cmpq $0, %rbx
  4332. je then30964
  4333. jmp if_end30965
  4334. then30964:
  4335. movq %r15, %rdi
  4336. movq $16, %rsi
  4337. callq _collect
  4338. if_end30965:
  4339. movq _free_ptr(%rip), %rbx
  4340. addq $16, _free_ptr(%rip)
  4341. movq %rbx, %r11
  4342. movq $3, 0(%r11)
  4343. movq %rbx, %r11
  4344. movq $42, 8(%r11)
  4345. movq _free_ptr(%rip), %rcx
  4346. addq $16, %rcx
  4347. cmpq _fromspace_end(%rip), %rcx
  4348. setl %al
  4349. movzbq %al, %rcx
  4350. cmpq $0, %rcx
  4351. je then30966
  4352. jmp if_end30967
  4353. \end{lstlisting}
  4354. \end{minipage}
  4355. \begin{minipage}[t]{0.45\textwidth}
  4356. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4357. then30966:
  4358. movq %rbx, 0(%r15)
  4359. addq $8, %r15
  4360. movq %r15, %rdi
  4361. movq $16, %rsi
  4362. callq _collect
  4363. subq $8, %r15
  4364. movq 0(%r15), %rbx
  4365. if_end30967:
  4366. movq _free_ptr(%rip), %rcx
  4367. addq $16, _free_ptr(%rip)
  4368. movq %rcx, %r11
  4369. movq $131, 0(%r11)
  4370. movq %rcx, %r11
  4371. movq %rbx, 8(%r11)
  4372. movq %rcx, %r11
  4373. movq 8(%r11), %rbx
  4374. movq %rbx, %r11
  4375. movq 8(%r11), %rbx
  4376. movq %rbx, %rax
  4377. movq %rax, %rdi
  4378. callq _print_int
  4379. movq $0, %rax
  4380. addq $0, %rsp
  4381. popq %rbx
  4382. popq %r12
  4383. popq %r13
  4384. popq %r14
  4385. popq %rbp
  4386. retq
  4387. \end{lstlisting}
  4388. \end{minipage}
  4389. \caption{Output of the \code{print-x86} pass.}
  4390. \label{fig:print-x86-output-gc}
  4391. \end{figure}
  4392. \marginpar{\scriptsize Suggest an implementation strategy
  4393. in which the students first do the code gen and test that
  4394. without GC (just use a big heap), then after that is debugged,
  4395. implement the GC. \\ --Jeremy}
  4396. \begin{figure}[p]
  4397. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4398. \node (R1) at (0,2) {\large $R_1$};
  4399. \node (R1-2) at (3,2) {\large $R_1$};
  4400. \node (R1-3) at (6,2) {\large $R_1$};
  4401. \node (C1-1) at (9,0) {\large $C_1$};
  4402. \node (C1-2) at (6,0) {\large $C_1$};
  4403. \node (C1-3) at (3,0) {\large $C_1$};
  4404. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4405. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4406. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4407. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  4408. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  4409. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4410. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4411. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize typecheck} (R1-2);
  4412. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize uniquify} (R1-3);
  4413. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize flatten} (C1-1);
  4414. \path[->,bend left=15] (C1-1) edge [below] node {\ttfamily\footnotesize\color{red} expose-alloc.} (C1-2);
  4415. \path[->,bend left=15] (C1-2) edge [below] node {\ttfamily\footnotesize\color{red} uncover...roots} (C1-3);
  4416. \path[->,bend right=15] (C1-3) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4417. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4418. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4419. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4420. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize lower-cond.} (x86-4);
  4421. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-5);
  4422. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  4423. \end{tikzpicture}
  4424. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4425. \label{fig:R3-passes}
  4426. \end{figure}
  4427. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  4428. for the compilation of $R_3$.
  4429. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4430. \chapter{Functions}
  4431. \label{ch:functions}
  4432. This chapter studies the compilation of functions (aka. procedures) at
  4433. the level of abstraction of the C language. This corresponds to a
  4434. subset of Typed Racket in which only top-level function definitions
  4435. are allowed. This abstraction level is an important stepping stone to
  4436. implementing lexically-scoped functions in the form of \key{lambda}
  4437. abstractions (Chapter~\ref{ch:lambdas}).
  4438. \section{The $R_4$ Language}
  4439. The syntax for function definitions and function application
  4440. (aka. function call) is shown in Figure~\ref{fig:r4-syntax}, where we
  4441. define the $R_4$ language. Programs in $R_4$ start with zero or more
  4442. function definitions. The function names from these definitions are
  4443. in-scope for the entire program, including all other function
  4444. definitions (so the ordering of function definitions does not matter).
  4445. Functions are first-class in the sense that a function pointer is data
  4446. and can be stored in memory or passed as a parameter to another
  4447. function. Thus, we introduce a function type, written
  4448. \begin{lstlisting}
  4449. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4450. \end{lstlisting}
  4451. for a function whose $n$ parameters have the types $\Type_1$ through
  4452. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4453. these functions (with respect to Racket functions) is that they are
  4454. not lexically scoped. That is, the only external entities that can be
  4455. referenced from inside a function body are other globally-defined
  4456. functions. The syntax of $R_4$ prevents functions from being nested
  4457. inside each other; they can only be defined at the top level.
  4458. \begin{figure}[tp]
  4459. \centering
  4460. \fbox{
  4461. \begin{minipage}{0.96\textwidth}
  4462. \[
  4463. \begin{array}{lcl}
  4464. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4465. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4466. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4467. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4468. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4469. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4470. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4471. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4472. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4473. (\key{vector-ref}\;\Exp\;\Int)} \\
  4474. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4475. &\mid& (\Exp \; \Exp^{*}) \\
  4476. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4477. R_4 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4478. \end{array}
  4479. \]
  4480. \end{minipage}
  4481. }
  4482. \caption{Syntax of $R_4$, extending $R_3$ with functions.}
  4483. \label{fig:r4-syntax}
  4484. \end{figure}
  4485. The program in Figure~\ref{fig:r4-function-example} is a
  4486. representative example of defining and using functions in $R_4$. We
  4487. define a function \code{map-vec} that applies some other function
  4488. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  4489. vector containing the results. We also define a function \code{add1}
  4490. that does what its name suggests. The program then applies
  4491. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  4492. \code{(vector 1 42)}, from which we return the \code{42}.
  4493. \begin{figure}[tbp]
  4494. \begin{lstlisting}
  4495. (program
  4496. (define (map-vec [f : (Integer -> Integer)]
  4497. [v : (Vector Integer Integer)])
  4498. : (Vector Integer Integer)
  4499. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  4500. (define (add1 [x : Integer]) : Integer
  4501. (+ x 1))
  4502. (vector-ref (map-vec add1 (vector 0 41)) 1)
  4503. )
  4504. \end{lstlisting}
  4505. \caption{Example of using functions in $R_4$.}
  4506. \label{fig:r4-function-example}
  4507. \end{figure}
  4508. The definitional interpreter for $R_4$ is in
  4509. Figure~\ref{fig:interp-R4}.
  4510. \begin{figure}[tp]
  4511. \begin{lstlisting}
  4512. (define (interp-R4 env)
  4513. (lambda (e)
  4514. (match e
  4515. ....
  4516. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  4517. (cons f `(lambda ,xs ,body))]
  4518. [`(program ,ds ... ,body)
  4519. (let ([top-level (map (interp-R4 '()) ds)])
  4520. ((interp-R4 top-level) body))]
  4521. [`(,fun ,args ...)
  4522. (define arg-vals (map (interp-R4 env) args))
  4523. (define fun-val ((interp-R4 env) fun))
  4524. (match fun-val
  4525. [`(lambda (,xs ...) ,body)
  4526. (define new-env (append (map cons xs arg-vals) env))
  4527. ((interp-R4 new-env) body)]
  4528. [else (error "interp-R4, expected function, not" fun-val)]))]
  4529. [else (error 'interp-R4 "unrecognized expression")]
  4530. )))
  4531. \end{lstlisting}
  4532. \caption{Interpreter for the $R_4$ language.}
  4533. \label{fig:interp-R4}
  4534. \end{figure}
  4535. \section{Functions in x86}
  4536. \label{sec:fun-x86}
  4537. \marginpar{\tiny Make sure callee save registers are discussed
  4538. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  4539. \marginpar{\tiny Talk about the return address on the
  4540. stack and what callq and retq does.\\ --Jeremy }
  4541. The x86 architecture provides a few features to support the
  4542. implementation of functions. We have already seen that x86 provides
  4543. labels so that one can refer to the location of an instruction, as is
  4544. needed for jump instructions. Labels can also be used to mark the
  4545. beginning of the instructions for a function. Going further, we can
  4546. obtain the address of a label by using the \key{leaq} instruction and
  4547. \key{rip}-relative addressing. For example, the following puts the
  4548. address of the \code{add1} label into the \code{rbx} register.
  4549. \begin{lstlisting}
  4550. leaq add1(%rip), %rbx
  4551. \end{lstlisting}
  4552. In Sections~\ref{sec:x86} and \ref{sec:select-s0} we saw the use of
  4553. the \code{callq} instruction for jumping to a function as specified by
  4554. a label. The use of the instruction changes slightly if the function
  4555. is specified by an address in a register, that is, an \emph{indirect
  4556. function call}. The x86 syntax is to give the register name prefixed
  4557. with an asterisk.
  4558. \begin{lstlisting}
  4559. callq *%rbx
  4560. \end{lstlisting}
  4561. The x86 architecture does not directly support passing arguments to
  4562. functions; instead we use a combination of registers and stack
  4563. locations for passing arguments, following the conventions used by
  4564. \code{gcc} as described by \cite{Matz:2013aa}. Up to six arguments may
  4565. be passed in registers, using the registers \code{rdi}, \code{rsi},
  4566. \code{rdx}, \code{rcx}, \code{r8}, and \code{r9}, in that order. If
  4567. there are more than six arguments, then the rest must be placed on the
  4568. stack, which we call \emph{stack arguments}, which we discuss in later
  4569. paragraphs. The register \code{rax} is for the return value of the
  4570. function.
  4571. Recall from Section~\ref{sec:x86} that the stack is also used for
  4572. local variables and for storing the values of callee-save registers
  4573. (we shall refer to all of these collectively as ``locals''), and that
  4574. at the beginning of a function we move the stack pointer \code{rsp}
  4575. down to make room for them.
  4576. %% We recommend storing the local variables
  4577. %% first and then the callee-save registers, so that the local variables
  4578. %% can be accessed using \code{rbp} the same as before the addition of
  4579. %% functions.
  4580. To make additional room for passing arguments, we shall
  4581. move the stack pointer even further down. We count how many stack
  4582. arguments are needed for each function call that occurs inside the
  4583. body of the function and find their maximum. Adding this number to the
  4584. number of locals gives us how much the \code{rsp} should be moved at
  4585. the beginning of the function. In preparation for a function call, we
  4586. offset from \code{rsp} to set up the stack arguments. We put the first
  4587. stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  4588. so on.
  4589. Upon calling the function, the stack arguments are retrieved by the
  4590. callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  4591. is the location of the first stack argument, \code{24(\%rbp)} is the
  4592. address of the second, and so on. Figure~\ref{fig:call-frames} shows
  4593. the layout of the caller and callee frames. Notice how important it is
  4594. that we correctly compute the maximum number of arguments needed for
  4595. function calls; if that number is too small then the arguments and
  4596. local variables will smash into each other!
  4597. As discussed in Section~\ref{sec:print-x86-reg-alloc}, an x86 function
  4598. is responsible for following conventions regarding the use of
  4599. registers: the caller should assume that all the caller save registers
  4600. get overwritten with arbitrary values by the callee. Thus, the caller
  4601. should either 1) not put values that are live across a call in caller
  4602. save registers, or 2) save and restore values that are live across
  4603. calls. We shall recommend option 1). On the flip side, if the callee
  4604. wants to use a callee save register, the callee must arrange to put
  4605. the original value back in the register prior to returning to the
  4606. caller.
  4607. \begin{figure}[tbp]
  4608. \centering
  4609. \begin{tabular}{r|r|l|l} \hline
  4610. Caller View & Callee View & Contents & Frame \\ \hline
  4611. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  4612. 0(\key{\%rbp}) & & old \key{rbp} \\
  4613. -8(\key{\%rbp}) & & local $1$ \\
  4614. \ldots & & \ldots \\
  4615. $-8k$(\key{\%rbp}) & & local $k$ \\
  4616. & & \\
  4617. $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  4618. & \ldots & \ldots \\
  4619. 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\ \hline
  4620. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  4621. & 0(\key{\%rbp}) & old \key{rbp} \\
  4622. & -8(\key{\%rbp}) & local $1$ \\
  4623. & \ldots & \ldots \\
  4624. & $-8m$(\key{\%rsp}) & local $m$\\ \hline
  4625. \end{tabular}
  4626. \caption{Memory layout of caller and callee frames.}
  4627. \label{fig:call-frames}
  4628. \end{figure}
  4629. \section{The compilation of functions}
  4630. \marginpar{\scriptsize To do: discuss the need to push and
  4631. pop call-live pointers (vectors and functions)
  4632. to the root stack \\ --Jeremy}
  4633. Now that we have a good understanding of functions as they appear in
  4634. $R_4$ and the support for functions in x86, we need to plan the
  4635. changes to our compiler, that is, do we need any new passes and/or do
  4636. we need to change any existing passes? Also, do we need to add new
  4637. kinds of AST nodes to any of the intermediate languages?
  4638. \begin{figure}[tp]
  4639. \centering
  4640. \fbox{
  4641. \begin{minipage}{0.96\textwidth}
  4642. \[
  4643. \begin{array}{lcl}
  4644. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4645. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4646. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4647. &\mid& (\key{function-ref}\, \itm{label})
  4648. \mid \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4649. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4650. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4651. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4652. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4653. (\key{vector-ref}\;\Exp\;\Int)} \\
  4654. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4655. &\mid& (\key{app}\, \Exp \; \Exp^{*}) \\
  4656. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4657. F_1 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4658. \end{array}
  4659. \]
  4660. \end{minipage}
  4661. }
  4662. \caption{The $F_1$ language, an extension of $R_3$
  4663. (Figure~\ref{fig:r3-syntax}).}
  4664. \label{fig:f1-syntax}
  4665. \end{figure}
  4666. To begin with, the syntax of $R_4$ is inconvenient for purposes of
  4667. compilation because it conflates the use of function names and local
  4668. variables and it conflates the application of primitive operations and
  4669. the application of functions. This is a problem because we need to
  4670. compile the use of a function name differently than the use of a local
  4671. variable; we need to use \code{leaq} to move the function name to a
  4672. register. Similarly, the application of a function is going to require
  4673. a complex sequence of instructions, unlike the primitive
  4674. operations. Thus, it is a good idea to create a new pass that changes
  4675. function references from just a symbol $f$ to \code{(function-ref
  4676. $f$)} and that changes function application from \code{($e_0$ $e_1$
  4677. $\ldots$ $e_n$)} to the explicitly tagged AST \code{(app $e_0$ $e_1$
  4678. $\ldots$ $e_n$)}. A good name for this pass is
  4679. \code{reveal-functions} and the output language, $F_1$, is defined in
  4680. Figure~\ref{fig:f1-syntax}. Placing this pass after \code{uniquify} is
  4681. a good idea, because it will make sure that there are no local
  4682. variables and functions that share the same name. On the other hand,
  4683. \code{reveal-functions} needs to come before the \code{flatten} pass
  4684. because \code{flatten} will help us compile \code{function-ref}.
  4685. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  4686. \key{flatten}.
  4687. \begin{figure}[tp]
  4688. \fbox{
  4689. \begin{minipage}{0.96\textwidth}
  4690. \[
  4691. \begin{array}{lcl}
  4692. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  4693. \mid (\key{function-ref}\,\itm{label})\\
  4694. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4695. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4696. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4697. &\mid& \gray{ (\key{vector}\, \Arg^{+})
  4698. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  4699. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) } \\
  4700. &\mid& (\key{app} \,\Arg\,\Arg^{*}) \\
  4701. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4702. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4703. &\mid& \gray{ (\key{initialize}\,\itm{int}\,\itm{int}) }\\
  4704. &\mid& \gray{ \IF{(\key{collection-needed?}\,\itm{int})}{\Stmt^{*}}{\Stmt^{*}} } \\
  4705. &\mid& \gray{ (\key{collect} \,\itm{int}) }
  4706. \mid \gray{ (\key{allocate} \,\itm{int}) }\\
  4707. &\mid& \gray{ (\key{call-live-roots}\,(\Var^{*}) \,\Stmt^{*}) } \\
  4708. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Stmt^{+}) \\
  4709. C_3 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;(\key{defines}\,\Def^{*})\;\Stmt^{+})
  4710. \end{array}
  4711. \]
  4712. \end{minipage}
  4713. }
  4714. \caption{The $C_3$ language, extending $C_2$ with functions.}
  4715. \label{fig:c3-syntax}
  4716. \end{figure}
  4717. Because each \code{function-ref} needs to eventually become an
  4718. \code{leaq} instruction, it first needs to become an assignment
  4719. statement so there is a left-hand side in which to put the
  4720. result. This can be handled easily in the \code{flatten} pass by
  4721. categorizing \code{function-ref} as a complex expression. Then, in
  4722. the \code{select-instructions} pass, an assignment of
  4723. \code{function-ref} becomes a \code{leaq} instruction as follows: \\
  4724. \begin{tabular}{lll}
  4725. \begin{minipage}{0.45\textwidth}
  4726. \begin{lstlisting}
  4727. (assign |$\itm{lhs}$| (function-ref |$f$|))
  4728. \end{lstlisting}
  4729. \end{minipage}
  4730. &
  4731. $\Rightarrow$
  4732. &
  4733. \begin{minipage}{0.4\textwidth}
  4734. \begin{lstlisting}
  4735. (leaq (function-ref |$f$|) |$\itm{lhs}$|)
  4736. \end{lstlisting}
  4737. \end{minipage}
  4738. \end{tabular} \\
  4739. %
  4740. The output of select instructions is a program in the x86$_3$
  4741. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  4742. \begin{figure}[tp]
  4743. \fbox{
  4744. \begin{minipage}{0.96\textwidth}
  4745. \[
  4746. \begin{array}{lcl}
  4747. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4748. \mid (\key{deref}\,\itm{register}\,\Int) \mid (\key{byte-reg}\; \itm{register}) } \\
  4749. &\mid& \gray{ (\key{global-value}\; \itm{name}) } \\
  4750. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4751. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  4752. (\key{subq} \; \Arg\; \Arg) \mid
  4753. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  4754. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  4755. (\key{pushq}\;\Arg) \mid
  4756. (\key{popq}\;\Arg) \mid
  4757. (\key{retq}) } \\
  4758. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4759. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4760. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4761. \mid (\key{jmp} \; \itm{label})
  4762. \mid (\key{j}\itm{cc} \; \itm{label})
  4763. \mid (\key{label} \; \itm{label}) } \\
  4764. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{leaq}\;\Arg\;\Arg)\\
  4765. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{int} \;\itm{info}\; \Stmt^{+})\\
  4766. x86_3 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\;
  4767. (\key{defines}\,\Def^{*}) \; \Instr^{+})
  4768. \end{array}
  4769. \]
  4770. \end{minipage}
  4771. }
  4772. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  4773. \label{fig:x86-3}
  4774. \end{figure}
  4775. Next we consider compiling function definitions. The \code{flatten}
  4776. pass should handle function definitions a lot like a \code{program}
  4777. node; after all, the \code{program} node represents the \code{main}
  4778. function. So the \code{flatten} pass, in addition to flattening the
  4779. body of the function into a sequence of statements, should record the
  4780. local variables in the $\Var^{*}$ field as shown below.
  4781. \begin{lstlisting}
  4782. (define (|$f$| [|\itm{xs}| : |\itm{ts}|]|$^{*}$|) : |\itm{rt}| (|$\Var^{*}$|) |$\Stmt^{+}$|)
  4783. \end{lstlisting}
  4784. In the \code{select-instructions} pass, we need to encode the
  4785. parameter passing in terms of the conventions discussed in
  4786. Section~\ref{sec:fun-x86}. So depending on the length of the parameter
  4787. list \itm{xs}, some of them may be in registers and some of them may
  4788. be on the stack. I recommend generating \code{movq} instructions to
  4789. move the parameters from their registers and stack locations into the
  4790. variables \itm{xs}, then let register allocation handle the assignment
  4791. of those variables to homes. After this pass, the \itm{xs} can be
  4792. added to the list of local variables. As mentioned in
  4793. Section~\ref{sec:fun-x86}, we need to find out how far to move the
  4794. stack pointer to ensure we have enough space for stack arguments in
  4795. all the calls inside the body of this function. This pass is a good
  4796. place to do this and store the result in the \itm{maxStack} field of
  4797. the output \code{define} shown below.
  4798. \begin{lstlisting}
  4799. (define (|$f$|) |\itm{numParams}| (|$\Var^{*}$| |\itm{maxStack}|) |$\Instr^{+}$|)
  4800. \end{lstlisting}
  4801. Next, consider the compilation of function applications, which have
  4802. the following form at the start of \code{select-instructions}.
  4803. \begin{lstlisting}
  4804. (assign |\itm{lhs}| (app |\itm{fun}| |\itm{args}| |$\ldots$|))
  4805. \end{lstlisting}
  4806. In the mirror image of handling the parameters of function
  4807. definitions, some of the arguments \itm{args} need to be moved to the
  4808. argument passing registers and the rest should be moved to the
  4809. appropriate stack locations, as discussed in
  4810. Section~\ref{sec:fun-x86}.
  4811. %% You might want to introduce a new kind of AST node for stack
  4812. %% arguments, \code{(stack-arg $i$)} where $i$ is the index of this
  4813. %% argument with respect to the other stack arguments.
  4814. As you're generating the code for parameter passing, take note of how
  4815. many stack arguments are needed for purposes of computing the
  4816. \itm{maxStack} discussed above.
  4817. Once the instructions for parameter passing have been generated, the
  4818. function call itself can be performed with an indirect function call,
  4819. for which I recommend creating the new instruction
  4820. \code{indirect-callq}. Of course, the return value from the function
  4821. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  4822. \begin{lstlisting}
  4823. (indirect-callq |\itm{fun}|)
  4824. (movq (reg rax) |\itm{lhs}|)
  4825. \end{lstlisting}
  4826. The rest of the passes need only minor modifications to handle the new
  4827. kinds of AST nodes: \code{function-ref}, \code{indirect-callq}, and
  4828. \code{leaq}. Inside \code{uncover-live}, when computing the $W$ set
  4829. (written variables) for an \code{indirect-callq} instruction, I
  4830. recommend including all the caller save registers, which will have the
  4831. affect of making sure that no caller save register actually needs to be
  4832. saved. In \code{patch-instructions}, you should deal with the x86
  4833. idiosyncrasy that the destination argument of \code{leaq} must be a
  4834. register.
  4835. For the \code{print-x86} pass, I recommend the following translations:
  4836. \begin{lstlisting}
  4837. (function-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  4838. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  4839. \end{lstlisting}
  4840. For function definitions, the \code{print-x86} pass should add the
  4841. code for saving and restoring the callee save registers, if you
  4842. haven't already done that.
  4843. \section{An Example Translation}
  4844. Figure~\ref{fig:add-fun} shows an example translation of a simple
  4845. function in $R_4$ to x86. The figure includes the results of the
  4846. \code{flatten} and \code{select-instructions} passes. Can you see any
  4847. ways to improve the translation?
  4848. \begin{figure}[tbp]
  4849. \begin{tabular}{lll}
  4850. \begin{minipage}{0.5\textwidth}
  4851. \begin{lstlisting}
  4852. (program
  4853. (define (add [x : Integer]
  4854. [y : Integer])
  4855. : Integer (+ x y))
  4856. (add 40 2))
  4857. \end{lstlisting}
  4858. $\Downarrow$
  4859. \begin{lstlisting}
  4860. (program (t.1 t.2)
  4861. (defines
  4862. (define (add.1 [x.1 : Integer]
  4863. [y.1 : Integer])
  4864. : Integer (t.3)
  4865. (assign t.3 (+ x.1 y.1))
  4866. (return t.3)))
  4867. (assign t.1 (function-ref add.1))
  4868. (assign t.2 (app t.1 40 2))
  4869. (return t.2))
  4870. \end{lstlisting}
  4871. $\Downarrow$
  4872. \begin{lstlisting}
  4873. (program ((rs.1 t.1 t.2) 0)
  4874. (type Integer)
  4875. (defines
  4876. (define (add28545) 3
  4877. ((rs.2 x.2 y.3 t.4) 0)
  4878. (movq (reg rdi) (var rs.2))
  4879. (movq (reg rsi) (var x.2))
  4880. (movq (reg rdx) (var y.3))
  4881. (movq (var x.2) (var t.4))
  4882. (addq (var y.3) (var t.4))
  4883. (movq (var t.4) (reg rax))))
  4884. (movq (int 16384) (reg rdi))
  4885. (movq (int 16) (reg rsi))
  4886. (callq initialize)
  4887. (movq (global-value rootstack_begin)
  4888. (var rs.1))
  4889. (leaq (function-ref add28545) (var t.1))
  4890. (movq (var rs.1) (reg rdi))
  4891. (movq (int 40) (reg rsi))
  4892. (movq (int 2) (reg rdx))
  4893. (indirect-callq (var t.1))
  4894. (movq (reg rax) (var t.2))
  4895. (movq (var t.2) (reg rax)))
  4896. \end{lstlisting}
  4897. \end{minipage}
  4898. &
  4899. \begin{minipage}{0.4\textwidth}
  4900. $\Downarrow$
  4901. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4902. .globl add28545
  4903. add28545:
  4904. pushq %rbp
  4905. movq %rsp, %rbp
  4906. pushq %r15
  4907. pushq %r14
  4908. pushq %r13
  4909. pushq %r12
  4910. pushq %rbx
  4911. subq $8, %rsp
  4912. movq %rdi, %rbx
  4913. movq %rsi, %rbx
  4914. movq %rdx, %rcx
  4915. addq %rcx, %rbx
  4916. movq %rbx, %rax
  4917. addq $8, %rsp
  4918. popq %rbx
  4919. popq %r12
  4920. popq %r13
  4921. popq %r14
  4922. popq %r15
  4923. popq %rbp
  4924. retq
  4925. .globl _main
  4926. _main:
  4927. pushq %rbp
  4928. movq %rsp, %rbp
  4929. pushq %r15
  4930. pushq %r14
  4931. pushq %r13
  4932. pushq %r12
  4933. pushq %rbx
  4934. subq $8, %rsp
  4935. movq $16384, %rdi
  4936. movq $16, %rsi
  4937. callq _initialize
  4938. movq _rootstack_begin(%rip), %rcx
  4939. leaq add28545(%rip), %rbx
  4940. movq %rcx, %rdi
  4941. movq $40, %rsi
  4942. movq $2, %rdx
  4943. callq *%rbx
  4944. movq %rax, %rbx
  4945. movq %rbx, %rax
  4946. movq %rax, %rdi
  4947. callq _print_int
  4948. movq $0, %rax
  4949. addq $8, %rsp
  4950. popq %rbx
  4951. popq %r12
  4952. popq %r13
  4953. popq %r14
  4954. popq %r15
  4955. popq %rbp
  4956. retq
  4957. \end{lstlisting}
  4958. \end{minipage}
  4959. \end{tabular}
  4960. \caption{Example compilation of a simple function to x86.}
  4961. \label{fig:add-fun}
  4962. \end{figure}
  4963. \begin{exercise}\normalfont
  4964. Expand your compiler to handle $R_4$ as outlined in this section.
  4965. Create 5 new programs that use functions, including examples that pass
  4966. functions and return functions from other functions, and test your
  4967. compiler on these new programs and all of your previously created test
  4968. programs.
  4969. \end{exercise}
  4970. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4971. \chapter{Lexically Scoped Functions}
  4972. \label{ch:lambdas}
  4973. This chapter studies lexically scoped functions as they appear in
  4974. functional languages such as Racket. By lexical scoping we mean that a
  4975. function's body may refer to variables whose binding site is outside
  4976. of the function, in an enclosing scope.
  4977. %
  4978. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  4979. anonymous function defined using the \key{lambda} form. The body of
  4980. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  4981. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  4982. the \key{lambda}. Variable \code{y} is bound by the enclosing
  4983. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  4984. returned from the function \code{f}. Below the definition of \code{f},
  4985. we have two calls to \code{f} with different arguments for \code{x},
  4986. first \code{5} then \code{3}. The functions returned from \code{f} are
  4987. bound to variables \code{g} and \code{h}. Even though these two
  4988. functions were created by the same \code{lambda}, they are really
  4989. different functions because they use different values for
  4990. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  4991. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  4992. the result of this program is \code{42}.
  4993. \begin{figure}[btp]
  4994. \begin{lstlisting}
  4995. (define (f [x : Integer]) : (Integer -> Integer)
  4996. (let ([y 4])
  4997. (lambda: ([z : Integer]) : Integer
  4998. (+ x (+ y z)))))
  4999. (let ([g (f 5)])
  5000. (let ([h (f 3)])
  5001. (+ (g 11) (h 15))))
  5002. \end{lstlisting}
  5003. \caption{Example of a lexically scoped function.}
  5004. \label{fig:lexical-scoping}
  5005. \end{figure}
  5006. \section{The $R_5$ Language}
  5007. The syntax for this language with anonymous functions and lexical
  5008. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5009. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5010. for function application. In this chapter we shall descibe how to
  5011. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5012. into a combination of functions (as in $R_4$) and tuples (as in
  5013. $R_3$).
  5014. \begin{figure}[tp]
  5015. \centering
  5016. \fbox{
  5017. \begin{minipage}{0.96\textwidth}
  5018. \[
  5019. \begin{array}{lcl}
  5020. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5021. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5022. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5023. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5024. \mid (\key{+} \; \Exp\;\Exp)} \\
  5025. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}
  5026. \mid \key{\#t} \mid \key{\#f} \mid
  5027. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5028. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5029. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5030. (\key{vector-ref}\;\Exp\;\Int)} \\
  5031. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5032. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5033. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5034. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5035. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5036. \end{array}
  5037. \]
  5038. \end{minipage}
  5039. }
  5040. \caption{Syntax of $R_5$, extending $R_4$ with \key{lambda}.}
  5041. \label{fig:r5-syntax}
  5042. \end{figure}
  5043. We shall describe how to compile $R_5$ to $R_4$, replacing anonymous
  5044. functions with top-level function definitions. However, our compiler
  5045. must provide special treatment to variable occurences such as \code{x}
  5046. and \code{y} in the body of the \code{lambda} of
  5047. Figure~\ref{fig:lexical-scoping}, for the functions of $R_4$ may not
  5048. refer to variables defined outside the function. To identify such
  5049. variable occurences, we review the standard notion of free variable.
  5050. \begin{definition}
  5051. A variable is \emph{free with respect to an expression} $e$ if the
  5052. variable occurs inside $e$ but does not have an enclosing binding in
  5053. $e$.
  5054. \end{definition}
  5055. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5056. free with respect to the expression \code{(+ x (+ y z))}. On the
  5057. other hand, only \code{x} and \code{y} are free with respect to the
  5058. following expression becuase \code{z} is bound by the \code{lambda}.
  5059. \begin{lstlisting}
  5060. (lambda: ([z : Integer]) : Integer
  5061. (+ x (+ y z)))
  5062. \end{lstlisting}
  5063. Once we have identified the free variables of a \code{lambda}, we need
  5064. to arrange for some way to transport, at runtime, the values of those
  5065. variables from the point where the \code{lambda} was created to the
  5066. point where the \code{lambda} is applied. Referring again to
  5067. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5068. needs to be used in the application of \code{g} to \code{11}, but the
  5069. binding of \code{x} to \code{3} needs to be used in the application of
  5070. \code{h} to \code{15}. The solution is to bundle the values of the
  5071. free variables together with the function pointer for the lambda's
  5072. code into a data structure called a \emph{closure}. Fortunately, we
  5073. already have the appropriate ingredients to make closures,
  5074. Chapter~\ref{ch:tuples} gave us tuples and Chapter~\ref{ch:functions}
  5075. gave us function pointers. The function pointer shall reside at index
  5076. $0$ and the values for free variables will fill in the rest of the
  5077. tuple. Figure~\ref{fig:closures} depicts the two closures created by
  5078. the two calls to \code{f} in Figure~\ref{fig:lexical-scoping}.
  5079. Because the two closures came from the same \key{lambda}, they share
  5080. the same code but differ in the values for free variable \code{x}.
  5081. \begin{figure}[tbp]
  5082. \centering \includegraphics[width=0.6\textwidth]{closures}
  5083. \caption{Example closure representation for the \key{lambda}'s
  5084. in Figure~\ref{fig:lexical-scoping}.}
  5085. \label{fig:closures}
  5086. \end{figure}
  5087. \section{Interpreting $R_5$}
  5088. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5089. $R_5$. There are several things to worth noting. First, and most
  5090. importantly, the match clause for \key{lambda} saves the current
  5091. environment inside the returned \key{lambda}. Then the clause for
  5092. \key{app} uses the environment from the \key{lambda}, the
  5093. \code{lam-env}, when interpreting the body of the \key{lambda}. Of
  5094. course, the \code{lam-env} environment is extending with the mapping
  5095. parameters to argument values. To enable mutual recursion and allow a
  5096. unified handling of functions created with \key{lambda} and with
  5097. \key{define}, the match clause for \key{program} includes a second
  5098. pass over the top-level functions to set their environments to be the
  5099. top-level environment.
  5100. \begin{figure}[tbp]
  5101. \begin{lstlisting}
  5102. (define (interp-R5 env)
  5103. (lambda (ast)
  5104. (match ast
  5105. ...
  5106. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5107. `(lambda ,xs ,body ,env)]
  5108. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5109. (mcons f `(lambda ,xs ,body))]
  5110. [`(program ,defs ... ,body)
  5111. (let ([top-level (map (interp-R5 '()) defs)])
  5112. (for/list ([b top-level])
  5113. (set-mcdr! b (match (mcdr b)
  5114. [`(lambda ,xs ,body)
  5115. `(lambda ,xs ,body ,top-level)])))
  5116. ((interp-R5 top-level) body))]
  5117. [`(,fun ,args ...)
  5118. (define arg-vals (map (interp-R5 env) args))
  5119. (define fun-val ((interp-R5 env) fun))
  5120. (match fun-val
  5121. [`(lambda (,xs ...) ,body ,lam-env)
  5122. (define new-env (append (map cons xs arg-vals) lam-env))
  5123. ((interp-R5 new-env) body)]
  5124. [else (error "interp-R5, expected function, not" fun-val)])]
  5125. )))
  5126. \end{lstlisting}
  5127. \caption{Interpreter for $R_5$.}
  5128. \label{fig:interp-R5}
  5129. \end{figure}
  5130. \section{Type Checking $R_5$}
  5131. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5132. \key{lambda} form. The body of the \key{lambda} is checked in an
  5133. environment that includes the current environment (because it is
  5134. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5135. require the body's type to match the declared return type.
  5136. \begin{figure}[tbp]
  5137. \begin{lstlisting}
  5138. (define (typecheck-R5 env)
  5139. (lambda (e)
  5140. (match e
  5141. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5142. (define new-env (append (map cons xs Ts) env))
  5143. (define bodyT ((typecheck-R5 new-env) body))
  5144. (cond [(equal? rT bodyT)
  5145. `(,@Ts -> ,rT)]
  5146. [else
  5147. (error "mismatch in return type" bodyT rT)])]
  5148. ...
  5149. )))
  5150. \end{lstlisting}
  5151. \caption{Type checking the \key{lambda}'s in $R_5$.}
  5152. \label{fig:typecheck-R5}
  5153. \end{figure}
  5154. \section{Closure Conversion}
  5155. The compiling of lexically-scoped functions into C-style functions is
  5156. accomplished in the pass \code{convert-to-closures} that comes after
  5157. \code{reveal-functions} and before flatten. This pass needs to treat
  5158. regular function calls differently from applying primitive operators,
  5159. and \code{reveal-functions} differentiates those two cases for us.
  5160. As usual, we shall implement the pass as a recursive function over the
  5161. AST. All of the action is in the clauses for \key{lambda} and
  5162. \key{app} (function application). We transform a \key{lambda}
  5163. expression into an expression that creates a closure, that is, creates
  5164. a vector whose first element is a function pointer and the rest of the
  5165. elements are the free variables of the \key{lambda}. The \itm{name}
  5166. is a unique symbol generated to identify the function.
  5167. \begin{tabular}{lll}
  5168. \begin{minipage}{0.4\textwidth}
  5169. \begin{lstlisting}
  5170. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  5171. \end{lstlisting}
  5172. \end{minipage}
  5173. &
  5174. $\Rightarrow$
  5175. &
  5176. \begin{minipage}{0.4\textwidth}
  5177. \begin{lstlisting}
  5178. (vector |\itm{name}| |\itm{fvs}| ...)
  5179. \end{lstlisting}
  5180. \end{minipage}
  5181. \end{tabular} \\
  5182. %
  5183. In addition to transforming each \key{lambda} into a \key{vector}, we
  5184. must create a top-level function definition for each \key{lambda}, as
  5185. shown below.
  5186. \begin{lstlisting}
  5187. (define (|\itm{name}| [clos : _] |\itm{ps}| ...)
  5188. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  5189. ...
  5190. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  5191. |\itm{body'}|)...))
  5192. \end{lstlisting}
  5193. The \code{clos} parameter refers to the closure whereas $\itm{ps}$ are
  5194. the normal parameters of the \key{lambda}. The sequence of \key{let}
  5195. forms being the free variables to their values obtained from the
  5196. closure.
  5197. We transform function application into code that retreives the
  5198. function pointer from the closure and then calls the function, passing
  5199. in the closure as the first argument. We bind $e'$ to a temporary
  5200. variable to avoid code duplication.
  5201. \begin{tabular}{lll}
  5202. \begin{minipage}{0.3\textwidth}
  5203. \begin{lstlisting}
  5204. (app |$e$| |\itm{es}| ...)
  5205. \end{lstlisting}
  5206. \end{minipage}
  5207. &
  5208. $\Rightarrow$
  5209. &
  5210. \begin{minipage}{0.5\textwidth}
  5211. \begin{lstlisting}
  5212. (let ([|\itm{tmp}| |$e'$|])
  5213. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  5214. \end{lstlisting}
  5215. \end{minipage}
  5216. \end{tabular} \\
  5217. There is also the question of what to do with top-level function
  5218. definitions. To maintain a uniform translation of function
  5219. application, we turn function references into closures.
  5220. \begin{tabular}{lll}
  5221. \begin{minipage}{0.3\textwidth}
  5222. \begin{lstlisting}
  5223. (function-ref |$f$|)
  5224. \end{lstlisting}
  5225. \end{minipage}
  5226. &
  5227. $\Rightarrow$
  5228. &
  5229. \begin{minipage}{0.5\textwidth}
  5230. \begin{lstlisting}
  5231. (vector (function-ref |$f$|))
  5232. \end{lstlisting}
  5233. \end{minipage}
  5234. \end{tabular} \\
  5235. %
  5236. The top-level function definitions need to be updated as well to take
  5237. an extra closure parameter.
  5238. \section{An Example Translation}
  5239. \label{sec:example-lambda}
  5240. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  5241. conversion for the example program demonstrating lexical scoping that
  5242. we discussed at the beginning of this chapter.
  5243. \begin{figure}[h]
  5244. \begin{minipage}{0.8\textwidth}
  5245. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5246. (program
  5247. (define (f [x : Integer]) : (Integer -> Integer)
  5248. (let ([y 4])
  5249. (lambda: ([z : Integer]) : Integer
  5250. (+ x (+ y z)))))
  5251. (let ([g (f 5)])
  5252. (let ([h (f 3)])
  5253. (+ (g 11) (h 15)))))
  5254. \end{lstlisting}
  5255. $\Downarrow$
  5256. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5257. (program (type Integer)
  5258. (define (f (x : Integer)) : (Integer -> Integer)
  5259. (let ((y 4))
  5260. (lambda: ((z : Integer)) : Integer
  5261. (+ x (+ y z)))))
  5262. (let ((g (app (function-ref f) 5)))
  5263. (let ((h (app (function-ref f) 3)))
  5264. (+ (app g 11) (app h 15)))))
  5265. \end{lstlisting}
  5266. $\Downarrow$
  5267. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5268. (program (type Integer)
  5269. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  5270. (let ((y 4))
  5271. (vector (function-ref lam.1) x y)))
  5272. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  5273. (let ((x (vector-ref clos.2 1)))
  5274. (let ((y (vector-ref clos.2 2)))
  5275. (+ x (+ y z)))))
  5276. (let ((g (let ((t.1 (vector (function-ref f))))
  5277. (app (vector-ref t.1 0) t.1 5))))
  5278. (let ((h (let ((t.2 (vector (function-ref f))))
  5279. (app (vector-ref t.2 0) t.2 3))))
  5280. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  5281. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  5282. \end{lstlisting}
  5283. \end{minipage}
  5284. \caption{Example of closure conversion.}
  5285. \label{fig:lexical-functions-example}
  5286. \end{figure}
  5287. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5288. \chapter{Dynamic Typing}
  5289. \label{ch:type-dynamic}
  5290. In this chapter we discuss the compilation of a dynamically typed
  5291. language, named $R_7$, that is a subset of the Racket language. (In
  5292. the previous chapters we have studied subsets of the \emph{Typed}
  5293. Racket language.) In dynamically typed languages, an expression may
  5294. produce values of differing type. Consider the following example with
  5295. a conditional expression that may return a Boolean or an integer
  5296. depending on the input to the program.
  5297. \begin{lstlisting}
  5298. (not (if (eq? (read) 1) #f 0))
  5299. \end{lstlisting}
  5300. Languages that allow expressions to produce different kinds of values
  5301. are called \emph{polymorphic}, and there are many kinds of
  5302. polymorphism, such as subtype polymorphism~\citep{Cardelli:1985kx} and
  5303. parametric polymorphism (Chapter~\ref{ch:parametric-polymorphism}).
  5304. Another characteristic of dynamically typed languages is that
  5305. primitive operations, such as \code{not}, are often defined to operate
  5306. on many different types of values. In fact, in Racket, the \code{not}
  5307. operator produces a result for any kind of value: given \code{\#f} it
  5308. returns \code{\#t} and given anything else it returns \code{\#f}.
  5309. Furthermore, even when primitive operations restrict their inputs to
  5310. values of a certain type, this restriction is enforced at runtime
  5311. instead of during compilation. For example, the following vector
  5312. reference results in a run-time contract violation.
  5313. \begin{lstlisting}
  5314. (vector-ref (vector 42) #t)
  5315. \end{lstlisting}
  5316. Let us consider how we might compile untyped Racket to x86, thinking
  5317. about the first example above. Our bit-level representation of the
  5318. Boolean \code{\#f} is zero and similarly for the integer \code{0}.
  5319. However, \code{(not \#f)} should produce \code{\#t} whereas \code{(not
  5320. 0)} should produce \code{\#f}. Furthermore, the behavior of
  5321. \code{not}, in general, cannot be determined at compile time, but
  5322. depends on the runtime type of its input, as in the example above that
  5323. depends on the result of \code{(read)}.
  5324. The way around this problem is to include information about a value's
  5325. runtime type in the value itself, so that this information can be
  5326. inspected by operators such as \code{not}. In particular, we shall
  5327. steal the 3 right-most bits from our 64-bit values to encode the
  5328. runtime type. We shall use $001$ to identify integers, $100$ for
  5329. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  5330. void value. We shall refer to these 3 bits as the \emph{tag} and we
  5331. define the following auxilliary function.
  5332. \begin{align*}
  5333. \itm{tagof}(\key{Integer}) &= 001 \\
  5334. \itm{tagof}(\key{Boolean}) &= 100 \\
  5335. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  5336. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  5337. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  5338. \itm{tagof}(\key{Void}) &= 101
  5339. \end{align*}
  5340. (We shall say more about the new \key{Vectorof} type shortly.)
  5341. This stealing of 3 bits comes at some
  5342. price: our integers are reduced to ranging from $-2^{60}$ to
  5343. $2^{60}$. The stealing does not adversely affect vectors and
  5344. procedures because those values are addresses, and our addresses are
  5345. 8-byte aligned so the rightmost 3 bits are unused, they are always
  5346. $000$. Thus, we do not lose information by overwriting the rightmost 3
  5347. bits with the tag and we can simply zero-out the tag to recover the
  5348. original address.
  5349. In some sense, these tagged values are a new kind of value. Indeed,
  5350. we can extend our \emph{typed} language with tagged values by adding a
  5351. new type to classify them, called \key{Any}, and with operations for
  5352. creating and using tagged values, creating the $R_6$ language defined
  5353. in Section~\ref{sec:r6-lang}. Thus, $R_6$ provides the fundamental
  5354. support for polymorphism and runtime types that we need to support
  5355. dynamic typing.
  5356. We shall implement our untyped language $R_7$ by compiling it to
  5357. $R_6$. We define $R_7$ in Section~\ref{sec:r7-lang} and describe the
  5358. compilation of $R_6$ and $R_7$ in the remainder of this chapter.
  5359. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  5360. \label{sec:r6-lang}
  5361. \begin{figure}[tp]
  5362. \centering
  5363. \fbox{
  5364. \begin{minipage}{0.97\textwidth}
  5365. \[
  5366. \begin{array}{lcl}
  5367. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5368. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  5369. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  5370. \FType &::=& \key{Integer} \mid \key{Boolean} \mid (\key{Vectorof}\;\key{Any})
  5371. \mid (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  5372. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5373. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5374. \mid (\key{+} \; \Exp\;\Exp)} \\
  5375. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  5376. &\mid& \gray{\key{\#t} \mid \key{\#f} \mid
  5377. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5378. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5379. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5380. (\key{vector-ref}\;\Exp\;\Int)} \\
  5381. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5382. &\mid& \gray{(\Exp \; \Exp^{*})
  5383. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5384. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  5385. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  5386. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  5387. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5388. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5389. \end{array}
  5390. \]
  5391. \end{minipage}
  5392. }
  5393. \caption{Syntax of $R_6$, extending $R_5$ with \key{Any}.}
  5394. \label{fig:r6-syntax}
  5395. \end{figure}
  5396. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  5397. $(\key{inject}\; e\; T)$ form converts the value produced by
  5398. expression $e$ of type $T$ into a tagged value. The
  5399. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  5400. expression $e$ into a value of type $T$ or else halts the program if
  5401. the type tag does not match $T$. Note that in both \key{inject} and
  5402. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  5403. which simplifies the implementation and corresponds with what is
  5404. needed for compiling untyped Racket. The type predicates,
  5405. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  5406. if the tag corresponds to the predicate, and return \key{\#t}
  5407. otherwise.
  5408. %
  5409. The type checker for $R_6$ is given in Figure~\ref{fig:typecheck-R6}.
  5410. \begin{figure}[tbp]
  5411. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5412. (define type-predicates
  5413. (set 'boolean? 'integer? 'vector? 'procedure?))
  5414. (define (typecheck-R6 env)
  5415. (lambda (e)
  5416. (define recur (typecheck-R6 env))
  5417. (match e
  5418. [`(inject ,(app recur new-e e-ty) ,ty)
  5419. (cond
  5420. [(equal? e-ty ty)
  5421. (values `(inject ,new-e ,ty) 'Any)]
  5422. [else
  5423. (error "inject expected ~a to have type ~a" e ty)])]
  5424. [`(project ,(app recur new-e e-ty) ,ty)
  5425. (cond
  5426. [(equal? e-ty 'Any)
  5427. (values `(project ,new-e ,ty) ty)]
  5428. [else
  5429. (error "project expected ~a to have type Any" e)])]
  5430. [`(,pred ,e) #:when (set-member? type-predicates pred)
  5431. (define-values (new-e e-ty) (recur e))
  5432. (cond
  5433. [(equal? e-ty 'Any)
  5434. (values `(,pred ,new-e) 'Boolean)]
  5435. [else
  5436. (error "predicate expected arg of type Any, not" e-ty)])]
  5437. [`(vector-ref ,(app recur e t) ,i)
  5438. (match t
  5439. [`(Vector ,ts ...) ...]
  5440. [`(Vectorof ,t)
  5441. (unless (exact-nonnegative-integer? i)
  5442. (error 'type-check "invalid index ~a" i))
  5443. (values `(vector-ref ,e ,i) t)]
  5444. [else (error "expected a vector in vector-ref, not" t)])]
  5445. [`(vector-set! ,(app recur e-vec^ t-vec) ,i
  5446. ,(app recur e-arg^ t-arg))
  5447. (match t-vec
  5448. [`(Vector ,ts ...) ...]
  5449. [`(Vectorof ,t)
  5450. (unless (exact-nonnegative-integer? i)
  5451. (error 'type-check "invalid index ~a" i))
  5452. (unless (equal? t t-arg)
  5453. (error 'type-check "type mismatch in vector-set! ~a ~a"
  5454. t t-arg))
  5455. (values `(vector-set! ,e-vec^
  5456. ,i
  5457. ,e-arg^) 'Void)]
  5458. [else (error 'type-check
  5459. "expected a vector in vector-set!, not ~a"
  5460. t-vec)])]
  5461. ...
  5462. )))
  5463. \end{lstlisting}
  5464. \caption{Type checker for the $R_6$ language.}
  5465. \label{fig:typecheck-R6}
  5466. \end{figure}
  5467. % to do: add rules for vector-ref, etc. for Vectorof
  5468. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  5469. Figure~\ref{fig:interp-R6} shows the definitional interpreter
  5470. for $R_6$.
  5471. \begin{figure}[tbp]
  5472. \begin{lstlisting}
  5473. (define primitives (set 'boolean? ...))
  5474. (define (interp-op op)
  5475. (match op
  5476. ['boolean? (lambda (v)
  5477. (match v
  5478. [`(tagged ,v1 Boolean) #t]
  5479. [else #f]))]
  5480. ...))
  5481. (define (interp-R6 env)
  5482. (lambda (ast)
  5483. (match ast
  5484. [`(inject ,e ,t)
  5485. `(tagged ,((interp-R6 env) e) ,t)]
  5486. [`(project ,e ,t2)
  5487. (define v ((interp-R6 env) e))
  5488. (match v
  5489. [`(tagged ,v1 ,t1)
  5490. (cond [(equal? t1 t2)
  5491. v1]
  5492. [else
  5493. (error "in project, type mismatch" t1 t2)])]
  5494. [else
  5495. (error "in project, expected tagged value" v)])]
  5496. ...)))
  5497. \end{lstlisting}
  5498. \caption{Interpreter for $R_6$.}
  5499. \label{fig:interp-R6}
  5500. \end{figure}
  5501. \section{The $R_7$ Language: Untyped Racket}
  5502. \label{sec:r7-lang}
  5503. \begin{figure}[tp]
  5504. \centering
  5505. \fbox{
  5506. \begin{minipage}{0.97\textwidth}
  5507. \[
  5508. \begin{array}{rcl}
  5509. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5510. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  5511. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  5512. &\mid& \key{\#t} \mid \key{\#f} \mid
  5513. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  5514. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  5515. &\mid& (\key{vector}\;\Exp^{+}) \mid
  5516. (\key{vector-ref}\;\Exp\;\Exp) \\
  5517. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  5518. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  5519. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  5520. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  5521. \end{array}
  5522. \]
  5523. \end{minipage}
  5524. }
  5525. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  5526. \label{fig:r7-syntax}
  5527. \end{figure}
  5528. The syntax of $R_7$, our subset of Racket, is defined in
  5529. Figure~\ref{fig:r7-syntax}.
  5530. %
  5531. The definitional interpreter for $R_7$ is given in
  5532. Figure~\ref{fig:interp-R7}.
  5533. \begin{figure}[tbp]
  5534. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5535. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  5536. (define (valid-op? op) (member op '(+ - and or not)))
  5537. (define (interp-r7 env)
  5538. (lambda (ast)
  5539. (define recur (interp-r7 env))
  5540. (match ast
  5541. [(? symbol?) (lookup ast env)]
  5542. [(? integer?) `(inject ,ast Integer)]
  5543. [#t `(inject #t Boolean)]
  5544. [#f `(inject #f Boolean)]
  5545. [`(read) `(inject ,(read-fixnum) Integer)]
  5546. [`(lambda (,xs ...) ,body)
  5547. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  5548. [`(define (,f ,xs ...) ,body)
  5549. (mcons f `(lambda ,xs ,body))]
  5550. [`(program ,ds ... ,body)
  5551. (let ([top-level (map (interp-r7 '()) ds)])
  5552. (for/list ([b top-level])
  5553. (set-mcdr! b (match (mcdr b)
  5554. [`(lambda ,xs ,body)
  5555. `(inject (lambda ,xs ,body ,top-level)
  5556. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  5557. ((interp-r7 top-level) body))]
  5558. [`(vector ,(app recur elts) ...)
  5559. (define tys (map get-tagged-type elts))
  5560. `(inject ,(apply vector elts) (Vector ,@tys))]
  5561. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  5562. (match v1
  5563. [`(inject ,vec ,ty)
  5564. (vector-set! vec n v2)
  5565. `(inject (void) Void)])]
  5566. [`(vector-ref ,(app recur v) ,n)
  5567. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  5568. [`(let ([,x ,(app recur v)]) ,body)
  5569. ((interp-r7 (cons (cons x v) env)) body)]
  5570. [`(,op ,es ...) #:when (valid-op? op)
  5571. (interp-r7-op op (map recur es))]
  5572. [`(eq? ,(app recur l) ,(app recur r))
  5573. `(inject ,(equal? l r) Boolean)]
  5574. [`(if ,(app recur q) ,t ,f)
  5575. (match q
  5576. [`(inject #f Boolean) (recur f)]
  5577. [else (recur t)])]
  5578. [`(,(app recur f-val) ,(app recur vs) ...)
  5579. (match f-val
  5580. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  5581. (define new-env (append (map cons xs vs) lam-env))
  5582. ((interp-r7 new-env) body)]
  5583. [else (error "interp-r7, expected function, not" f-val)])])))
  5584. \end{lstlisting}
  5585. \caption{Interpreter for the $R_7$ language.}
  5586. \label{fig:interp-R7}
  5587. \end{figure}
  5588. \section{Compiling $R_6$}
  5589. \label{sec:compile-r6}
  5590. Most of the compiler passes only require straightforward changes. The
  5591. interesting part is in instruction selection.
  5592. \paragraph{Inject}
  5593. We recommend compiling an \key{inject} as follows if the type is
  5594. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  5595. destination to the left by the number of bits specified by the source
  5596. ($2$) and it preserves the sign of the integer. We use the \key{orq}
  5597. instruction to combine the tag and the value to form the tagged value.
  5598. \\
  5599. \begin{tabular}{lll}
  5600. \begin{minipage}{0.4\textwidth}
  5601. \begin{lstlisting}
  5602. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5603. \end{lstlisting}
  5604. \end{minipage}
  5605. &
  5606. $\Rightarrow$
  5607. &
  5608. \begin{minipage}{0.5\textwidth}
  5609. \begin{lstlisting}
  5610. (movq |$e'$| |\itm{lhs}'|)
  5611. (salq (int 2) |\itm{lhs}'|)
  5612. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5613. \end{lstlisting}
  5614. \end{minipage}
  5615. \end{tabular} \\
  5616. The instruction selection for vectors and procedures is different
  5617. because their is no need to shift them to the left. The rightmost 3
  5618. bits are already zeros as described above. So we combine the value and
  5619. the tag using
  5620. \key{orq}. \\
  5621. \begin{tabular}{lll}
  5622. \begin{minipage}{0.4\textwidth}
  5623. \begin{lstlisting}
  5624. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5625. \end{lstlisting}
  5626. \end{minipage}
  5627. &
  5628. $\Rightarrow$
  5629. &
  5630. \begin{minipage}{0.5\textwidth}
  5631. \begin{lstlisting}
  5632. (movq |$e'$| |\itm{lhs}'|)
  5633. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5634. \end{lstlisting}
  5635. \end{minipage}
  5636. \end{tabular} \\
  5637. \paragraph{Project}
  5638. The instruction selection for \key{project} is a bit more involved.
  5639. Like \key{inject}, the instructions are different depending on whether
  5640. the type $T$ is a pointer (vector or procedure) or not (Integer or
  5641. Boolean). The following shows the instruction selection for Integer
  5642. and Boolean. We first check to see if the tag on the tagged value
  5643. matches the tag of the target type $T$. If not, we halt the program by
  5644. calling the \code{exit} function. If we have a match, we need to
  5645. produce an untagged value by shifting it to the right by 2 bits.
  5646. %
  5647. \\
  5648. \begin{tabular}{lll}
  5649. \begin{minipage}{0.4\textwidth}
  5650. \begin{lstlisting}
  5651. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5652. \end{lstlisting}
  5653. \end{minipage}
  5654. &
  5655. $\Rightarrow$
  5656. &
  5657. \begin{minipage}{0.5\textwidth}
  5658. \begin{lstlisting}
  5659. (movq |$e'$| |\itm{lhs}'|)
  5660. (andq (int 3) |\itm{lhs}'|)
  5661. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5662. ((movq |$e'$| |\itm{lhs}'|)
  5663. (sarq (int 2) |\itm{lhs}'|))
  5664. ((callq exit)))
  5665. \end{lstlisting}
  5666. \end{minipage}
  5667. \end{tabular} \\
  5668. %
  5669. The case for vectors and procedures begins in a similar way, checking
  5670. that the runtime tag matches the target type $T$ and exiting if there
  5671. is a mismatch. However, the way in which we convert the tagged value
  5672. to a value is different, as there is no need to shift. Instead we need
  5673. to zero-out the rightmost 2 bits. We accomplish this by creating the
  5674. bit pattern $\ldots 0011$, applying \code{notq} to obtain $\ldots
  5675. 1100$, and then applying \code{andq} with the tagged value get the
  5676. desired result. \\
  5677. %
  5678. \begin{tabular}{lll}
  5679. \begin{minipage}{0.4\textwidth}
  5680. \begin{lstlisting}
  5681. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5682. \end{lstlisting}
  5683. \end{minipage}
  5684. &
  5685. $\Rightarrow$
  5686. &
  5687. \begin{minipage}{0.5\textwidth}
  5688. \begin{lstlisting}
  5689. (movq |$e'$| |\itm{lhs}'|)
  5690. (andq (int 3) |\itm{lhs}'|)
  5691. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5692. ((movq (int 3) |\itm{lhs}'|)
  5693. (notq |\itm{lhs}'|)
  5694. (andq |$e'$| |\itm{lhs}'|))
  5695. ((callq exit)))
  5696. \end{lstlisting}
  5697. \end{minipage}
  5698. \end{tabular} \\
  5699. \paragraph{Type Predicates} We leave it to the reader to
  5700. devise a sequence of instructions to implement the type predicates
  5701. \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  5702. \section{Compiling $R_7$ to $R_6$}
  5703. \label{sec:compile-r7}
  5704. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  5705. $R_7$ forms into $R_6$. An important invariant of this pass is that
  5706. given a subexpression $e$ of $R_7$, the pass will produce an
  5707. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  5708. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  5709. the Boolean \code{\#t}, which must be injected to produce an
  5710. expression of type \key{Any}.
  5711. %
  5712. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  5713. addition, is representative of compilation for many operations: the
  5714. arguments have type \key{Any} and must be projected to \key{Integer}
  5715. before the addition can be performed.
  5716. %
  5717. The compilation of \key{lambda} (third row of
  5718. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  5719. produce type annotations, we simply use \key{Any}.
  5720. %
  5721. The compilation of \code{if}, \code{eq?}, and \code{and} all
  5722. demonstrate how this pass has to account for some differences in
  5723. behavior between $R_7$ and $R_6$. The $R_7$ language is more
  5724. permissive than $R_6$ regarding what kind of values can be used in
  5725. various places. For example, the condition of an \key{if} does not
  5726. have to be a Boolean. Similarly, the arguments of \key{and} do not
  5727. need to be Boolean. For \key{eq?}, the arguments need not be of the
  5728. same type.
  5729. \begin{figure}[tbp]
  5730. \centering
  5731. \begin{tabular}{|lll|} \hline
  5732. \begin{minipage}{0.25\textwidth}
  5733. \begin{lstlisting}
  5734. #t
  5735. \end{lstlisting}
  5736. \end{minipage}
  5737. &
  5738. $\Rightarrow$
  5739. &
  5740. \begin{minipage}{0.6\textwidth}
  5741. \begin{lstlisting}
  5742. (inject #t Boolean)
  5743. \end{lstlisting}
  5744. \end{minipage}
  5745. \\[2ex]\hline
  5746. \begin{minipage}{0.25\textwidth}
  5747. \begin{lstlisting}
  5748. (+ |$e_1$| |$e_2$|)
  5749. \end{lstlisting}
  5750. \end{minipage}
  5751. &
  5752. $\Rightarrow$
  5753. &
  5754. \begin{minipage}{0.6\textwidth}
  5755. \begin{lstlisting}
  5756. (inject
  5757. (+ (project |$e'_1$| Integer)
  5758. (project |$e'_2$| Integer))
  5759. Integer)
  5760. \end{lstlisting}
  5761. \end{minipage}
  5762. \\[2ex]\hline
  5763. \begin{minipage}{0.25\textwidth}
  5764. \begin{lstlisting}
  5765. (lambda (|$x_1 \ldots$|) |$e$|)
  5766. \end{lstlisting}
  5767. \end{minipage}
  5768. &
  5769. $\Rightarrow$
  5770. &
  5771. \begin{minipage}{0.6\textwidth}
  5772. \begin{lstlisting}
  5773. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  5774. (Any|$\ldots$|Any -> Any))
  5775. \end{lstlisting}
  5776. \end{minipage}
  5777. \\[2ex]\hline
  5778. \begin{minipage}{0.25\textwidth}
  5779. \begin{lstlisting}
  5780. (app |$e_0$| |$e_1 \ldots e_n$|)
  5781. \end{lstlisting}
  5782. \end{minipage}
  5783. &
  5784. $\Rightarrow$
  5785. &
  5786. \begin{minipage}{0.6\textwidth}
  5787. \begin{lstlisting}
  5788. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  5789. |$e'_1 \ldots e'_n$|)
  5790. \end{lstlisting}
  5791. \end{minipage}
  5792. \\[2ex]\hline
  5793. \begin{minipage}{0.25\textwidth}
  5794. \begin{lstlisting}
  5795. (vector-ref |$e_1$| |$e_2$|)
  5796. \end{lstlisting}
  5797. \end{minipage}
  5798. &
  5799. $\Rightarrow$
  5800. &
  5801. \begin{minipage}{0.6\textwidth}
  5802. \begin{lstlisting}
  5803. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  5804. (let ([tmp2 (project |$e'_2$| Integer)])
  5805. (vector-ref tmp1 tmp2)))
  5806. \end{lstlisting}
  5807. \end{minipage}
  5808. \\[2ex]\hline
  5809. \begin{minipage}{0.25\textwidth}
  5810. \begin{lstlisting}
  5811. (if |$e_1$| |$e_2$| |$e_3$|)
  5812. \end{lstlisting}
  5813. \end{minipage}
  5814. &
  5815. $\Rightarrow$
  5816. &
  5817. \begin{minipage}{0.6\textwidth}
  5818. \begin{lstlisting}
  5819. (if (eq? |$e'_1$| (inject #f Boolean))
  5820. |$e'_3$|
  5821. |$e'_2$|)
  5822. \end{lstlisting}
  5823. \end{minipage}
  5824. \\[2ex]\hline
  5825. \begin{minipage}{0.25\textwidth}
  5826. \begin{lstlisting}
  5827. (eq? |$e_1$| |$e_2$|)
  5828. \end{lstlisting}
  5829. \end{minipage}
  5830. &
  5831. $\Rightarrow$
  5832. &
  5833. \begin{minipage}{0.6\textwidth}
  5834. \begin{lstlisting}
  5835. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  5836. \end{lstlisting}
  5837. \end{minipage}
  5838. \\[2ex]\hline
  5839. \begin{minipage}{0.25\textwidth}
  5840. \begin{lstlisting}
  5841. (and |$e_1$| |$e_2$|)
  5842. \end{lstlisting}
  5843. \end{minipage}
  5844. &
  5845. $\Rightarrow$
  5846. &
  5847. \begin{minipage}{0.6\textwidth}
  5848. \begin{lstlisting}
  5849. (let ([tmp |$e'_1$|])
  5850. (if (eq? tmp (inject #f Boolean))
  5851. tmp
  5852. |$e'_2$|))
  5853. \end{lstlisting}
  5854. \end{minipage} \\\hline
  5855. \end{tabular} \\
  5856. \caption{Compiling $R_7$ to $R_6$.}
  5857. \label{fig:compile-r7-r6}
  5858. \end{figure}
  5859. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5860. \chapter{Gradual Typing}
  5861. \label{ch:gradual-typing}
  5862. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  5863. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5864. \chapter{Parametric Polymorphism}
  5865. \label{ch:parametric-polymorphism}
  5866. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  5867. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  5868. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5869. \chapter{High-level Optimization}
  5870. \label{ch:high-level-optimization}
  5871. This chapter will present a procedure inlining pass based on the
  5872. algorithm of \citet{Waddell:1997fk}.
  5873. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5874. \chapter{Appendix}
  5875. \section{Interpreters}
  5876. \label{appendix:interp}
  5877. We provide several interpreters in the \key{interp.rkt} file. The
  5878. \key{interp-scheme} function takes an AST in one of the Racket-like
  5879. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  5880. the program, returning the result value. The \key{interp-C} function
  5881. interprets an AST for a program in one of the C-like languages ($C_0,
  5882. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  5883. for an x86 program.
  5884. \section{Utility Functions}
  5885. \label{appendix:utilities}
  5886. The utility function described in this section can be found in the
  5887. \key{utilities.rkt} file.
  5888. The \key{read-program} function takes a file path and parses that file
  5889. (it must be a Racket program) into an abstract syntax tree (as an
  5890. S-expression) with a \key{program} AST at the top.
  5891. The \key{assert} function displays the error message \key{msg} if the
  5892. Boolean \key{bool} is false.
  5893. \begin{lstlisting}
  5894. (define (assert msg bool) ...)
  5895. \end{lstlisting}
  5896. The \key{lookup} function ...
  5897. The \key{map2} function ...
  5898. \subsection{Graphs}
  5899. \begin{itemize}
  5900. \item The \code{make-graph} function takes a list of vertices
  5901. (symbols) and returns a graph.
  5902. \item The \code{add-edge} function takes a graph and two vertices and
  5903. adds an edge to the graph that connects the two vertices. The graph
  5904. is updated in-place. There is no return value for this function.
  5905. \item The \code{adjacent} function takes a graph and a vertex and
  5906. returns the set of vertices that are adjacent to the given
  5907. vertex. The return value is a Racket \code{hash-set} so it can be
  5908. used with functions from the \code{racket/set} module.
  5909. \item The \code{vertices} function takes a graph and returns the list
  5910. of vertices in the graph.
  5911. \end{itemize}
  5912. \subsection{Testing}
  5913. The \key{interp-tests} function takes a compiler name (a string), a
  5914. description of the passes, an interpreter for the source language, a
  5915. test family name (a string), and a list of test numbers, and runs the
  5916. compiler passes and the interpreters to check whether the passes
  5917. correct. The description of the passes is a list with one entry per
  5918. pass. An entry is a list with three things: a string giving the name
  5919. of the pass, the function that implements the pass (a translator from
  5920. AST to AST), and a function that implements the interpreter (a
  5921. function from AST to result value) for the language of the output of
  5922. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  5923. good choice. The \key{interp-tests} function assumes that the
  5924. subdirectory \key{tests} has a bunch of Scheme programs whose names
  5925. all start with the family name, followed by an underscore and then the
  5926. test number, ending in \key{.scm}. Also, for each Scheme program there
  5927. is a file with the same number except that it ends with \key{.in} that
  5928. provides the input for the Scheme program.
  5929. \begin{lstlisting}
  5930. (define (interp-tests name passes test-family test-nums) ...
  5931. \end{lstlisting}
  5932. The compiler-tests function takes a compiler name (a string) a
  5933. description of the passes (see the comment for \key{interp-tests}) a
  5934. test family name (a string), and a list of test numbers (see the
  5935. comment for interp-tests), and runs the compiler to generate x86 (a
  5936. \key{.s} file) and then runs gcc to generate machine code. It runs
  5937. the machine code and checks that the output is 42.
  5938. \begin{lstlisting}
  5939. (define (compiler-tests name passes test-family test-nums) ...)
  5940. \end{lstlisting}
  5941. The compile-file function takes a description of the compiler passes
  5942. (see the comment for \key{interp-tests}) and returns a function that,
  5943. given a program file name (a string ending in \key{.scm}), applies all
  5944. of the passes and writes the output to a file whose name is the same
  5945. as the program file name but with \key{.scm} replaced with \key{.s}.
  5946. \begin{lstlisting}
  5947. (define (compile-file passes)
  5948. (lambda (prog-file-name) ...))
  5949. \end{lstlisting}
  5950. \section{x86 Instruction Set Quick-Reference}
  5951. \label{sec:x86-quick-reference}
  5952. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  5953. do. We write $A \to B$ to mean that the value of $A$ is written into
  5954. location $B$. Address offsets are given in bytes. The instruction
  5955. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  5956. registers (such as $\%rax$), or memory references (such as
  5957. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  5958. reference per instruction. Other operands must be immediates or
  5959. registers.
  5960. \begin{table}[tbp]
  5961. \centering
  5962. \begin{tabular}{l|l}
  5963. \textbf{Instruction} & \textbf{Operation} \\ \hline
  5964. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  5965. \texttt{negq} $A$ & $- A \to A$ \\
  5966. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  5967. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  5968. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  5969. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  5970. \texttt{retq} & Pops the return address and jumps to it \\
  5971. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  5972. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  5973. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  5974. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set flag \\
  5975. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag matches
  5976. the condition code, otherwise go to the next instructions.
  5977. The condition codes are \key{e} for ``equal'',
  5978. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  5979. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  5980. \texttt{jl} $L$ & \\
  5981. \texttt{jle} $L$ & \\
  5982. \texttt{jg} $L$ & \\
  5983. \texttt{jge} $L$ & \\
  5984. \texttt{jmp} $L$ & Jump to label $L$ \\
  5985. \texttt{movq} $A$, $B$ & $A \to B$ \\
  5986. \texttt{movzbq} $A$, $B$ &
  5987. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  5988. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  5989. and the extra bytes of $B$ are set to zero.} \\
  5990. & \\
  5991. & \\
  5992. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  5993. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  5994. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  5995. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  5996. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  5997. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  5998. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  5999. description of the condition codes. $A$ must be a single byte register
  6000. (e.g., \texttt{al} or \texttt{cl}).} \\
  6001. \texttt{setl} $A$ & \\
  6002. \texttt{setle} $A$ & \\
  6003. \texttt{setg} $A$ & \\
  6004. \texttt{setge} $A$ &
  6005. \end{tabular}
  6006. \vspace{5pt}
  6007. \caption{Quick-reference for the x86 instructions used in this book.}
  6008. \label{tab:x86-instr}
  6009. \end{table}
  6010. \bibliographystyle{plainnat}
  6011. \bibliography{all}
  6012. \end{document}
  6013. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6014. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6015. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6016. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6017. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6018. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6019. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6020. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6021. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6022. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6023. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6024. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6025. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6026. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6027. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6028. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6029. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6030. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6031. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6032. %% LocalWords: len prev rootlen heaplen setl lt