book.tex 251 KB

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