book.tex 303 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{multirow}
  49. \usepackage{color}
  50. \usepackage{upquote}
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. %% For pictures
  55. \usepackage{tikz}
  56. \usetikzlibrary{arrows.meta}
  57. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  58. % Computer Modern is already the default. -Jeremy
  59. %\renewcommand{\ttdefault}{cmtt}
  60. \definecolor{comment-red}{rgb}{0.8,0,0}
  61. \if{0}
  62. % Peanut gallery comments:
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{#1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then},
  73. deletekeywords={read},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~}
  77. }
  78. \newtheorem{theorem}{Theorem}
  79. \newtheorem{lemma}[theorem]{Lemma}
  80. \newtheorem{corollary}[theorem]{Corollary}
  81. \newtheorem{proposition}[theorem]{Proposition}
  82. \newtheorem{constraint}[theorem]{Constraint}
  83. \newtheorem{definition}[theorem]{Definition}
  84. \newtheorem{exercise}[theorem]{Exercise}
  85. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  86. % 'dedication' environment: To add a dedication paragraph at the start of book %
  87. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  88. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  89. \newenvironment{dedication}
  90. {
  91. \cleardoublepage
  92. \thispagestyle{empty}
  93. \vspace*{\stretch{1}}
  94. \hfill\begin{minipage}[t]{0.66\textwidth}
  95. \raggedright
  96. }
  97. {
  98. \end{minipage}
  99. \vspace*{\stretch{3}}
  100. \clearpage
  101. }
  102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  103. % Chapter quote at the start of chapter %
  104. % Source: http://tex.stackexchange.com/a/53380 %
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. \makeatletter
  107. \renewcommand{\@chapapp}{}% Not necessary...
  108. \newenvironment{chapquote}[2][2em]
  109. {\setlength{\@tempdima}{#1}%
  110. \def\chapquote@author{#2}%
  111. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  112. \itshape}
  113. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  114. \makeatother
  115. \input{defs}
  116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  117. \title{\Huge \textbf{Essentials of Compilation} \\
  118. \huge An Incremental Approach}
  119. \author{\textsc{Jeremy G. Siek} \\
  120. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  121. Indiana University \\
  122. \\
  123. with contributions from: \\
  124. Carl Factora \\
  125. Andre Kuhlenschmidt \\
  126. Ryan R. Newton \\
  127. Ryan Scott \\
  128. Cameron Swords \\
  129. Michael M. Vitousek \\
  130. Michael Vollmer
  131. }
  132. \begin{document}
  133. \frontmatter
  134. \maketitle
  135. \begin{dedication}
  136. This book is dedicated to the programming language wonks at Indiana
  137. University.
  138. \end{dedication}
  139. \tableofcontents
  140. \listoffigures
  141. %\listoftables
  142. \mainmatter
  143. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  144. \chapter*{Preface}
  145. The tradition of compiler writing at Indiana University goes back to
  146. research and courses about programming languages by Daniel Friedman in
  147. the 1970's and 1980's. Dan conducted research on lazy
  148. evaluation~\citep{Friedman:1976aa} in the context of
  149. Lisp~\citep{McCarthy:1960dz} and then studied
  150. continuations~\citep{Felleisen:kx} and
  151. macros~\citep{Kohlbecker:1986dk} in the context of the
  152. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  153. of those courses, Kent Dybvig, went on to build Chez
  154. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  155. compiler for Scheme. After completing his Ph.D. at the University of
  156. North Carolina, Kent returned to teach at Indiana University.
  157. Throughout the 1990's and 2000's, Kent continued development of Chez
  158. Scheme and taught the compiler course.
  159. The compiler course evolved to incorporate novel pedagogical ideas
  160. while also including elements of effective real-world compilers. One
  161. of Dan's ideas was to split the compiler into many small ``passes'' so
  162. that the code for each pass would be easy to understood in isolation.
  163. (In contrast, most compilers of the time were organized into only a
  164. few monolithic passes for reasons of compile-time efficiency.) Kent,
  165. with later help from his students Dipanwita Sarkar and Andrew Keep,
  166. developed infrastructure to support this approach and evolved the
  167. course, first to use micro-sized passes and then into even smaller
  168. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  169. student in this compiler course in the early 2000's, as part of his
  170. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  171. the course immensely!
  172. During that time, another student named Abdulaziz Ghuloum observed
  173. that the front-to-back organization of the course made it difficult
  174. for students to understand the rationale for the compiler
  175. design. Abdulaziz proposed an incremental approach in which the
  176. students build the compiler in stages; they start by implementing a
  177. complete compiler for a very small subset of the input language and in
  178. each subsequent stage they add a language feature and add or modify
  179. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  180. the students see how the language features motivate aspects of the
  181. compiler design.
  182. After graduating from Indiana University in 2005, Jeremy went on to
  183. teach at the University of Colorado. He adapted the nano pass and
  184. incremental approaches to compiling a subset of the Python
  185. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  186. on the surface but there is a large overlap in the compiler techniques
  187. required for the two languages. Thus, Jeremy was able to teach much of
  188. the same content from the Indiana compiler course. He very much
  189. enjoyed teaching the course organized in this way, and even better,
  190. many of the students learned a lot and got excited about compilers.
  191. Jeremy returned to teach at Indiana University in 2013. In his
  192. absence the compiler course had switched from the front-to-back
  193. organization to a back-to-front organization. Seeing how well the
  194. incremental approach worked at Colorado, he started porting and
  195. adapting the structure of the Colorado course back into the land of
  196. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  197. the course is now about compiling a subset of Racket (and Typed
  198. Racket) to the x86 assembly language. The compiler is implemented in
  199. Racket 7.1~\citep{plt-tr}.
  200. This is the textbook for the incremental version of the compiler
  201. course at Indiana University (Spring 2016 - present) and it is the
  202. first open textbook for an Indiana compiler course. With this book we
  203. hope to make the Indiana compiler course available to people that have
  204. not had the chance to study in Bloomington in person. Many of the
  205. compiler design decisions in this book are drawn from the assignment
  206. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  207. are the most important topics from \cite{Dybvig:2010aa} but we have
  208. omitted topics that we think are less interesting conceptually and we
  209. have made simplifications to reduce complexity. In this way, this
  210. book leans more towards pedagogy than towards the efficiency of the
  211. generated code. Also, the book differs in places where we saw the
  212. opportunity to make the topics more fun, such as in relating register
  213. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  214. \section*{Prerequisites}
  215. The material in this book is challenging but rewarding. It is meant to
  216. prepare students for a lifelong career in programming languages.
  217. The book uses the Racket language both for the implementation of the
  218. compiler and for the language that is compiled, so a student should be
  219. proficient with Racket (or Scheme) prior to reading this book. There
  220. are many excellent resources for learning Scheme and
  221. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  222. is helpful but not necessary for the student to have prior exposure to
  223. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  224. obtain from a computer systems
  225. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  226. parts of x86-64 assembly language that are needed.
  227. %\section*{Structure of book}
  228. % You might want to add short description about each chapter in this book.
  229. %\section*{About the companion website}
  230. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  231. %\begin{itemize}
  232. % \item A link to (freely downlodable) latest version of this document.
  233. % \item Link to download LaTeX source for this document.
  234. % \item Miscellaneous material (e.g. suggested readings etc).
  235. %\end{itemize}
  236. \section*{Acknowledgments}
  237. Many people have contributed to the ideas, techniques, organization,
  238. and teaching of the materials in this book. We especially thank the
  239. following people.
  240. \begin{itemize}
  241. \item Bor-Yuh Evan Chang
  242. \item Kent Dybvig
  243. \item Daniel P. Friedman
  244. \item Ronald Garcia
  245. \item Abdulaziz Ghuloum
  246. \item Jay McCarthy
  247. \item Dipanwita Sarkar
  248. \item Andrew Keep
  249. \item Oscar Waddell
  250. \item Michael Wollowski
  251. \end{itemize}
  252. \mbox{}\\
  253. \noindent Jeremy G. Siek \\
  254. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  255. %\noindent Spring 2016
  256. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  257. \chapter{Preliminaries}
  258. \label{ch:trees-recur}
  259. In this chapter we review the basic tools that are needed to implement
  260. a compiler. Programs are typically input by a programmer as text,
  261. i.e., a sequence of characters. The program-as-text representation is
  262. called \emph{concrete syntax}. We use concrete syntax to concisely
  263. write down and talk about programs. Inside the compiler, we use
  264. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  265. that efficiently supports the operations that the compiler needs to
  266. perform.
  267. %
  268. The translation from concrete syntax to abstract syntax is a process
  269. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  270. and implementation of parsing in this book. A parser is provided in
  271. the supporting materials for translating from concrete syntax to
  272. abstract syntax for the languages used in this book.
  273. ASTs can be represented in many different ways inside the compiler,
  274. depending on the programming language used to write the compiler.
  275. %
  276. We use Racket's \code{struct} feature to represent ASTs
  277. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  278. of programming languages (Section~\ref{sec:grammar}) and pattern
  279. matching to inspect individual nodes in an AST
  280. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  281. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  282. chapter provides an brief introduction to these ideas.
  283. \section{Abstract Syntax Trees and Racket Structures}
  284. \label{sec:ast}
  285. Compilers use abstract syntax trees to represent programs because
  286. compilers often need to ask questions like: for a given part of a
  287. program, what kind of language feature is it? What are the sub-parts
  288. of this part of the program? Consider the program on the left and its
  289. AST on the right. This program is an addition and it has two
  290. sub-parts, a read operation and a negation. The negation has another
  291. sub-part, the integer constant \code{8}. By using a tree to represent
  292. the program, we can easily follow the links to go from one part of a
  293. program to its sub-parts.
  294. \begin{center}
  295. \begin{minipage}{0.4\textwidth}
  296. \begin{lstlisting}
  297. (+ (read) (- 8))
  298. \end{lstlisting}
  299. \end{minipage}
  300. \begin{minipage}{0.4\textwidth}
  301. \begin{equation}
  302. \begin{tikzpicture}
  303. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  304. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  305. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  306. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  307. \draw[->] (plus) to (read);
  308. \draw[->] (plus) to (minus);
  309. \draw[->] (minus) to (8);
  310. \end{tikzpicture}
  311. \label{eq:arith-prog}
  312. \end{equation}
  313. \end{minipage}
  314. \end{center}
  315. We use the standard terminology for trees to describe ASTs: each
  316. circle above is called a \emph{node}. The arrows connect a node to its
  317. \emph{children} (which are also nodes). The top-most node is the
  318. \emph{root}. Every node except for the root has a \emph{parent} (the
  319. node it is the child of). If a node has no children, it is a
  320. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  321. %% Recall that an \emph{symbolic expression} (S-expression) is either
  322. %% \begin{enumerate}
  323. %% \item an atom, or
  324. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  325. %% where $e_1$ and $e_2$ are each an S-expression.
  326. %% \end{enumerate}
  327. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  328. %% null value \code{'()}, etc. We can create an S-expression in Racket
  329. %% simply by writing a backquote (called a quasi-quote in Racket)
  330. %% followed by the textual representation of the S-expression. It is
  331. %% quite common to use S-expressions to represent a list, such as $a, b
  332. %% ,c$ in the following way:
  333. %% \begin{lstlisting}
  334. %% `(a . (b . (c . ())))
  335. %% \end{lstlisting}
  336. %% Each element of the list is in the first slot of a pair, and the
  337. %% second slot is either the rest of the list or the null value, to mark
  338. %% the end of the list. Such lists are so common that Racket provides
  339. %% special notation for them that removes the need for the periods
  340. %% and so many parenthesis:
  341. %% \begin{lstlisting}
  342. %% `(a b c)
  343. %% \end{lstlisting}
  344. %% The following expression creates an S-expression that represents AST
  345. %% \eqref{eq:arith-prog}.
  346. %% \begin{lstlisting}
  347. %% `(+ (read) (- 8))
  348. %% \end{lstlisting}
  349. %% When using S-expressions to represent ASTs, the convention is to
  350. %% represent each AST node as a list and to put the operation symbol at
  351. %% the front of the list. The rest of the list contains the children. So
  352. %% in the above case, the root AST node has operation \code{`+} and its
  353. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  354. %% diagram \eqref{eq:arith-prog}.
  355. %% To build larger S-expressions one often needs to splice together
  356. %% several smaller S-expressions. Racket provides the comma operator to
  357. %% splice an S-expression into a larger one. For example, instead of
  358. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  359. %% we could have first created an S-expression for AST
  360. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  361. %% S-expression.
  362. %% \begin{lstlisting}
  363. %% (define ast1.4 `(- 8))
  364. %% (define ast1.1 `(+ (read) ,ast1.4))
  365. %% \end{lstlisting}
  366. %% In general, the Racket expression that follows the comma (splice)
  367. %% can be any expression that produces an S-expression.
  368. We define a Racket \code{struct} for each kind of node. For this
  369. chapter we require just two kinds of nodes: one for integer constants
  370. and one for primitive operations. The following is the \code{struct}
  371. definition for integer constants.
  372. \begin{lstlisting}
  373. (struct Int (value))
  374. \end{lstlisting}
  375. An integer node includes just one thing: the integer value.
  376. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  377. \begin{lstlisting}
  378. (define eight (Int 8))
  379. \end{lstlisting}
  380. We say that the value created by \code{(Int 8)} is an
  381. \emph{instance} of the \code{Int} structure.
  382. The following is the \code{struct} definition for primitives operations.
  383. \begin{lstlisting}
  384. (struct Prim (op arg*))
  385. \end{lstlisting}
  386. A primitive operation node includes an operator symbol \code{op}
  387. and a list of children \code{arg*}. For example, to create
  388. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  389. \begin{lstlisting}
  390. (define neg-eight (Prim '- (list eight)))
  391. \end{lstlisting}
  392. Primitive operations may have zero or more children. The \code{read}
  393. operator has zero children:
  394. \begin{lstlisting}
  395. (define rd (Prim 'read '()))
  396. \end{lstlisting}
  397. whereas the addition operator has two children:
  398. \begin{lstlisting}
  399. (define ast1.1 (Prim '+ (list rd neg-eight)))
  400. \end{lstlisting}
  401. We have made a design choice regarding the \code{Prim} structure.
  402. Instead of using one structure for many different operations
  403. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  404. structure for each operation, as follows.
  405. \begin{lstlisting}
  406. (struct Read ())
  407. (struct Add (left right))
  408. (struct Neg (value))
  409. \end{lstlisting}
  410. The reason we choose to use just one structure is that in many parts
  411. of the compiler the code for the different primitive operators is the
  412. same, so we might as well just write that code once, which is enabled
  413. by using a single structure.
  414. When compiling a program such as \eqref{eq:arith-prog}, we need to
  415. know that the operation associated with the root node is addition and
  416. we need to be able to access its two children. Racket provides pattern
  417. matching over structures to support these kinds of queries, as we
  418. shall see in Section~\ref{sec:pattern-matching}.
  419. In this book, we often write down the concrete syntax of a program
  420. even when we really have in mind the AST because the concrete syntax
  421. is more concise. We recommend that, in your mind, you always think of
  422. programs as abstract syntax trees.
  423. \section{Grammars}
  424. \label{sec:grammar}
  425. A programming language can be thought of as a \emph{set} of programs.
  426. The set is typically infinite (one can always create larger and larger
  427. programs), so one cannot simply describe a language by listing all of
  428. the programs in the language. Instead we write down a set of rules, a
  429. \emph{grammar}, for building programs. Grammars are often used to
  430. define the concrete syntax of a language, but they can also be used to
  431. describe the abstract syntax. We shall write our rules in a variant of
  432. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  433. example, we describe a small language, named $R_0$, that consists of
  434. integers and arithmetic operations.
  435. The first grammar rule for the abstract syntax of $R_0$ says that an
  436. instance of the \code{Int} structure is an expression:
  437. \begin{equation}
  438. \Exp ::= \INT{\Int} \label{eq:arith-int}
  439. \end{equation}
  440. %
  441. Each rule has a left-hand-side and a right-hand-side. The way to read
  442. a rule is that if you have all the program parts on the
  443. right-hand-side, then you can create an AST node and categorize it
  444. according to the left-hand-side.
  445. %
  446. A name such as $\Exp$ that is
  447. defined by the grammar rules is a \emph{non-terminal}.
  448. %
  449. The name $\Int$ is a also a non-terminal, but instead of defining it
  450. with a grammar rule, we define it with the following explanation. We
  451. make the simplifying design decision that all of the languages in this
  452. book only handle machine-representable integers. On most modern
  453. machines this corresponds to integers represented with 64-bits, i.e.,
  454. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  455. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  456. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  457. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  458. that the sequence of decimals represent an integer in range $-2^{62}$
  459. to $2^{62}-1$.
  460. The second grammar rule is the \texttt{read} operation that receives
  461. an input integer from the user of the program.
  462. \begin{equation}
  463. \Exp ::= \READ{} \label{eq:arith-read}
  464. \end{equation}
  465. The third rule says that, given an $\Exp$ node, you can build another
  466. $\Exp$ node by negating it.
  467. \begin{equation}
  468. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  469. \end{equation}
  470. Symbols in typewriter font such as \key{-} and \key{read} are
  471. \emph{terminal} symbols and must literally appear in the program for
  472. the rule to be applicable.
  473. We can apply the rules to build ASTs in the $R_0$
  474. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  475. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  476. an $\Exp$.
  477. \begin{center}
  478. \begin{minipage}{0.4\textwidth}
  479. \begin{lstlisting}
  480. (Prim '- (list (Int 8)))
  481. \end{lstlisting}
  482. \end{minipage}
  483. \begin{minipage}{0.25\textwidth}
  484. \begin{equation}
  485. \begin{tikzpicture}
  486. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  487. \node[draw, circle] (8) at (0, -1.2) {$8$};
  488. \draw[->] (minus) to (8);
  489. \end{tikzpicture}
  490. \label{eq:arith-neg8}
  491. \end{equation}
  492. \end{minipage}
  493. \end{center}
  494. The next grammar rule defines addition expressions:
  495. \begin{equation}
  496. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  497. \end{equation}
  498. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  499. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  500. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  501. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  502. to show that
  503. \begin{lstlisting}
  504. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  505. \end{lstlisting}
  506. is an $\Exp$ in the $R_0$ language.
  507. If you have an AST for which the above rules do not apply, then the
  508. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  509. is not in $R_0$ because there are no rules for \code{+} with only one
  510. argument, nor for \key{-} with two arguments. Whenever we define a
  511. language with a grammar, the language only includes those programs
  512. that are justified by the rules.
  513. The last grammar rule for $R_0$ states that there is a \code{Program}
  514. node to mark the top of the whole program:
  515. \[
  516. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  517. \]
  518. The \code{Program} structure is defined as follows
  519. \begin{lstlisting}
  520. (struct Program (info body))
  521. \end{lstlisting}
  522. where \code{body} is an expression. In later chapters, the \code{info}
  523. part will be used to store auxiliary information but for now it is
  524. just the empty list.
  525. It is common to have many grammar rules with the same left-hand side
  526. but different right-hand sides, such as the rules for $\Exp$ in the
  527. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  528. combine several right-hand-sides into a single rule.
  529. We collect all of the grammar rules for the abstract syntax of $R_0$
  530. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  531. defined in Figure~\ref{fig:r0-concrete-syntax}.
  532. The \code{read-program} function provided in \code{utilities.rkt} of
  533. the support materials reads a program in from a file (the sequence of
  534. characters in the concrete syntax of Racket) and parses it into an
  535. abstract syntax tree. See the description of \code{read-program} in
  536. Appendix~\ref{appendix:utilities} for more details.
  537. \begin{figure}[tp]
  538. \fbox{
  539. \begin{minipage}{0.96\textwidth}
  540. \[
  541. \begin{array}{rcl}
  542. \begin{array}{rcl}
  543. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)
  544. \mid (\key{-}\;\Exp\;\Exp) \\
  545. R_0 &::=& \Exp
  546. \end{array}
  547. \end{array}
  548. \]
  549. \end{minipage}
  550. }
  551. \caption{The concrete syntax of $R_0$.}
  552. \label{fig:r0-concrete-syntax}
  553. \end{figure}
  554. \begin{figure}[tp]
  555. \fbox{
  556. \begin{minipage}{0.96\textwidth}
  557. \[
  558. \begin{array}{rcl}
  559. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  560. &\mid& \ADD{\Exp}{\Exp} \\
  561. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  562. \end{array}
  563. \]
  564. \end{minipage}
  565. }
  566. \caption{The abstract syntax of $R_0$.}
  567. \label{fig:r0-syntax}
  568. \end{figure}
  569. \section{Pattern Matching}
  570. \label{sec:pattern-matching}
  571. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  572. the parts of an AST node. Racket provides the \texttt{match} form to
  573. access the parts of a structure. Consider the following example and
  574. the output on the right.
  575. \begin{center}
  576. \begin{minipage}{0.5\textwidth}
  577. \begin{lstlisting}
  578. (match ast1.1
  579. [(Prim op (list child1 child2))
  580. (print op)])
  581. \end{lstlisting}
  582. \end{minipage}
  583. \vrule
  584. \begin{minipage}{0.25\textwidth}
  585. \begin{lstlisting}
  586. '+
  587. \end{lstlisting}
  588. \end{minipage}
  589. \end{center}
  590. In the above example, the \texttt{match} form takes the AST
  591. \eqref{eq:arith-prog} and binds its parts to the three pattern
  592. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  593. general, a match clause consists of a \emph{pattern} and a
  594. \emph{body}. Patterns are recursively defined to be either a pattern
  595. variable, a structure name followed by a pattern for each of the
  596. structure's arguments, or an S-expression (symbols, lists, etc.).
  597. (See Chapter 12 of The Racket
  598. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  599. and Chapter 9 of The Racket
  600. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  601. for a complete description of \code{match}.)
  602. %
  603. The body of a match clause may contain arbitrary Racket code. The
  604. pattern variables can be used in the scope of the body.
  605. A \code{match} form may contain several clauses, as in the following
  606. function \code{leaf?} that recognizes when an $R_0$ node is
  607. a leaf. The \code{match} proceeds through the clauses in order,
  608. checking whether the pattern can match the input AST. The
  609. body of the first clause that matches is executed. The output of
  610. \code{leaf?} for several ASTs is shown on the right.
  611. \begin{center}
  612. \begin{minipage}{0.6\textwidth}
  613. \begin{lstlisting}
  614. (define (leaf? arith)
  615. (match arith
  616. [(Int n) #t]
  617. [(Prim 'read '()) #t]
  618. [(Prim '- (list c1)) #f]
  619. [(Prim '+ (list c1 c2)) #f]))
  620. (leaf? (Prim 'read '()))
  621. (leaf? (Prim '- (list (Int 8))))
  622. (leaf? (Int 8))
  623. \end{lstlisting}
  624. \end{minipage}
  625. \vrule
  626. \begin{minipage}{0.25\textwidth}
  627. \begin{lstlisting}
  628. #t
  629. #f
  630. #t
  631. \end{lstlisting}
  632. \end{minipage}
  633. \end{center}
  634. When writing a \code{match}, we refer to the grammar definition to
  635. identify which non-terminal we are expecting to match against, then we
  636. make sure that 1) we have one clause for each alternative of that
  637. non-terminal and 2) that the pattern in each clause corresponds to the
  638. corresponding right-hand side of a grammar rule. For the \code{match}
  639. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  640. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  641. alternatives, so the \code{match} has 4 clauses. The pattern in each
  642. clause corresponds to the right-hand side of a grammar rule. For
  643. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  644. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  645. patterns, replace non-terminals such as $\Exp$ with pattern variables
  646. of your choice (e.g. \code{c1} and \code{c2}).
  647. \section{Recursion}
  648. \label{sec:recursion}
  649. Programs are inherently recursive. For example, an $R_0$ expression is
  650. often made of smaller expressions. Thus, the natural way to process an
  651. entire program is with a recursive function. As a first example of
  652. such a recursive function, we define \texttt{exp?} below, which takes
  653. an arbitrary value and determines whether or not it is an $R_0$
  654. expression.
  655. %
  656. When a recursive function is defined using a sequence of match clauses
  657. that correspond to a grammar, and the body of each clause makes a
  658. recursive call on each child node, then we say the function is defined
  659. by \emph{structural recursion}\footnote{This principle of structuring
  660. code according to the data definition is advocated in the book
  661. \emph{How to Design Programs}
  662. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  663. define a second function, named \code{R0?}, that determines whether a
  664. value is an $R_0$ program. In general we can expect to write one
  665. recursive function to handle each non-terminal in a grammar.
  666. %
  667. \begin{center}
  668. \begin{minipage}{0.7\textwidth}
  669. \begin{lstlisting}
  670. (define (exp? ast)
  671. (match ast
  672. [(Int n) #t]
  673. [(Prim 'read '()) #t]
  674. [(Prim '- (list e)) (exp? e)]
  675. [(Prim '+ (list e1 e2))
  676. (and (exp? e1) (exp? e2))]
  677. [else #f]))
  678. (define (R0? ast)
  679. (match ast
  680. [(Program '() e) (exp? e)]
  681. [else #f]))
  682. (R0? (Program '() ast1.1)
  683. (R0? (Program '()
  684. (Prim '- (list (Prim 'read '())
  685. (Prim '+ (list (Num 8)))))))
  686. \end{lstlisting}
  687. \end{minipage}
  688. \vrule
  689. \begin{minipage}{0.25\textwidth}
  690. \begin{lstlisting}
  691. #t
  692. #f
  693. \end{lstlisting}
  694. \end{minipage}
  695. \end{center}
  696. You may be tempted to merge the two functions into one, like this:
  697. \begin{center}
  698. \begin{minipage}{0.5\textwidth}
  699. \begin{lstlisting}
  700. (define (R0? ast)
  701. (match ast
  702. [(Int n) #t]
  703. [(Prim 'read '()) #t]
  704. [(Prim '- (list e)) (R0? e)]
  705. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  706. [(Program '() e) (R0? e)]
  707. [else #f]))
  708. \end{lstlisting}
  709. \end{minipage}
  710. \end{center}
  711. %
  712. Sometimes such a trick will save a few lines of code, especially when
  713. it comes to the \code{Program} wrapper. Yet this style is generally
  714. \emph{not} recommended because it can get you into trouble.
  715. %
  716. For example, the above function is subtly wrong:
  717. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  718. will return true, when it should return false.
  719. %% NOTE FIXME - must check for consistency on this issue throughout.
  720. \section{Interpreters}
  721. \label{sec:interp-R0}
  722. The meaning, or semantics, of a program is typically defined in the
  723. specification of the language. For example, the Scheme language is
  724. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  725. defined in its reference manual~\citep{plt-tr}. In this book we use an
  726. interpreter to define the meaning of each language that we consider,
  727. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  728. interpreter that is designated (by some people) as the definition of a
  729. language is called a \emph{definitional interpreter}. We warm up by
  730. creating a definitional interpreter for the $R_0$ language, which
  731. serves as a second example of structural recursion. The
  732. \texttt{interp-R0} function is defined in
  733. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  734. input program followed by a call to the \lstinline{interp-exp} helper
  735. function, which in turn has one match clause per grammar rule for
  736. $R_0$ expressions.
  737. \begin{figure}[tbp]
  738. \begin{lstlisting}
  739. (define (interp-exp e)
  740. (match e
  741. [(Int n) n]
  742. [(Prim 'read '())
  743. (define r (read))
  744. (cond [(fixnum? r) r]
  745. [else (error 'interp-R1 "expected an integer" r)])]
  746. [(Prim '- (list e))
  747. (define v (interp-exp e))
  748. (fx- 0 v)]
  749. [(Prim '+ (list e1 e2))
  750. (define v1 (interp-exp e1))
  751. (define v2 (interp-exp e2))
  752. (fx+ v1 v2)]
  753. )))
  754. (define (interp-R0 p)
  755. (match p
  756. [(Program '() e) (interp-exp e)]
  757. ))
  758. \end{lstlisting}
  759. \caption{Interpreter for the $R_0$ language.}
  760. \label{fig:interp-R0}
  761. \end{figure}
  762. Let us consider the result of interpreting a few $R_0$ programs. The
  763. following program adds two integers.
  764. \begin{lstlisting}
  765. (+ 10 32)
  766. \end{lstlisting}
  767. The result is \key{42}. We wrote the above program in concrete syntax,
  768. whereas the parsed abstract syntax is:
  769. \begin{lstlisting}
  770. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  771. \end{lstlisting}
  772. The next example demonstrates that expressions may be nested within
  773. each other, in this case nesting several additions and negations.
  774. \begin{lstlisting}
  775. (+ 10 (- (+ 12 20)))
  776. \end{lstlisting}
  777. What is the result of the above program?
  778. As mentioned previously, the $R_0$ language does not support
  779. arbitrarily-large integers, but only $63$-bit integers, so we
  780. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  781. in Racket.
  782. Suppose
  783. \[
  784. n = 999999999999999999
  785. \]
  786. which indeed fits in $63$-bits. What happens when we run the
  787. following program in our interpreter?
  788. \begin{lstlisting}
  789. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  790. \end{lstlisting}
  791. It produces an error:
  792. \begin{lstlisting}
  793. fx+: result is not a fixnum
  794. \end{lstlisting}
  795. We establish the convention that if running the definitional
  796. interpreter on a program produces an error, then the meaning of that
  797. program is \emph{unspecified}. That means a compiler for the language
  798. is under no obligations regarding that program; it may or may not
  799. produce an executable, and if it does, that executable can do
  800. anything. This convention applies to the languages defined in this
  801. book, as a way to simplify the student's task of implementing them,
  802. but this convention is not applicable to all programming languages.
  803. Moving on to the last feature of the $R_0$ language, the \key{read}
  804. operation prompts the user of the program for an integer. Recall that
  805. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  806. \code{8}. So if we run
  807. \begin{lstlisting}
  808. (interp-R0 ast1.1)
  809. \end{lstlisting}
  810. and if the input is \code{50}, then we get the answer to life, the
  811. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  812. Guide to the Galaxy} by Douglas Adams.}
  813. We include the \key{read} operation in $R_0$ so a clever student
  814. cannot implement a compiler for $R_0$ that simply runs the interpreter
  815. during compilation to obtain the output and then generates the trivial
  816. code to produce the output. (Yes, a clever student did this in the
  817. first instance of this course.)
  818. The job of a compiler is to translate a program in one language into a
  819. program in another language so that the output program behaves the
  820. same way as the input program does according to its definitional
  821. interpreter. This idea is depicted in the following diagram. Suppose
  822. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  823. interpreter for each language. Suppose that the compiler translates
  824. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  825. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  826. respective interpreters with input $i$ should yield the same output
  827. $o$.
  828. \begin{equation} \label{eq:compile-correct}
  829. \begin{tikzpicture}[baseline=(current bounding box.center)]
  830. \node (p1) at (0, 0) {$P_1$};
  831. \node (p2) at (3, 0) {$P_2$};
  832. \node (o) at (3, -2.5) {$o$};
  833. \path[->] (p1) edge [above] node {compile} (p2);
  834. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  835. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  836. \end{tikzpicture}
  837. \end{equation}
  838. In the next section we see our first example of a compiler.
  839. \section{Example Compiler: a Partial Evaluator}
  840. \label{sec:partial-evaluation}
  841. In this section we consider a compiler that translates $R_0$ programs
  842. into $R_0$ programs that may be more efficient, that is, this compiler
  843. is an optimizer. This optimizer eagerly computes the parts of the
  844. program that do not depend on any inputs, a process known as
  845. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  846. following program
  847. \begin{lstlisting}
  848. (+ (read) (- (+ 5 3)))
  849. \end{lstlisting}
  850. our compiler will translate it into the program
  851. \begin{lstlisting}
  852. (+ (read) -8)
  853. \end{lstlisting}
  854. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  855. evaluator for the $R_0$ language. The output of the partial evaluator
  856. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  857. recursion over $\Exp$ is captured in the \code{pe-exp} function
  858. whereas the code for partially evaluating the negation and addition
  859. operations is factored into two separate helper functions:
  860. \code{pe-neg} and \code{pe-add}. The input to these helper
  861. functions is the output of partially evaluating the children.
  862. \begin{figure}[tbp]
  863. \begin{lstlisting}
  864. (define (pe-neg r)
  865. (match r
  866. [(Int n) (Int (fx- 0 n))]
  867. [else (Prim '- (list r))]))
  868. (define (pe-add r1 r2)
  869. (match* (r1 r2)
  870. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  871. [(_ _) (Prim '+ (list r1 r2))]))
  872. (define (pe-exp e)
  873. (match e
  874. [(Int n) (Int n)]
  875. [(Prim 'read '()) (Prim 'read '())]
  876. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  877. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  878. ))
  879. (define (pe-R0 p)
  880. (match p
  881. [(Program info e) (Program info (pe-exp e))]
  882. ))
  883. \end{lstlisting}
  884. \caption{A partial evaluator for $R_0$ expressions.}
  885. \label{fig:pe-arith}
  886. \end{figure}
  887. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  888. arguments are integers and if they are, perform the appropriate
  889. arithmetic. Otherwise, they create an AST node for the operation
  890. (either negation or addition).
  891. To gain some confidence that the partial evaluator is correct, we can
  892. test whether it produces programs that get the same result as the
  893. input programs. That is, we can test whether it satisfies Diagram
  894. \eqref{eq:compile-correct}. The following code runs the partial
  895. evaluator on several examples and tests the output program. The
  896. \texttt{parse-program} and \texttt{assert} functions are defined in
  897. Appendix~\ref{appendix:utilities}.\\
  898. \begin{minipage}{1.0\textwidth}
  899. \begin{lstlisting}
  900. (define (test-pe p)
  901. (assert "testing pe-R0"
  902. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  903. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  904. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  905. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  906. \end{lstlisting}
  907. \end{minipage}
  908. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  909. \chapter{Integers and Variables}
  910. \label{ch:int-exp}
  911. This chapter is about compiling the subset of Racket that includes
  912. integer arithmetic and local variable binding, which we name $R_1$, to
  913. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  914. to x86-64 simply as x86. The chapter begins with a description of the
  915. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  916. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  917. discuss only what is needed for compiling $R_1$. We introduce more of
  918. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  919. reflect on their differences and come up with a plan to break down the
  920. translation from $R_1$ to x86 into a handful of steps
  921. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  922. chapter give detailed hints regarding each step
  923. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  924. to give enough hints that the well-prepared reader, together with a
  925. few friends, can implement a compiler from $R_1$ to x86 in a couple
  926. weeks while at the same time leaving room for some fun and creativity.
  927. To give the reader a feeling for the scale of this first compiler, the
  928. instructor solution for the $R_1$ compiler is less than 500 lines of
  929. code.
  930. \section{The $R_1$ Language}
  931. \label{sec:s0}
  932. The $R_1$ language extends the $R_0$ language with variable
  933. definitions. The concrete syntax of the $R_1$ language is defined by
  934. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  935. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  936. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  937. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  938. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  939. \key{Program} struct to mark the top of the program.
  940. %% The $\itm{info}$
  941. %% field of the \key{Program} structure contains an \emph{association
  942. %% list} (a list of key-value pairs) that is used to communicate
  943. %% auxiliary data from one compiler pass the next.
  944. Despite the simplicity of the $R_1$ language, it is rich enough to
  945. exhibit several compilation techniques.
  946. \begin{figure}[btp]
  947. \centering
  948. \fbox{
  949. \begin{minipage}{0.96\textwidth}
  950. \[
  951. \begin{array}{rcl}
  952. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)
  953. \mid (\key{-}\;\Exp\;\Exp) \\
  954. &\mid& \Var \mid \key{(let}~\key{([}\Var ~\Exp \key{])}~ \Exp \key{)} \\
  955. R_1 &::=& \Exp
  956. \end{array}
  957. \]
  958. \end{minipage}
  959. }
  960. \caption{The concrete syntax of $R_1$.}
  961. \label{fig:r1-concrete-syntax}
  962. \end{figure}
  963. \begin{figure}[btp]
  964. \centering
  965. \fbox{
  966. \begin{minipage}{0.96\textwidth}
  967. \[
  968. \begin{array}{rcl}
  969. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  970. &\mid& \ADD{\Exp}{\Exp}
  971. \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  972. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  973. \end{array}
  974. \]
  975. \end{minipage}
  976. }
  977. \caption{The abstract syntax of $R_1$.}
  978. \label{fig:r1-syntax}
  979. \end{figure}
  980. Let us dive further into the syntax and semantics of the $R_1$
  981. language. The \key{Let} feature defines a variable for use within its
  982. body and initializes the variable with the value of an expression.
  983. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  984. The concrete syntax for \key{Let} is
  985. \begin{lstlisting}
  986. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  987. \end{lstlisting}
  988. For example, the following program initializes \code{x} to $32$ and then
  989. evaluates the body \code{(+ 10 x)}, producing $42$.
  990. \begin{lstlisting}
  991. (let ([x (+ 12 20)]) (+ 10 x))
  992. \end{lstlisting}
  993. When there are multiple \key{let}'s for the same variable, the closest
  994. enclosing \key{let} is used. That is, variable definitions overshadow
  995. prior definitions. Consider the following program with two \key{let}'s
  996. that define variables named \code{x}. Can you figure out the result?
  997. \begin{lstlisting}
  998. (let ([x 32]) (+ (let ([x 10]) x) x))
  999. \end{lstlisting}
  1000. For the purposes of depicting which variable uses correspond to which
  1001. definitions, the following shows the \code{x}'s annotated with
  1002. subscripts to distinguish them. Double check that your answer for the
  1003. above is the same as your answer for this annotated version of the
  1004. program.
  1005. \begin{lstlisting}
  1006. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1007. \end{lstlisting}
  1008. The initializing expression is always evaluated before the body of the
  1009. \key{let}, so in the following, the \key{read} for \code{x} is
  1010. performed before the \key{read} for \code{y}. Given the input
  1011. $52$ then $10$, the following produces $42$ (not $-42$).
  1012. \begin{lstlisting}
  1013. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1014. \end{lstlisting}
  1015. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1016. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1017. \key{match} clauses for variables and for \key{let}. For \key{let},
  1018. we need a way to communicate the value of a variable to all the uses
  1019. of a variable. To accomplish this, we maintain a mapping from
  1020. variables to values, which is called an \emph{environment}. For
  1021. simplicity, here we use an association list to represent the
  1022. environment. The \code{interp-R1} function takes the current
  1023. environment, \code{env}, as an extra parameter. When the interpreter
  1024. encounters a variable, it finds the corresponding value using the
  1025. \code{dict-ref} function from the \code{racket/dict} package. When
  1026. the interpreter encounters a \key{Let}, it evaluates the initializing
  1027. expression, extends the environment with the result value bound to the
  1028. variable (using \code{dict-set}), then evaluates the body of the
  1029. \key{Let}.
  1030. \begin{figure}[tbp]
  1031. \begin{lstlisting}
  1032. (define (interp-exp env)
  1033. (lambda (e)
  1034. (match e
  1035. [(Int n) n]
  1036. [(Prim 'read '())
  1037. (define r (read))
  1038. (cond [(fixnum? r) r]
  1039. [else (error 'interp-R1 "expected an integer" r)])]
  1040. [(Prim '- (list e))
  1041. (define v ((interp-exp env) e))
  1042. (fx- 0 v)]
  1043. [(Prim '+ (list e1 e2))
  1044. (define v1 ((interp-exp env) e1))
  1045. (define v2 ((interp-exp env) e2))
  1046. (fx+ v1 v2)]
  1047. [(Var x) (dict-ref env x)]
  1048. [(Let x e body)
  1049. (define new-env (dict-set env x ((interp-exp env) e)))
  1050. ((interp-exp new-env) body)]
  1051. )))
  1052. (define (interp-R1 p)
  1053. (match p
  1054. [(Program info e) ((interp-exp '()) e)]
  1055. ))
  1056. \end{lstlisting}
  1057. \caption{Interpreter for the $R_1$ language.}
  1058. \label{fig:interp-R1}
  1059. \end{figure}
  1060. The goal for this chapter is to implement a compiler that translates
  1061. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1062. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1063. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1064. is, they both output the same integer $n$. We depict this correctness
  1065. criteria in the following diagram.
  1066. \[
  1067. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1068. \node (p1) at (0, 0) {$P_1$};
  1069. \node (p2) at (4, 0) {$P_2$};
  1070. \node (o) at (4, -2) {$n$};
  1071. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1072. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1073. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1074. \end{tikzpicture}
  1075. \]
  1076. In the next section we introduce enough of the x86 assembly
  1077. language to compile $R_1$.
  1078. \section{The x86 Assembly Language}
  1079. \label{sec:x86}
  1080. Figure~\ref{fig:x86-a} defines the concrete syntax for the subset of
  1081. the x86 assembly language needed for this chapter.
  1082. %
  1083. An x86 program is a sequence of instructions. The program is stored in
  1084. the computer's memory and the computer has a \emph{program counter}
  1085. that points to the address of the next instruction to be executed. For
  1086. most instructions, once the instruction is executed, the program
  1087. counter is incremented to point to the immediately following
  1088. instruction in memory. Most x86 instructions take two operands, where
  1089. each operand is either an integer constant (called \emph{immediate
  1090. value}), a \emph{register}, or a \emph{memory} location. A register
  1091. is a special kind of variable. Each one holds a 64-bit value; there
  1092. are 16 registers in the computer and their names are given in
  1093. Figure~\ref{fig:x86-a}. The computer's memory as a mapping of 64-bit
  1094. addresses to 64-bit values%
  1095. \footnote{This simple story suffices for describing how sequential
  1096. programs access memory but is not sufficient for multi-threaded
  1097. programs. However, multi-threaded execution is beyond the scope of
  1098. this book.}.
  1099. %
  1100. We use the AT\&T syntax expected by the GNU assembler, which comes
  1101. with the \key{gcc} compiler that we use for compiling assembly code to
  1102. machine code.
  1103. %
  1104. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1105. the x86 instructions used in this book.
  1106. % to do: finish treatment of imulq
  1107. % it's needed for vector's in R6/R7
  1108. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1109. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1110. && \key{r8} \mid \key{r9} \mid \key{r10}
  1111. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1112. \mid \key{r14} \mid \key{r15}}
  1113. \begin{figure}[tp]
  1114. \fbox{
  1115. \begin{minipage}{0.96\textwidth}
  1116. \[
  1117. \begin{array}{lcl}
  1118. \Reg &::=& \allregisters{} \\
  1119. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1120. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1121. \key{subq} \; \Arg\key{,} \Arg \mid
  1122. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1123. && \key{callq} \; \mathit{label} \mid
  1124. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1125. \Prog &::= & \key{.globl main}\\
  1126. & & \key{main:} \; \Instr^{+}
  1127. \end{array}
  1128. \]
  1129. \end{minipage}
  1130. }
  1131. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1132. \label{fig:x86-a}
  1133. \end{figure}
  1134. An immediate value is written using the notation \key{\$}$n$ where $n$
  1135. is an integer.
  1136. %
  1137. A register is written with a \key{\%} followed by the register name,
  1138. such as \key{\%rax}.
  1139. %
  1140. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1141. which obtains the address stored in register $r$ and then adds $n$
  1142. bytes to the address. The resulting address is used to either load or
  1143. store to memory depending on whether it occurs as a source or
  1144. destination argument of an instruction.
  1145. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1146. source $s$ and destination $d$, applies the arithmetic operation, then
  1147. writes the result back to the destination $d$.
  1148. %
  1149. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1150. stores the result in $d$.
  1151. %
  1152. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1153. specified by the label. We discuss procedure calls in more detail
  1154. later in this chapter and in Chapter~\ref{ch:functions}.
  1155. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1156. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1157. \key{main} procedure is externally visible, which is necessary so
  1158. that the operating system can call it. The label \key{main:}
  1159. indicates the beginning of the \key{main} procedure which is where
  1160. the operating system starts executing this program. The instruction
  1161. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1162. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1163. $10$ in \key{rax} and puts the result, $42$, back into
  1164. \key{rax}.
  1165. %
  1166. The last instruction, \key{retq}, finishes the \key{main} function by
  1167. returning the integer in \key{rax} to the operating system. The
  1168. operating system interprets this integer as the program's exit
  1169. code. By convention, an exit code of 0 indicates that a program
  1170. completed successfully, and all other exit codes indicate various
  1171. errors. Nevertheless, we return the result of the program as the exit
  1172. code.
  1173. %\begin{wrapfigure}{r}{2.25in}
  1174. \begin{figure}[tbp]
  1175. \begin{lstlisting}
  1176. .globl main
  1177. main:
  1178. movq $10, %rax
  1179. addq $32, %rax
  1180. retq
  1181. \end{lstlisting}
  1182. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1183. \label{fig:p0-x86}
  1184. %\end{wrapfigure}
  1185. \end{figure}
  1186. Unfortunately, x86 varies in a couple ways depending on what operating
  1187. system it is assembled in. The code examples shown here are correct on
  1188. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1189. labels like \key{main} must be prefixed with an underscore, as in
  1190. \key{\_main}.
  1191. We exhibit the use of memory for storing intermediate results in the
  1192. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1193. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1194. region of memory called the \emph{procedure call stack} (or
  1195. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1196. for each procedure call. The memory layout for an individual frame is
  1197. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1198. \emph{stack pointer} and points to the item at the top of the
  1199. stack. The stack grows downward in memory, so we increase the size of
  1200. the stack by subtracting from the stack pointer. Some operating
  1201. systems require the frame size to be a multiple of 16 bytes. In the
  1202. context of a procedure call, the \emph{return address} is the next
  1203. instruction after the call instruction on the caller side. During a
  1204. function call, the return address is pushed onto the stack. The
  1205. register \key{rbp} is the \emph{base pointer} which serves two
  1206. purposes: 1) it saves the location of the stack pointer for the
  1207. calling procedure and 2) it is used to access variables associated
  1208. with the current procedure. The base pointer of the calling procedure
  1209. is pushed onto the stack after the return address. We number the
  1210. variables from $1$ to $n$. Variable $1$ is stored at address
  1211. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1212. \begin{figure}[tbp]
  1213. \begin{lstlisting}
  1214. start:
  1215. movq $10, -8(%rbp)
  1216. negq -8(%rbp)
  1217. movq -8(%rbp), %rax
  1218. addq $52, %rax
  1219. jmp conclusion
  1220. .globl main
  1221. main:
  1222. pushq %rbp
  1223. movq %rsp, %rbp
  1224. subq $16, %rsp
  1225. jmp start
  1226. conclusion:
  1227. addq $16, %rsp
  1228. popq %rbp
  1229. retq
  1230. \end{lstlisting}
  1231. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1232. \label{fig:p1-x86}
  1233. \end{figure}
  1234. \begin{figure}[tbp]
  1235. \centering
  1236. \begin{tabular}{|r|l|} \hline
  1237. Position & Contents \\ \hline
  1238. 8(\key{\%rbp}) & return address \\
  1239. 0(\key{\%rbp}) & old \key{rbp} \\
  1240. -8(\key{\%rbp}) & variable $1$ \\
  1241. -16(\key{\%rbp}) & variable $2$ \\
  1242. \ldots & \ldots \\
  1243. 0(\key{\%rsp}) & variable $n$\\ \hline
  1244. \end{tabular}
  1245. \caption{Memory layout of a frame.}
  1246. \label{fig:frame}
  1247. \end{figure}
  1248. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1249. three instructions are the typical \emph{prelude} for a procedure.
  1250. The instruction \key{pushq \%rbp} saves the base pointer for the
  1251. caller onto the stack and subtracts $8$ from the stack pointer. The
  1252. second instruction \key{movq \%rsp, \%rbp} changes the base pointer to
  1253. the top of the stack. The instruction \key{subq \$16, \%rsp} moves the
  1254. stack pointer down to make enough room for storing variables. This
  1255. program needs one variable ($8$ bytes) but because the frame size is
  1256. required to be a multiple of 16 bytes, the space for variables is
  1257. rounded to 16 bytes.
  1258. The four instructions under the label \code{start} carry out the work
  1259. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1260. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1261. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1262. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1263. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1264. \key{rax}, at which point \key{rax} contains $42$.
  1265. The three instructions under the label \code{conclusion} are the
  1266. typical \emph{finale} of a procedure. The first two instructions are
  1267. necessary to get the state of the machine back to where it was at the
  1268. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1269. moves the stack pointer back to point at the old base pointer. The
  1270. amount added here needs to match the amount that was subtracted in the
  1271. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1272. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1273. instruction, \key{retq}, jumps back to the procedure that called this
  1274. one and adds 8 to the stack pointer, which returns the stack pointer
  1275. to where it was prior to the procedure call.
  1276. The compiler will need a convenient representation for manipulating
  1277. x86 programs, so we define an abstract syntax for x86 in
  1278. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1279. a subscript $0$ because later we introduce extended versions of this
  1280. assembly language. The main difference compared to the concrete syntax
  1281. of x86 (Figure~\ref{fig:x86-a}) is that it does not allow labeled
  1282. instructions to appear anywhere, but instead organizes instructions
  1283. into groups called \emph{blocks} and associates a label with every
  1284. block, which is why the \key{CFG} struct (for control-flow graph)
  1285. includes an association list mapping labels to blocks. The reason for
  1286. this organization becomes apparent in Chapter~\ref{ch:bool-types} when
  1287. we introduce conditional branching.
  1288. \begin{figure}[tp]
  1289. \fbox{
  1290. \begin{minipage}{0.96\textwidth}
  1291. \small
  1292. \[
  1293. \begin{array}{lcl}
  1294. \Reg &::=& \allregisters{} \\
  1295. \Arg &::=& \IMM{\Int} \mid \REG{\code{'}\Reg}
  1296. \mid \DEREF{\Reg}{\Int} \\
  1297. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1298. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1299. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1300. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1301. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1302. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \\
  1303. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1304. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1305. \end{array}
  1306. \]
  1307. \end{minipage}
  1308. }
  1309. \caption{Abstract syntax of $x86_0$ assembly.}
  1310. \label{fig:x86-ast-a}
  1311. \end{figure}
  1312. \section{Planning the trip to x86 via the $C_0$ language}
  1313. \label{sec:plan-s0-x86}
  1314. To compile one language to another it helps to focus on the
  1315. differences between the two languages because the compiler will need
  1316. to bridge those differences. What are the differences between $R_1$
  1317. and x86 assembly? Here are some of the most important ones:
  1318. \begin{enumerate}
  1319. \item[(a)] x86 arithmetic instructions typically have two arguments
  1320. and update the second argument in place. In contrast, $R_1$
  1321. arithmetic operations take two arguments and produce a new value.
  1322. An x86 instruction may have at most one memory-accessing argument.
  1323. Furthermore, some instructions place special restrictions on their
  1324. arguments.
  1325. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1326. whereas x86 instructions restrict their arguments to be integers
  1327. constants, registers, and memory locations.
  1328. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1329. sequence of instructions and jumps to labeled positions, whereas in
  1330. $R_1$ the order of evaluation is a left-to-right depth-first
  1331. traversal of the abstract syntax tree.
  1332. \item[(d)] An $R_1$ program can have any number of variables whereas
  1333. x86 has 16 registers and the procedure calls stack.
  1334. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1335. same name. The registers and memory locations of x86 all have unique
  1336. names or addresses.
  1337. \end{enumerate}
  1338. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1339. the problem into several steps, dealing with the above differences one
  1340. at a time. Each of these steps is called a \emph{pass} of the
  1341. compiler.
  1342. %
  1343. This terminology comes from each step traverses (i.e. passes over) the
  1344. AST of the program.
  1345. %
  1346. We begin by sketching how we might implement each pass, and give them
  1347. names. We then figure out an ordering of the passes and the
  1348. input/output language for each pass. The very first pass has $R_1$ as
  1349. its input language and the last pass has x86 as its output
  1350. language. In between we can choose whichever language is most
  1351. convenient for expressing the output of each pass, whether that be
  1352. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1353. Finally, to implement each pass we write one recursive function per
  1354. non-terminal in the grammar of the input language of the pass.
  1355. \begin{description}
  1356. \item[Pass \key{select-instructions}] To handle the difference between
  1357. $R_1$ operations and x86 instructions we convert each $R_1$
  1358. operation to a short sequence of instructions that accomplishes the
  1359. same task.
  1360. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1361. subexpression (i.e. operator and operand, and hence the name
  1362. \key{opera*}) is an \emph{atomic} expression (a variable or
  1363. integer), we introduce temporary variables to hold the results
  1364. of subexpressions.
  1365. \item[Pass \key{explicate-control}] To make the execution order of the
  1366. program explicit, we convert from the abstract syntax tree
  1367. representation into a \emph{control-flow graph} in which each node
  1368. contains a sequence of statements and the edges between nodes say
  1369. where to go at the end of the sequence.
  1370. \item[Pass \key{assign-homes}] To handle the difference between the
  1371. variables in $R_1$ versus the registers and stack locations in x86,
  1372. we assignment of each variable to a register or stack location.
  1373. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1374. by renaming every variable to a unique name, so that shadowing no
  1375. longer occurs.
  1376. \end{description}
  1377. The next question is: in what order should we apply these passes? This
  1378. question can be challenging because it is difficult to know ahead of
  1379. time which orders will be better (easier to implement, produce more
  1380. efficient code, etc.) so oftentimes trial-and-error is
  1381. involved. Nevertheless, we can try to plan ahead and make educated
  1382. choices regarding the ordering.
  1383. Let us consider the ordering of \key{uniquify} and
  1384. \key{remove-complex-opera*}. The assignment of subexpressions to
  1385. temporary variables involves introducing new variables and moving
  1386. subexpressions, which might change the shadowing of variables and
  1387. inadvertently change the behavior of the program. But if we apply
  1388. \key{uniquify} first, this will not be an issue. Of course, this means
  1389. that in \key{remove-complex-opera*}, we need to ensure that the
  1390. temporary variables that it creates are unique.
  1391. What should be the ordering of \key{explicate-control} with respect to
  1392. \key{uniquify}? The \key{uniquify} pass should come first because
  1393. \key{explicate-control} changes all the \key{let}-bound variables to
  1394. become local variables whose scope is the entire program, which would
  1395. confuse variables with the same name.
  1396. %
  1397. Likewise, we place \key{explicate-control} after
  1398. \key{remove-complex-opera*} because \key{explicate-control} removes
  1399. the \key{let} form, but it is convenient to use \key{let} in the
  1400. output of \key{remove-complex-opera*}.
  1401. %
  1402. Regarding \key{assign-homes}, it is helpful to place
  1403. \key{explicate-control} first because \key{explicate-control} changes
  1404. \key{let}-bound variables into program-scope variables. This means
  1405. that the \key{assign-homes} pass can read off the variables from the
  1406. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1407. entire program in search of \key{let}-bound variables.
  1408. Last, we need to decide on the ordering of \key{select-instructions}
  1409. and \key{assign-homes}. These two passes are intertwined, creating a
  1410. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1411. have already determined which instructions will be used, because x86
  1412. instructions have restrictions about which of their arguments can be
  1413. registers versus stack locations. One might want to give preferential
  1414. treatment to variables that occur in register-argument positions. On
  1415. the other hand, it may turn out to be impossible to make sure that all
  1416. such variables are assigned to registers, and then one must redo the
  1417. selection of instructions. Some compilers handle this problem by
  1418. iteratively repeating these two passes until a good solution is found.
  1419. We shall use a simpler approach in which \key{select-instructions}
  1420. comes first, followed by the \key{assign-homes}, then a third
  1421. pass named \key{patch-instructions} that uses a reserved register to
  1422. patch-up outstanding problems regarding instructions with too many
  1423. memory accesses. The disadvantage of this approach is some programs
  1424. may not execute as efficiently as they would if we used the iterative
  1425. approach and used all of the registers for variables.
  1426. \begin{figure}[tbp]
  1427. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1428. \node (R1) at (0,2) {\large $R_1$};
  1429. \node (R1-2) at (3,2) {\large $R_1$};
  1430. \node (R1-3) at (6,2) {\large $R_1$};
  1431. %\node (C0-1) at (6,0) {\large $C_0$};
  1432. \node (C0-2) at (3,0) {\large $C_0$};
  1433. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1434. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1435. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1436. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1437. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1438. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1439. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1440. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1441. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1442. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1443. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1444. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1445. \end{tikzpicture}
  1446. \caption{Overview of the passes for compiling $R_1$. }
  1447. \label{fig:R1-passes}
  1448. \end{figure}
  1449. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1450. passes in the form of a graph. Each pass is an edge and the
  1451. input/output language of each pass is a node in the graph. The output
  1452. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1453. are still in the $R_1$ language, but the output of the pass
  1454. \key{explicate-control} is in a different language $C_0$ that is
  1455. designed to make the order of evaluation explicit in its syntax, which
  1456. we introduce in the next section. The \key{select-instruction} pass
  1457. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1458. \key{patch-instructions} passes input and output variants of x86
  1459. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1460. \key{print-x86}, which converts from the abstract syntax of
  1461. $\text{x86}_0$ to the concrete syntax of x86.
  1462. In the next sections we discuss the $C_0$ language and the
  1463. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1464. remainder of this chapter gives hints regarding the implementation of
  1465. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1466. \subsection{The $C_0$ Intermediate Language}
  1467. The output of \key{explicate-control} is similar to the $C$
  1468. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1469. categories for expressions and statements, so we name it $C_0$. The
  1470. concrete syntax for $C_0$ is define din
  1471. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1472. is defined in Figure~\ref{fig:c0-syntax}.
  1473. %
  1474. The $C_0$ language supports the same operators as $R_1$ but the
  1475. arguments of operators are restricted to atomic expressions (variables
  1476. and integers), thanks to the \key{remove-complex-opera*} pass. In the
  1477. literature this style of intermediate language is called
  1478. administrative normal form, or ANF for
  1479. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{Let}
  1480. expressions, $C_0$ has assignment statements which can be executed in
  1481. sequence using the \key{Seq} form. A sequence of statements always
  1482. ends with \key{Return}, a guarantee that is baked into the grammar
  1483. rules for the \itm{tail} non-terminal. The naming of this non-terminal
  1484. comes from the term \emph{tail position}, which refers to an
  1485. expression that is the last one to execute within a function. (A
  1486. expression in tail position may contain subexpressions, and those may
  1487. or may not be in tail position depending on the kind of expression.)
  1488. A $C_0$ program consists of a control-flow graph (represented as an
  1489. association list mapping labels to tails). This is more general than
  1490. necessary for the present chapter, as we do not yet need to introduce
  1491. \key{goto} for jumping to labels, but it saves us from having to
  1492. change the syntax of the program construct in
  1493. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1494. \key{start}, and the whole program is its tail.
  1495. %
  1496. The $\itm{info}$ field of the \key{Program} form, after the
  1497. \key{explicate-control} pass, contains a mapping from the symbol
  1498. \key{locals} to a list of variables, that is, a list of all the
  1499. variables used in the program. At the start of the program, these
  1500. variables are uninitialized; they become initialized on their first
  1501. assignment.
  1502. \begin{figure}[tbp]
  1503. \fbox{
  1504. \begin{minipage}{0.96\textwidth}
  1505. \[
  1506. \begin{array}{lcl}
  1507. \Atm &::=& \Int \mid \Var \\
  1508. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1509. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1510. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1511. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1512. \end{array}
  1513. \]
  1514. \end{minipage}
  1515. }
  1516. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1517. \label{fig:c0-concrete-syntax}
  1518. \end{figure}
  1519. \begin{figure}[tbp]
  1520. \fbox{
  1521. \begin{minipage}{0.96\textwidth}
  1522. \[
  1523. \begin{array}{lcl}
  1524. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1525. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1526. &\mid& \ADD{\Atm}{\Atm}\\
  1527. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1528. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1529. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1530. \end{array}
  1531. \]
  1532. \end{minipage}
  1533. }
  1534. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1535. \label{fig:c0-syntax}
  1536. \end{figure}
  1537. %% The \key{select-instructions} pass is optimistic in the sense that it
  1538. %% treats variables as if they were all mapped to registers. The
  1539. %% \key{select-instructions} pass generates a program that consists of
  1540. %% x86 instructions but that still uses variables, so it is an
  1541. %% intermediate language that is technically different than x86, which
  1542. %% explains the asterisks in the diagram above.
  1543. %% In this Chapter we shall take the easy road to implementing
  1544. %% \key{assign-homes} and simply map all variables to stack locations.
  1545. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1546. %% smarter approach in which we make a best-effort to map variables to
  1547. %% registers, resorting to the stack only when necessary.
  1548. %% Once variables have been assigned to their homes, we can finalize the
  1549. %% instruction selection by dealing with an idiosyncrasy of x86
  1550. %% assembly. Many x86 instructions have two arguments but only one of the
  1551. %% arguments may be a memory reference (and the stack is a part of
  1552. %% memory). Because some variables may get mapped to stack locations,
  1553. %% some of our generated instructions may violate this restriction. The
  1554. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1555. %% replacing every violating instruction with a short sequence of
  1556. %% instructions that use the \key{rax} register. Once we have implemented
  1557. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1558. %% need to patch instructions will be relatively rare.
  1559. \subsection{The dialects of x86}
  1560. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1561. the pass \key{select-instructions}. It extends $x86_0$ with an
  1562. unbounded number of program-scope variables and has looser rules
  1563. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1564. output of \key{print-x86}, is the concrete syntax for x86.
  1565. \section{Uniquify Variables}
  1566. \label{sec:uniquify-s0}
  1567. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1568. programs in which every \key{let} uses a unique variable name. For
  1569. example, the \code{uniquify} pass should translate the program on the
  1570. left into the program on the right. \\
  1571. \begin{tabular}{lll}
  1572. \begin{minipage}{0.4\textwidth}
  1573. \begin{lstlisting}
  1574. (let ([x 32])
  1575. (+ (let ([x 10]) x) x))
  1576. \end{lstlisting}
  1577. \end{minipage}
  1578. &
  1579. $\Rightarrow$
  1580. &
  1581. \begin{minipage}{0.4\textwidth}
  1582. \begin{lstlisting}
  1583. (let ([x.1 32])
  1584. (+ (let ([x.2 10]) x.2) x.1))
  1585. \end{lstlisting}
  1586. \end{minipage}
  1587. \end{tabular} \\
  1588. %
  1589. The following is another example translation, this time of a program
  1590. with a \key{let} nested inside the initializing expression of another
  1591. \key{let}.\\
  1592. \begin{tabular}{lll}
  1593. \begin{minipage}{0.4\textwidth}
  1594. \begin{lstlisting}
  1595. (let ([x (let ([x 4])
  1596. (+ x 1))])
  1597. (+ x 2))
  1598. \end{lstlisting}
  1599. \end{minipage}
  1600. &
  1601. $\Rightarrow$
  1602. &
  1603. \begin{minipage}{0.4\textwidth}
  1604. \begin{lstlisting}
  1605. (let ([x.2 (let ([x.1 4])
  1606. (+ x.1 1))])
  1607. (+ x.2 2))
  1608. \end{lstlisting}
  1609. \end{minipage}
  1610. \end{tabular}
  1611. We recommend implementing \code{uniquify} by creating a function named
  1612. \code{uniquify-exp} that is structurally recursive function and mostly
  1613. just copies the input program. However, when encountering a \key{let},
  1614. it should generate a unique name for the variable (the Racket function
  1615. \code{gensym} is handy for this) and associate the old name with the
  1616. new unique name in an association list. The \code{uniquify-exp}
  1617. function will need to access this association list when it gets to a
  1618. variable reference, so we add another parameter to \code{uniquify-exp}
  1619. for the association list. It is quite common for a compiler pass to
  1620. need a map to store extra information about variables. Such maps are
  1621. traditionally called \emph{symbol tables}.
  1622. The skeleton of the \code{uniquify-exp} function is shown in
  1623. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1624. convenient to partially apply it to a symbol table and then apply it
  1625. to different expressions, as in the last clause for primitive
  1626. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1627. is useful for applying a function to each element of a list to produce
  1628. a new list.
  1629. \begin{exercise}
  1630. \normalfont % I don't like the italics for exercises. -Jeremy
  1631. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1632. implement the clauses for variables and for the \key{let} form.
  1633. \end{exercise}
  1634. \begin{figure}[tbp]
  1635. \begin{lstlisting}
  1636. (define (uniquify-exp symtab)
  1637. (lambda (e)
  1638. (match e
  1639. [(Var x) ___]
  1640. [(Int n) (Int n)]
  1641. [(Let x e body) ___]
  1642. [(Prim op es)
  1643. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1644. )))
  1645. (define (uniquify p)
  1646. (match p
  1647. [(Program info e)
  1648. (Program info ((uniquify-exp '()) e))]
  1649. )))
  1650. \end{lstlisting}
  1651. \caption{Skeleton for the \key{uniquify} pass.}
  1652. \label{fig:uniquify-s0}
  1653. \end{figure}
  1654. \begin{exercise}
  1655. \normalfont % I don't like the italics for exercises. -Jeremy
  1656. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1657. and checking whether the output programs produce the same result as
  1658. the input programs. The $R_1$ programs should be designed to test the
  1659. most interesting parts of the \key{uniquify} pass, that is, the
  1660. programs should include \key{let} forms, variables, and variables
  1661. that overshadow each other. The five programs should be in a
  1662. subdirectory named \key{tests} and they should have the same file name
  1663. except for a different integer at the end of the name, followed by the
  1664. ending \key{.rkt}. Use the \key{interp-tests} function
  1665. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1666. your \key{uniquify} pass on the example programs. See the
  1667. \key{run-tests.rkt} script in the student support code for an example
  1668. of how to use \key{interp-tests}.
  1669. \end{exercise}
  1670. \section{Remove Complex Operands}
  1671. \label{sec:remove-complex-opera-r1}
  1672. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1673. $R_1$ programs in which the arguments of operations are atomic
  1674. expressions. Put another way, this pass removes complex operands,
  1675. such as the expression \code{(- 10)} in the program below. This is
  1676. accomplished by introducing a new \key{let}-bound variable, binding
  1677. the complex operand to the new variable, and then using the new
  1678. variable in place of the complex operand, as shown in the output of
  1679. \code{remove-complex-opera*} on the right.\\
  1680. \begin{tabular}{lll}
  1681. \begin{minipage}{0.4\textwidth}
  1682. % s0_19.rkt
  1683. \begin{lstlisting}
  1684. (+ 52 (- 10))
  1685. \end{lstlisting}
  1686. \end{minipage}
  1687. &
  1688. $\Rightarrow$
  1689. &
  1690. \begin{minipage}{0.4\textwidth}
  1691. \begin{lstlisting}
  1692. (let ([tmp.1 (- 10)])
  1693. (+ 52 tmp.1))
  1694. \end{lstlisting}
  1695. \end{minipage}
  1696. \end{tabular}
  1697. We recommend implementing this pass with two mutually recursive
  1698. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1699. \code{rco-atom} to subexpressions that need to become atomic and to
  1700. apply \code{rco-exp} to subexpressions that can be atomic or complex.
  1701. Both functions take an $R_1$ expression as input. The \code{rco-exp}
  1702. function returns an expression. The \code{rco-atom} function returns
  1703. two things: an atomic expression and association list mapping
  1704. temporary variables to complex subexpressions. You can return multiple
  1705. things from a function using Racket's \key{values} form and you can
  1706. receive multiple things from a function call using the
  1707. \key{define-values} form. If you are not familiar with these features,
  1708. review the Racket documentation. Also, the \key{for/lists} form is
  1709. useful for applying a function to each element of a list, in the case
  1710. where the function returns multiple values.
  1711. The following shows the output of \code{rco-atom} on the expression
  1712. \code{(- 10)} (using concrete syntax to be concise).
  1713. \begin{tabular}{lll}
  1714. \begin{minipage}{0.4\textwidth}
  1715. \begin{lstlisting}
  1716. (- 10)
  1717. \end{lstlisting}
  1718. \end{minipage}
  1719. &
  1720. $\Rightarrow$
  1721. &
  1722. \begin{minipage}{0.4\textwidth}
  1723. \begin{lstlisting}
  1724. tmp.1
  1725. ((tmp.1 . (- 10)))
  1726. \end{lstlisting}
  1727. \end{minipage}
  1728. \end{tabular}
  1729. Take special care of programs such as the next one that \key{let}-bind
  1730. variables with integers or other variables. You should leave them
  1731. unchanged, as shown in to the program on the right \\
  1732. \begin{tabular}{lll}
  1733. \begin{minipage}{0.4\textwidth}
  1734. % s0_20.rkt
  1735. \begin{lstlisting}
  1736. (let ([a 42])
  1737. (let ([b a])
  1738. b))
  1739. \end{lstlisting}
  1740. \end{minipage}
  1741. &
  1742. $\Rightarrow$
  1743. &
  1744. \begin{minipage}{0.4\textwidth}
  1745. \begin{lstlisting}
  1746. (let ([a 42])
  1747. (let ([b a])
  1748. b))
  1749. \end{lstlisting}
  1750. \end{minipage}
  1751. \end{tabular} \\
  1752. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1753. produce the following output.\\
  1754. \begin{minipage}{0.4\textwidth}
  1755. \begin{lstlisting}
  1756. (let ([tmp.1 42])
  1757. (let ([a tmp.1])
  1758. (let ([tmp.2 a])
  1759. (let ([b tmp.2])
  1760. b))))
  1761. \end{lstlisting}
  1762. \end{minipage}
  1763. \begin{exercise}
  1764. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1765. it on all of the example programs that you created to test the
  1766. \key{uniquify} pass and create three new example programs that are
  1767. designed to exercise the interesting code in the
  1768. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1769. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1770. your passes on the example programs.
  1771. \end{exercise}
  1772. \section{Explicate Control}
  1773. \label{sec:explicate-control-r1}
  1774. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1775. programs that make the order of execution explicit in their
  1776. syntax. For now this amounts to flattening \key{let} constructs into a
  1777. sequence of assignment statements. For example, consider the following
  1778. $R_1$ program.\\
  1779. % s0_11.rkt
  1780. \begin{minipage}{0.96\textwidth}
  1781. \begin{lstlisting}
  1782. (let ([y (let ([x 20])
  1783. (+ x (let ([x 22]) x)))])
  1784. y)
  1785. \end{lstlisting}
  1786. \end{minipage}\\
  1787. %
  1788. The output of the previous pass and of \code{explicate-control} is
  1789. shown below. Recall that the right-hand-side of a \key{let} executes
  1790. before its body, so the order of evaluation for this program is to
  1791. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1792. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1793. output of \code{explicate-control} makes this ordering explicit.\\
  1794. \begin{tabular}{lll}
  1795. \begin{minipage}{0.4\textwidth}
  1796. \begin{lstlisting}
  1797. (let ([y (let ([x.1 20])
  1798. (let ([x.2 22])
  1799. (+ x.1 x.2)))])
  1800. y)
  1801. \end{lstlisting}
  1802. \end{minipage}
  1803. &
  1804. $\Rightarrow$
  1805. &
  1806. \begin{minipage}{0.4\textwidth}
  1807. \begin{lstlisting}
  1808. locals: y x.1 x.2
  1809. start:
  1810. x.1 = 20;
  1811. x.2 = 22;
  1812. y = (+ x.1 x.2);
  1813. return y;
  1814. \end{lstlisting}
  1815. \end{minipage}
  1816. \end{tabular}
  1817. We recommend implementing \code{explicate-control} using two mutually
  1818. recursive functions: \code{explicate-tail} and
  1819. \code{explicate-assign}. The first function should be applied to
  1820. expressions in tail position whereas the second should be applied to
  1821. expressions that occur on the right-hand-side of a \key{let}. The
  1822. \code{explicate-tail} function takes an $R_1$ expression as input and
  1823. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1824. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1825. function takes an $R_1$ expression, the variable that it is to be
  1826. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1827. assignment (e.g., the code generated for the body of the \key{let}).
  1828. It returns a $\Tail$ and a list of variables. The top-level
  1829. \code{explicate-control} function should invoke \code{explicate-tail}
  1830. on the body of the \key{program} and then associate the \code{locals}
  1831. symbol with the resulting list of variables in the $\itm{info}$ field,
  1832. as in the above example.
  1833. %% \section{Uncover Locals}
  1834. %% \label{sec:uncover-locals-r1}
  1835. %% The pass \code{uncover-locals} simply collects all of the variables in
  1836. %% the program and places then in the $\itm{info}$ of the program
  1837. %% construct. Here is the output for the example program of the last
  1838. %% section.
  1839. %% \begin{minipage}{0.4\textwidth}
  1840. %% \begin{lstlisting}
  1841. %% (program ((locals . (x.1 x.2 y)))
  1842. %% ((start .
  1843. %% (seq (assign x.1 20)
  1844. %% (seq (assign x.2 22)
  1845. %% (seq (assign y (+ x.1 x.2))
  1846. %% (return y)))))))
  1847. %% \end{lstlisting}
  1848. %% \end{minipage}
  1849. \section{Select Instructions}
  1850. \label{sec:select-r1}
  1851. In the \code{select-instructions} pass we begin the work of
  1852. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1853. this pass is a variable of x86 that still uses variables, so we add an
  1854. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1855. syntax of Figure~\ref{fig:x86-ast-a}. We recommend implementing the
  1856. \code{select-instructions} in terms of three auxiliary functions, one
  1857. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1858. The cases for $\Atm$ are straightforward, variables stay
  1859. the same and integer constants are changed to immediates:
  1860. $\INT{n}$ changes to $\IMM{n}$.
  1861. Next we consider the cases for $\Stmt$, starting with arithmetic
  1862. operations. For example, in $C_0$ an addition operation can take the
  1863. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1864. need to use the \key{addq} instruction which does an in-place
  1865. update. So we must first move \code{10} to \code{x}. \\
  1866. \begin{tabular}{lll}
  1867. \begin{minipage}{0.4\textwidth}
  1868. \begin{lstlisting}
  1869. x = (+ 10 32);
  1870. \end{lstlisting}
  1871. \end{minipage}
  1872. &
  1873. $\Rightarrow$
  1874. &
  1875. \begin{minipage}{0.4\textwidth}
  1876. \begin{lstlisting}
  1877. movq $10, x
  1878. addq $32, x
  1879. \end{lstlisting}
  1880. \end{minipage}
  1881. \end{tabular} \\
  1882. %
  1883. There are cases that require special care to avoid generating
  1884. needlessly complicated code. If one of the arguments of the addition
  1885. is the same as the left-hand side of the assignment, then there is no
  1886. need for the extra move instruction. For example, the following
  1887. assignment statement can be translated into a single \key{addq}
  1888. instruction.\\
  1889. \begin{tabular}{lll}
  1890. \begin{minipage}{0.4\textwidth}
  1891. \begin{lstlisting}
  1892. x = (+ 10 x);
  1893. \end{lstlisting}
  1894. \end{minipage}
  1895. &
  1896. $\Rightarrow$
  1897. &
  1898. \begin{minipage}{0.4\textwidth}
  1899. \begin{lstlisting}
  1900. addq $10, x
  1901. \end{lstlisting}
  1902. \end{minipage}
  1903. \end{tabular} \\
  1904. The \key{read} operation does not have a direct counterpart in x86
  1905. assembly, so we have instead implemented this functionality in the C
  1906. language, with the function \code{read\_int} in the file
  1907. \code{runtime.c}. In general, we refer to all of the functionality in
  1908. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1909. for short. When compiling your generated x86 assembly code, you need
  1910. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1911. using \code{gcc} option \code{-c}) and link it into the
  1912. executable. For our purposes of code generation, all you need to do is
  1913. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1914. (for left-hand side) into a call to the \code{read\_int} function
  1915. followed by a move from \code{rax} to the left-hand side. The move
  1916. from \code{rax} is needed because the return value from
  1917. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1918. \begin{tabular}{lll}
  1919. \begin{minipage}{0.4\textwidth}
  1920. \begin{lstlisting}
  1921. |$\itm{lhs}$| = (read);
  1922. \end{lstlisting}
  1923. \end{minipage}
  1924. &
  1925. $\Rightarrow$
  1926. &
  1927. \begin{minipage}{0.4\textwidth}
  1928. \begin{lstlisting}
  1929. callq read_int
  1930. movq %rax, |$\itm{lhs}$|
  1931. \end{lstlisting}
  1932. \end{minipage}
  1933. \end{tabular} \\
  1934. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1935. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1936. assignment to the \key{rax} register followed by a jump to the
  1937. conclusion of the program (so the conclusion needs to be labeled).
  1938. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1939. recursively and append the resulting instructions.
  1940. \begin{exercise}
  1941. \normalfont
  1942. Implement the \key{select-instructions} pass and test it on all of the
  1943. example programs that you created for the previous passes and create
  1944. three new example programs that are designed to exercise all of the
  1945. interesting code in this pass. Use the \key{interp-tests} function
  1946. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1947. your passes on the example programs.
  1948. \end{exercise}
  1949. \section{Assign Homes}
  1950. \label{sec:assign-r1}
  1951. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  1952. $\text{x86}^{*}_0$ programs that no longer use program variables.
  1953. Thus, the \key{assign-homes} pass is responsible for placing all of
  1954. the program variables in registers or on the stack. For runtime
  1955. efficiency, it is better to place variables in registers, but as there
  1956. are only 16 registers, some programs must necessarily resort to
  1957. placing some variables on the stack. In this chapter we focus on the
  1958. mechanics of placing variables on the stack. We study an algorithm for
  1959. placing variables in registers in
  1960. Chapter~\ref{ch:register-allocation-r1}.
  1961. Consider again the following $R_1$ program.
  1962. % s0_20.rkt
  1963. \begin{lstlisting}
  1964. (let ([a 42])
  1965. (let ([b a])
  1966. b))
  1967. \end{lstlisting}
  1968. For reference, we repeat the output of \code{select-instructions} on
  1969. the left and show the output of \code{assign-homes} on the right.
  1970. Recall that \key{explicate-control} associated the list of
  1971. variables with the \code{locals} symbol in the program's $\itm{info}$
  1972. field, so \code{assign-homes} has convenient access to the them. In
  1973. this example, we assign variable \code{a} to stack location
  1974. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  1975. \begin{tabular}{l}
  1976. \begin{minipage}{0.4\textwidth}
  1977. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1978. locals: a b
  1979. start:
  1980. movq $42, a
  1981. movq a, b
  1982. movq b, %rax
  1983. jmp conclusion
  1984. \end{lstlisting}
  1985. \end{minipage}
  1986. {$\Rightarrow$}
  1987. \begin{minipage}{0.4\textwidth}
  1988. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1989. stack-space: 16
  1990. start:
  1991. movq $42, -8(%rbp)
  1992. movq -8(%rbp), -16(%rbp)
  1993. movq -16(%rbp), %rax
  1994. jmp conclusion
  1995. \end{lstlisting}
  1996. \end{minipage}
  1997. \end{tabular} \\
  1998. In the process of assigning variables to stack locations, it is
  1999. convenient to compute and store the size of the frame (in bytes) in
  2000. the $\itm{info}$ field of the \key{Program} node, with the key
  2001. \code{stack-space}, which will be needed later to generate the
  2002. procedure conclusion. Some operating systems place restrictions on
  2003. the frame size. For example, Mac OS X requires the frame size to be a
  2004. multiple of 16 bytes.
  2005. \begin{exercise}
  2006. \normalfont Implement the \key{assign-homes} pass and test it on all
  2007. of the example programs that you created for the previous passes pass.
  2008. We recommend that \key{assign-homes} take an extra parameter that is a
  2009. mapping of variable names to homes (stack locations for now). Use the
  2010. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2011. \key{utilities.rkt} to test your passes on the example programs.
  2012. \end{exercise}
  2013. \section{Patch Instructions}
  2014. \label{sec:patch-s0}
  2015. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2016. programs to $\text{x86}_0$ programs by making sure that each
  2017. instruction adheres to the restrictions of the x86 assembly language.
  2018. In particular, at most one argument of an instruction may be a memory
  2019. reference.
  2020. We return to the following running example.
  2021. % s0_20.rkt
  2022. \begin{lstlisting}
  2023. (let ([a 42])
  2024. (let ([b a])
  2025. b))
  2026. \end{lstlisting}
  2027. After the \key{assign-homes} pass, the above program has been translated to
  2028. the following. \\
  2029. \begin{minipage}{0.5\textwidth}
  2030. \begin{lstlisting}
  2031. stack-space: 16
  2032. start:
  2033. movq $42, -8(%rbp)
  2034. movq -8(%rbp), -16(%rbp)
  2035. movq -16(%rbp), %rax
  2036. jmp conclusion
  2037. \end{lstlisting}
  2038. \end{minipage}\\
  2039. The second \key{movq} instruction is problematic because both
  2040. arguments are stack locations. We suggest fixing this problem by
  2041. moving from the source location to the register \key{rax} and then
  2042. from \key{rax} to the destination location, as follows.
  2043. \begin{lstlisting}
  2044. movq -8(%rbp), %rax
  2045. movq %rax, -16(%rbp)
  2046. \end{lstlisting}
  2047. \begin{exercise}
  2048. \normalfont
  2049. Implement the \key{patch-instructions} pass and test it on all of the
  2050. example programs that you created for the previous passes and create
  2051. three new example programs that are designed to exercise all of the
  2052. interesting code in this pass. Use the \key{interp-tests} function
  2053. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2054. your passes on the example programs.
  2055. \end{exercise}
  2056. \section{Print x86}
  2057. \label{sec:print-x86}
  2058. The last step of the compiler from $R_1$ to x86 is to convert the
  2059. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-ast-a}) to the
  2060. string representation (defined in Figure~\ref{fig:x86-a}). The Racket
  2061. \key{format} and \key{string-append} functions are useful in this
  2062. regard. The main work that this step needs to perform is to create the
  2063. \key{main} function and the standard instructions for its prelude and
  2064. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2065. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2066. variables, so we suggest computing it in the \key{assign-homes} pass
  2067. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2068. of the \key{program} node.
  2069. %% Your compiled code should print the result of the program's execution
  2070. %% by using the \code{print\_int} function provided in
  2071. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2072. %% far, this final result should be stored in the \key{rax} register.
  2073. %% We'll talk more about how to perform function calls with arguments in
  2074. %% general later on, but for now, place the following after the compiled
  2075. %% code for the $R_1$ program but before the conclusion:
  2076. %% \begin{lstlisting}
  2077. %% movq %rax, %rdi
  2078. %% callq print_int
  2079. %% \end{lstlisting}
  2080. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2081. %% stores the first argument to be passed into \key{print\_int}.
  2082. If you want your program to run on Mac OS X, your code needs to
  2083. determine whether or not it is running on a Mac, and prefix
  2084. underscores to labels like \key{main}. You can determine the platform
  2085. with the Racket call \code{(system-type 'os)}, which returns
  2086. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2087. %% In addition to
  2088. %% placing underscores on \key{main}, you need to put them in front of
  2089. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2090. %% \_print\_int}).
  2091. \begin{exercise}
  2092. \normalfont Implement the \key{print-x86} pass and test it on all of
  2093. the example programs that you created for the previous passes. Use the
  2094. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2095. \key{utilities.rkt} to test your complete compiler on the example
  2096. programs. See the \key{run-tests.rkt} script in the student support
  2097. code for an example of how to use \key{compiler-tests}. Also, remember
  2098. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2099. \key{gcc}.
  2100. \end{exercise}
  2101. \section{Challenge: Partial Evaluator for $R_1$}
  2102. \label{sec:pe-R1}
  2103. This section describes optional challenge exercises that involve
  2104. adapting and improving the partial evaluator for $R_0$ that was
  2105. introduced in Section~\ref{sec:partial-evaluation}.
  2106. \begin{exercise}\label{ex:pe-R1}
  2107. \normalfont
  2108. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2109. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2110. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2111. and variables to the $R_0$ language, so you will need to add cases for
  2112. them in the \code{pe-exp} function. Also, note that the \key{program}
  2113. form changes slightly to include an $\itm{info}$ field. Once
  2114. complete, add the partial evaluation pass to the front of your
  2115. compiler and make sure that your compiler still passes all of the
  2116. tests.
  2117. \end{exercise}
  2118. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2119. \begin{exercise}
  2120. \normalfont
  2121. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2122. \code{pe-add} auxiliary functions with functions that know more about
  2123. arithmetic. For example, your partial evaluator should translate
  2124. \begin{lstlisting}
  2125. (+ 1 (+ (read) 1))
  2126. \end{lstlisting}
  2127. into
  2128. \begin{lstlisting}
  2129. (+ 2 (read))
  2130. \end{lstlisting}
  2131. To accomplish this, the \code{pe-exp} function should produce output
  2132. in the form of the $\itm{residual}$ non-terminal of the following
  2133. grammar.
  2134. \[
  2135. \begin{array}{lcl}
  2136. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2137. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2138. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2139. \end{array}
  2140. \]
  2141. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2142. that their inputs are $\itm{residual}$ expressions and they should
  2143. return $\itm{residual}$ expressions. Once the improvements are
  2144. complete, make sure that your compiler still passes all of the tests.
  2145. After all, fast code is useless if it produces incorrect results!
  2146. \end{exercise}
  2147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2148. \chapter{Register Allocation}
  2149. \label{ch:register-allocation-r1}
  2150. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2151. make our life easier. However, we can improve the performance of the
  2152. generated code if we instead place some variables into registers. The
  2153. CPU can access a register in a single cycle, whereas accessing the
  2154. stack takes many cycles if the relevant data is in cache or many more
  2155. to access main memory if the data is not in cache.
  2156. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2157. serves as a running example. We show the source program and also the
  2158. output of instruction selection. At that point the program is almost
  2159. x86 assembly but not quite; it still contains variables instead of
  2160. stack locations or registers.
  2161. \begin{figure}
  2162. \begin{minipage}{0.45\textwidth}
  2163. Example $R_1$ program:
  2164. % s0_22.rkt
  2165. \begin{lstlisting}
  2166. (let ([v 1])
  2167. (let ([w 46])
  2168. (let ([x (+ v 7)])
  2169. (let ([y (+ 4 x)])
  2170. (let ([z (+ x w)])
  2171. (+ z (- y)))))))
  2172. \end{lstlisting}
  2173. \end{minipage}
  2174. \begin{minipage}{0.45\textwidth}
  2175. After instruction selection:
  2176. \begin{lstlisting}
  2177. locals: v w x y z t.1
  2178. start:
  2179. movq $1, v
  2180. movq $46, w
  2181. movq v, x
  2182. addq $7, x
  2183. movq x, y
  2184. addq $4, y
  2185. movq x, z
  2186. addq w, z
  2187. movq y, t.1
  2188. negq t.1
  2189. movq z, %rax
  2190. addq t.1, %rax
  2191. jmp conclusion
  2192. \end{lstlisting}
  2193. \end{minipage}
  2194. \caption{An example program for register allocation.}
  2195. \label{fig:reg-eg}
  2196. \end{figure}
  2197. The goal of register allocation is to fit as many variables into
  2198. registers as possible. A program sometimes has more variables than
  2199. registers, so we cannot map each variable to a different
  2200. register. Fortunately, it is common for different variables to be
  2201. needed during different periods of time during program execution, and
  2202. in such cases several variables can be mapped to the same register.
  2203. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2204. After the variable \code{x} is moved to \code{z} it is no longer
  2205. needed. Variable \code{y}, on the other hand, is used only after this
  2206. point, so \code{x} and \code{y} could share the same register. The
  2207. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2208. where a variable is needed. Once we have that information, we compute
  2209. which variables are needed at the same time, i.e., which ones
  2210. \emph{interfere}, and represent this relation as an undirected graph
  2211. whose vertices are variables and edges indicate when two variables
  2212. interfere with each other (Section~\ref{sec:build-interference}). We
  2213. then model register allocation as a graph coloring problem, which we
  2214. discuss in Section~\ref{sec:graph-coloring}.
  2215. In the event that we run out of registers despite these efforts, we
  2216. place the remaining variables on the stack, similar to what we did in
  2217. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2218. for assigning a variable to a stack location. The process of spilling
  2219. variables is handled as part of the graph coloring process described
  2220. in \ref{sec:graph-coloring}.
  2221. \section{Registers and Calling Conventions}
  2222. \label{sec:calling-conventions}
  2223. As we perform register allocation, we need to be aware of the
  2224. conventions that govern the way in which registers interact with
  2225. function calls, such as calls to the \code{read\_int} function. The
  2226. convention for x86 is that the caller is responsible for freeing up
  2227. some registers, the \emph{caller-saved registers}, prior to the
  2228. function call, and the callee is responsible for saving and restoring
  2229. some other registers, the \emph{callee-saved registers}, before and
  2230. after using them. The caller-saved registers are
  2231. \begin{lstlisting}
  2232. rax rdx rcx rsi rdi r8 r9 r10 r11
  2233. \end{lstlisting}
  2234. while the callee-saved registers are
  2235. \begin{lstlisting}
  2236. rsp rbp rbx r12 r13 r14 r15
  2237. \end{lstlisting}
  2238. Another way to think about this caller/callee convention is the
  2239. following. The caller should assume that all the caller-saved registers
  2240. get overwritten with arbitrary values by the callee. On the other
  2241. hand, the caller can safely assume that all the callee-saved registers
  2242. contain the same values after the call that they did before the call.
  2243. The callee can freely use any of the caller-saved registers. However,
  2244. if the callee wants to use a callee-saved register, the callee must
  2245. arrange to put the original value back in the register prior to
  2246. returning to the caller, which is usually accomplished by saving and
  2247. restoring the value from the stack.
  2248. \section{Liveness Analysis}
  2249. \label{sec:liveness-analysis-r1}
  2250. A variable is \emph{live} if the variable is used at some later point
  2251. in the program and there is not an intervening assignment to the
  2252. variable.
  2253. %
  2254. To understand the latter condition, consider the following code
  2255. fragment in which there are two writes to \code{b}. Are \code{a} and
  2256. \code{b} both live at the same time?
  2257. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2258. movq $5, a
  2259. movq $30, b
  2260. movq a, c
  2261. movq $10, b
  2262. addq b, c
  2263. \end{lstlisting}
  2264. The answer is no because the integer \code{30} written to \code{b} on
  2265. line 2 is never used. The variable \code{b} is read on line 5 and
  2266. there is an intervening write to \code{b} on line 4, so the read on
  2267. line 5 receives the value written on line 4, not line 2.
  2268. The live variables can be computed by traversing the instruction
  2269. sequence back to front (i.e., backwards in execution order). Let
  2270. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2271. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2272. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2273. variables before instruction $I_k$. The live variables after an
  2274. instruction are always the same as the live variables before the next
  2275. instruction.
  2276. \begin{equation} \label{eq:live-after-before-next}
  2277. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2278. \end{equation}
  2279. To start things off, there are no live variables after the last
  2280. instruction, so
  2281. \begin{equation}\label{eq:live-last-empty}
  2282. L_{\mathsf{after}}(n) = \emptyset
  2283. \end{equation}
  2284. We then apply the following rule repeatedly, traversing the
  2285. instruction sequence back to front.
  2286. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2287. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2288. \end{equation}
  2289. where $W(k)$ are the variables written to by instruction $I_k$ and
  2290. $R(k)$ are the variables read by instruction $I_k$.
  2291. Let us walk through the above example, applying these formulas
  2292. starting with the instruction on line 5. We collect the answers in the
  2293. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2294. instruction is $\emptyset$ because it is the last instruction
  2295. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2296. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2297. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2298. is
  2299. \[
  2300. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2301. \]
  2302. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2303. the live-before set from line 5 to be the live-after set for this
  2304. instruction (formula~\ref{eq:live-after-before-next}).
  2305. \[
  2306. L_{\mathsf{after}}(4) = \{ b, c \}
  2307. \]
  2308. This move instruction writes to $b$ and does not read from any
  2309. variables, so we have the following live-before set
  2310. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2311. \[
  2312. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2313. \]
  2314. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2315. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2316. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2317. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2318. variable that is not live and does not read from a variable.
  2319. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2320. because it writes to variable $a$.
  2321. \begin{center}
  2322. \begin{minipage}{0.45\textwidth}
  2323. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2324. movq $5, a
  2325. movq $30, b
  2326. movq a, c
  2327. movq $10, b
  2328. addq b, c
  2329. \end{lstlisting}
  2330. \end{minipage}
  2331. \vrule\hspace{10pt}
  2332. \begin{minipage}{0.45\textwidth}
  2333. \begin{align*}
  2334. L_{\mathsf{before}}(1)= \emptyset,
  2335. L_{\mathsf{after}}(1)= \{a\}\\
  2336. L_{\mathsf{before}}(2)= \{a\},
  2337. L_{\mathsf{after}}(2)= \{a\}\\
  2338. L_{\mathsf{before}}(3)= \{a\},
  2339. L_{\mathsf{after}}(2)= \{c\}\\
  2340. L_{\mathsf{before}}(4)= \{c\},
  2341. L_{\mathsf{after}}(4)= \{b,c\}\\
  2342. L_{\mathsf{before}}(5)= \{b,c\},
  2343. L_{\mathsf{after}}(5)= \emptyset
  2344. \end{align*}
  2345. \end{minipage}
  2346. \end{center}
  2347. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2348. for the running example program, with each instruction aligned with
  2349. its $L_{\mathtt{after}}$ set to make the figure easy to read.
  2350. \begin{figure}[tbp]
  2351. \hspace{20pt}
  2352. \begin{minipage}{0.45\textwidth}
  2353. \begin{lstlisting}[numbers=left]
  2354. movq $1, v
  2355. movq $46, w
  2356. movq v, x
  2357. addq $7, x
  2358. movq x, y
  2359. addq $4, y
  2360. movq x, z
  2361. addq w, z
  2362. movq y, t.1
  2363. negq t.1)
  2364. movq z, %rax
  2365. addq t.1, %rax
  2366. jmp conclusion
  2367. \end{lstlisting}
  2368. \end{minipage}
  2369. \vrule\hspace{10pt}
  2370. \begin{minipage}{0.45\textwidth}
  2371. \begin{lstlisting}
  2372. |$\{\}$|
  2373. |$\{v \}$|
  2374. |$\{v,w\}$|
  2375. |$\{w,x\}$|
  2376. |$\{w,x\}$|
  2377. |$\{w,x,y\}$|
  2378. |$\{w,x,y\}$|
  2379. |$\{w,y,z\}$|
  2380. |$\{y,z\}$|
  2381. |$\{z,t.1\}$|
  2382. |$\{z,t.1\}$|
  2383. |$\{t.1\}$|
  2384. |$\{\}$|
  2385. |$\{\}$|
  2386. \end{lstlisting}
  2387. \end{minipage}
  2388. \caption{The running example annotated with live-after sets.}
  2389. \label{fig:live-eg}
  2390. \end{figure}
  2391. \begin{exercise}\normalfont
  2392. Implement the compiler pass named \code{uncover-live} that computes
  2393. the live-after sets. We recommend storing the live-after sets (a list
  2394. of lists of variables) in the $\itm{info}$ field of the \key{Block}
  2395. structure.
  2396. %
  2397. We recommend organizing your code to use a helper function that takes
  2398. a list of instructions and an initial live-after set (typically empty)
  2399. and returns the list of live-after sets.
  2400. %
  2401. We recommend creating helper functions to 1) compute the set of
  2402. variables that appear in an argument (of an instruction), 2) compute
  2403. the variables read by an instruction which corresponds to the $R$
  2404. function discussed above, and 3) the variables written by an
  2405. instruction which corresponds to $W$.
  2406. \end{exercise}
  2407. \section{Building the Interference Graph}
  2408. \label{sec:build-interference}
  2409. Based on the liveness analysis, we know where each variable is needed.
  2410. However, during register allocation, we need to answer questions of
  2411. the specific form: are variables $u$ and $v$ live at the same time?
  2412. (And therefore cannot be assigned to the same register.) To make this
  2413. question easier to answer, we create an explicit data structure, an
  2414. \emph{interference graph}. An interference graph is an undirected
  2415. graph that has an edge between two variables if they are live at the
  2416. same time, that is, if they interfere with each other.
  2417. The most obvious way to compute the interference graph is to look at
  2418. the set of live variables between each statement in the program and
  2419. add an edge to the graph for every pair of variables in the same set.
  2420. This approach is less than ideal for two reasons. First, it can be
  2421. expensive because it takes $O(n^2)$ time to look at every pair in a
  2422. set of $n$ live variables. Second, there is a special case in which
  2423. two variables that are live at the same time do not actually interfere
  2424. with each other: when they both contain the same value because we have
  2425. assigned one to the other.
  2426. A better way to compute the interference graph is to focus on the
  2427. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2428. instruction to overwrite something in a live variable. So for each
  2429. instruction, we create an edge between the variable being written to
  2430. and all the \emph{other} live variables. (One should not create self
  2431. edges.) For a \key{callq} instruction, think of all caller-saved
  2432. registers as being written to, so an edge must be added between every
  2433. live variable and every caller-saved register. For \key{movq}, we deal
  2434. with the above-mentioned special case by not adding an edge between a
  2435. live variable $v$ and destination $d$ if $v$ matches the source of the
  2436. move. So we have the following three rules.
  2437. \begin{enumerate}
  2438. \item If instruction $I_k$ is an arithmetic instruction such as
  2439. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2440. L_{\mathsf{after}}(k)$ unless $v = d$.
  2441. \item If instruction $I_k$ is of the form \key{callq}
  2442. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2443. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2444. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2445. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2446. d$ or $v = s$.
  2447. \end{enumerate}
  2448. \margincomment{JM: I think you could give examples of each one of these
  2449. using the example program and use those to help explain why these
  2450. rules are correct.\\
  2451. JS: Agreed.}
  2452. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2453. the following interference for the instruction at the specified line
  2454. number.
  2455. \begin{quote}
  2456. Line 2: no interference,\\
  2457. Line 3: $w$ interferes with $v$,\\
  2458. Line 4: $x$ interferes with $w$,\\
  2459. Line 5: $x$ interferes with $w$,\\
  2460. Line 6: $y$ interferes with $w$,\\
  2461. Line 7: $y$ interferes with $w$ and $x$,\\
  2462. Line 8: $z$ interferes with $w$ and $y$,\\
  2463. Line 9: $z$ interferes with $y$, \\
  2464. Line 10: $t.1$ interferes with $z$, \\
  2465. Line 11: $t.1$ interferes with $z$, \\
  2466. Line 12: no interference, \\
  2467. Line 13: no interference. \\
  2468. Line 14: no interference.
  2469. \end{quote}
  2470. The resulting interference graph is shown in
  2471. Figure~\ref{fig:interfere}.
  2472. \begin{figure}[tbp]
  2473. \large
  2474. \[
  2475. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2476. \node (v) at (0,0) {$v$};
  2477. \node (w) at (2,0) {$w$};
  2478. \node (x) at (4,0) {$x$};
  2479. \node (t1) at (6,-2) {$t.1$};
  2480. \node (y) at (2,-2) {$y$};
  2481. \node (z) at (4,-2) {$z$};
  2482. \draw (v) to (w);
  2483. \foreach \i in {w,x,y}
  2484. {
  2485. \foreach \j in {w,x,y}
  2486. {
  2487. \draw (\i) to (\j);
  2488. }
  2489. }
  2490. \draw (z) to (w);
  2491. \draw (z) to (y);
  2492. \draw (t1) to (z);
  2493. \end{tikzpicture}
  2494. \]
  2495. \caption{The interference graph of the example program.}
  2496. \label{fig:interfere}
  2497. \end{figure}
  2498. %% Our next concern is to choose a data structure for representing the
  2499. %% interference graph. There are many choices for how to represent a
  2500. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2501. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2502. %% data structure is to study the algorithm that uses the data structure,
  2503. %% determine what operations need to be performed, and then choose the
  2504. %% data structure that provide the most efficient implementations of
  2505. %% those operations. Often times the choice of data structure can have an
  2506. %% effect on the time complexity of the algorithm, as it does here. If
  2507. %% you skim the next section, you will see that the register allocation
  2508. %% algorithm needs to ask the graph for all of its vertices and, given a
  2509. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2510. %% correct choice of graph representation is that of an adjacency
  2511. %% list. There are helper functions in \code{utilities.rkt} for
  2512. %% representing graphs using the adjacency list representation:
  2513. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2514. %% (Appendix~\ref{appendix:utilities}).
  2515. %% %
  2516. %% \margincomment{\footnotesize To do: change to use the
  2517. %% Racket graph library. \\ --Jeremy}
  2518. %% %
  2519. %% In particular, those functions use a hash table to map each vertex to
  2520. %% the set of adjacent vertices, and the sets are represented using
  2521. %% Racket's \key{set}, which is also a hash table.
  2522. \begin{exercise}\normalfont
  2523. Implement the compiler pass named \code{build-interference} according
  2524. to the algorithm suggested above. We recommend using the Racket
  2525. \code{graph} package to create and inspect the interference graph.
  2526. The output graph of this pass should be stored in the $\itm{info}$
  2527. field of the program, under the key \code{conflicts}.
  2528. \end{exercise}
  2529. \section{Graph Coloring via Sudoku}
  2530. \label{sec:graph-coloring}
  2531. We come to the main event, mapping variables to registers (or to stack
  2532. locations in the event that we run out of registers). We need to make
  2533. sure that two variables do not get mapped to the same register if the
  2534. two variables interfere with each other. Thinking about the
  2535. interference graph, this means that adjacent vertices must be mapped
  2536. to different registers. If we think of registers as colors, the
  2537. register allocation problem becomes the widely-studied graph coloring
  2538. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2539. The reader may be more familiar with the graph coloring problem than he
  2540. or she realizes; the popular game of Sudoku is an instance of the
  2541. graph coloring problem. The following describes how to build a graph
  2542. out of an initial Sudoku board.
  2543. \begin{itemize}
  2544. \item There is one vertex in the graph for each Sudoku square.
  2545. \item There is an edge between two vertices if the corresponding squares
  2546. are in the same row, in the same column, or if the squares are in
  2547. the same $3\times 3$ region.
  2548. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2549. \item Based on the initial assignment of numbers to squares in the
  2550. Sudoku board, assign the corresponding colors to the corresponding
  2551. vertices in the graph.
  2552. \end{itemize}
  2553. If you can color the remaining vertices in the graph with the nine
  2554. colors, then you have also solved the corresponding game of Sudoku.
  2555. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2556. the corresponding graph with colored vertices. We map the Sudoku
  2557. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2558. sampling of the vertices (the colored ones) because showing edges for
  2559. all of the vertices would make the graph unreadable.
  2560. \begin{figure}[tbp]
  2561. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2562. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2563. \caption{A Sudoku game board and the corresponding colored graph.}
  2564. \label{fig:sudoku-graph}
  2565. \end{figure}
  2566. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2567. strategies to come up with an algorithm for allocating registers. For
  2568. example, one of the basic techniques for Sudoku is called Pencil
  2569. Marks. The idea is to use a process of elimination to determine what
  2570. numbers no longer make sense for a square and write down those
  2571. numbers in the square (writing very small). For example, if the number
  2572. $1$ is assigned to a square, then by process of elimination, you can
  2573. write the pencil mark $1$ in all the squares in the same row, column,
  2574. and region. Many Sudoku computer games provide automatic support for
  2575. Pencil Marks.
  2576. %
  2577. The Pencil Marks technique corresponds to the notion of
  2578. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2579. vertex, in Sudoku terms, is the set of numbers that are no longer
  2580. available. In graph terminology, we have the following definition:
  2581. \begin{equation*}
  2582. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2583. \text{ and } \mathrm{color}(v) = c \}
  2584. \end{equation*}
  2585. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2586. edge with $u$.
  2587. Using the Pencil Marks technique leads to a simple strategy for
  2588. filling in numbers: if there is a square with only one possible number
  2589. left, then choose that number! But what if there are no squares with
  2590. only one possibility left? One brute-force approach is to try them
  2591. all: choose the first and if it ultimately leads to a solution,
  2592. great. If not, backtrack and choose the next possibility. One good
  2593. thing about Pencil Marks is that it reduces the degree of branching in
  2594. the search tree. Nevertheless, backtracking can be horribly time
  2595. consuming. One way to reduce the amount of backtracking is to use the
  2596. most-constrained-first heuristic. That is, when choosing a square,
  2597. always choose one with the fewest possibilities left (the vertex with
  2598. the highest saturation). The idea is that choosing highly constrained
  2599. squares earlier rather than later is better because later on there may
  2600. not be any possibilities left for those squares.
  2601. In some sense, register allocation is easier than Sudoku because the
  2602. register allocator can choose to map variables to stack locations when
  2603. the registers run out. Thus, it makes sense to drop backtracking in
  2604. favor of greedy search, that is, make the best choice at the time and
  2605. keep going. We still wish to minimize the number of colors needed, so
  2606. keeping the most-constrained-first heuristic is a good idea.
  2607. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2608. algorithm for register allocation based on saturation and the
  2609. most-constrained-first heuristic. It is roughly equivalent to the
  2610. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2611. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2612. Sudoku, the algorithm represents colors with integers. The first $k$
  2613. colors corresponding to the $k$ registers in a given machine and the
  2614. rest of the integers corresponding to stack locations.
  2615. \begin{figure}[btp]
  2616. \centering
  2617. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2618. Algorithm: DSATUR
  2619. Input: a graph |$G$|
  2620. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2621. |$W \gets \mathit{vertices}(G)$|
  2622. while |$W \neq \emptyset$| do
  2623. pick a vertex |$u$| from |$W$| with the highest saturation,
  2624. breaking ties randomly
  2625. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2626. |$\mathrm{color}[u] \gets c$|
  2627. |$W \gets W - \{u\}$|
  2628. \end{lstlisting}
  2629. \caption{The saturation-based greedy graph coloring algorithm.}
  2630. \label{fig:satur-algo}
  2631. \end{figure}
  2632. With this algorithm in hand, let us return to the running example and
  2633. consider how to color the interference graph in
  2634. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2635. colored and they are unsaturated, so we annotate each of them with a
  2636. dash for their color and an empty set for the saturation.
  2637. \[
  2638. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2639. \node (v) at (0,0) {$v:-,\{\}$};
  2640. \node (w) at (3,0) {$w:-,\{\}$};
  2641. \node (x) at (6,0) {$x:-,\{\}$};
  2642. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2643. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2644. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2645. \draw (v) to (w);
  2646. \foreach \i in {w,x,y}
  2647. {
  2648. \foreach \j in {w,x,y}
  2649. {
  2650. \draw (\i) to (\j);
  2651. }
  2652. }
  2653. \draw (z) to (w);
  2654. \draw (z) to (y);
  2655. \draw (t1) to (z);
  2656. \end{tikzpicture}
  2657. \]
  2658. The algorithm says to select a maximally saturated vertex and color it
  2659. $0$. In this case we have a 7-way tie, so we arbitrarily pick
  2660. $t.1$. We then mark color $0$ as no longer available for $z$ because
  2661. it interferes with $t.1$.
  2662. \[
  2663. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2664. \node (v) at (0,0) {$v:-,\{\}$};
  2665. \node (w) at (3,0) {$w:-,\{\}$};
  2666. \node (x) at (6,0) {$x:-,\{\}$};
  2667. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2668. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2669. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2670. \draw (v) to (w);
  2671. \foreach \i in {w,x,y}
  2672. {
  2673. \foreach \j in {w,x,y}
  2674. {
  2675. \draw (\i) to (\j);
  2676. }
  2677. }
  2678. \draw (z) to (w);
  2679. \draw (z) to (y);
  2680. \draw (t1) to (z);
  2681. \end{tikzpicture}
  2682. \]
  2683. Next we repeat the process, selecting another maximally saturated
  2684. vertex, which is $z$, and color it with the first available number,
  2685. which is $1$.
  2686. \[
  2687. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2688. \node (v) at (0,0) {$v:-,\{\}$};
  2689. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2690. \node (x) at (6,0) {$x:-,\{\}$};
  2691. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2692. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2693. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2694. \draw (t1) to (z);
  2695. \draw (v) to (w);
  2696. \foreach \i in {w,x,y}
  2697. {
  2698. \foreach \j in {w,x,y}
  2699. {
  2700. \draw (\i) to (\j);
  2701. }
  2702. }
  2703. \draw (z) to (w);
  2704. \draw (z) to (y);
  2705. \end{tikzpicture}
  2706. \]
  2707. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2708. first available color, which is $0$.
  2709. \[
  2710. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2711. \node (v) at (0,0) {$v:-,\{\}$};
  2712. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2713. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2714. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2715. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2716. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2717. \draw (t1) to (z);
  2718. \draw (v) to (w);
  2719. \foreach \i in {w,x,y}
  2720. {
  2721. \foreach \j in {w,x,y}
  2722. {
  2723. \draw (\i) to (\j);
  2724. }
  2725. }
  2726. \draw (z) to (w);
  2727. \draw (z) to (y);
  2728. \end{tikzpicture}
  2729. \]
  2730. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2731. We cannot choose $0$ or $1$ because those numbers are in $w$'s
  2732. saturation set. Indeed, $w$ interferes with $y$ and $z$, whose colors
  2733. are $0$ and $1$ respectively.
  2734. \[
  2735. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2736. \node (v) at (0,0) {$v:-,\{2\}$};
  2737. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2738. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2739. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2740. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2741. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2742. \draw (t1) to (z);
  2743. \draw (v) to (w);
  2744. \foreach \i in {w,x,y}
  2745. {
  2746. \foreach \j in {w,x,y}
  2747. {
  2748. \draw (\i) to (\j);
  2749. }
  2750. }
  2751. \draw (z) to (w);
  2752. \draw (z) to (y);
  2753. \end{tikzpicture}
  2754. \]
  2755. Now $x$ has the highest saturation, so we color it $1$.
  2756. \[
  2757. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2758. \node (v) at (0,0) {$v:-,\{2\}$};
  2759. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2760. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2761. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2762. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2763. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2764. \draw (t1) to (z);
  2765. \draw (v) to (w);
  2766. \foreach \i in {w,x,y}
  2767. {
  2768. \foreach \j in {w,x,y}
  2769. {
  2770. \draw (\i) to (\j);
  2771. }
  2772. }
  2773. \draw (z) to (w);
  2774. \draw (z) to (y);
  2775. \end{tikzpicture}
  2776. \]
  2777. In the last step of the algorithm, we color $v$ with $0$.
  2778. \[
  2779. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2780. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2781. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2782. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2783. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2784. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2785. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2786. \draw (t1) to (z);
  2787. \draw (v) to (w);
  2788. \foreach \i in {w,x,y}
  2789. {
  2790. \foreach \j in {w,x,y}
  2791. {
  2792. \draw (\i) to (\j);
  2793. }
  2794. }
  2795. \draw (z) to (w);
  2796. \draw (z) to (y);
  2797. \end{tikzpicture}
  2798. \]
  2799. With the coloring complete, we finalize the assignment of variables to
  2800. registers and stack locations. Recall that if we have $k$ registers,
  2801. we map the first $k$ colors to registers and the rest to stack
  2802. locations. Suppose for the moment that we have just one register to
  2803. use for register allocation, \key{rcx}. Then the following is the
  2804. mapping of colors to registers and stack allocations.
  2805. \[
  2806. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2807. \]
  2808. Putting this mapping together with the above coloring of the
  2809. variables, we arrive at the following assignment of variables to
  2810. registers and stack locations.
  2811. \begin{gather*}
  2812. \{ v \mapsto \key{\%rcx}, \,
  2813. w \mapsto \key{-16(\%rbp)}, \,
  2814. x \mapsto \key{-8(\%rbp)}, \\
  2815. y \mapsto \key{\%rcx}, \,
  2816. z\mapsto \key{-8(\%rbp)},
  2817. t.1\mapsto \key{\%rcx} \}
  2818. \end{gather*}
  2819. Applying this assignment to our running example, on the left, yields
  2820. the program on the right.
  2821. % why frame size of 32? -JGS
  2822. \begin{center}
  2823. \begin{minipage}{0.3\textwidth}
  2824. \begin{lstlisting}
  2825. movq $1, v
  2826. movq $46, w
  2827. movq v, x
  2828. addq $7, x
  2829. movq x, y
  2830. addq $4, y
  2831. movq x, z
  2832. addq w, z
  2833. movq y, t.1
  2834. negq t.1
  2835. movq z, %rax
  2836. addq t.1, %rax
  2837. jmp conclusion
  2838. \end{lstlisting}
  2839. \end{minipage}
  2840. $\Rightarrow\qquad$
  2841. \begin{minipage}{0.45\textwidth}
  2842. \begin{lstlisting}
  2843. movq $1, %rcx
  2844. movq $46, -16(%rbp)
  2845. movq %rcx, -8(%rbp)
  2846. addq $7, -8(%rbp)
  2847. movq -8(%rbp), %rcx
  2848. addq $4, %rcx
  2849. movq -8(%rbp), -8(%rbp)
  2850. addq -16(%rbp), -8(%rbp)
  2851. movq %rcx, %rcx
  2852. negq %rcx
  2853. movq -8(%rbp), %rax
  2854. addq %rcx, %rax
  2855. jmp conclusion
  2856. \end{lstlisting}
  2857. \end{minipage}
  2858. \end{center}
  2859. The resulting program is almost an x86 program. The remaining step is
  2860. the patch instructions pass. In this example, the trivial move of
  2861. \code{-8(\%rbp)} to itself is deleted and the addition of
  2862. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2863. \code{rax} as follows.
  2864. \begin{lstlisting}
  2865. movq -16(%rbp), %rax
  2866. addq %rax, -8(%rbp)
  2867. \end{lstlisting}
  2868. An overview of all of the passes involved in register allocation is
  2869. shown in Figure~\ref{fig:reg-alloc-passes}.
  2870. \begin{figure}[tbp]
  2871. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2872. \node (R1) at (0,2) {\large $R_1$};
  2873. \node (R1-2) at (3,2) {\large $R_1$};
  2874. \node (R1-3) at (6,2) {\large $R_1$};
  2875. \node (C0-1) at (6,0) {\large $C_0$};
  2876. \node (C0-2) at (3,0) {\large $C_0$};
  2877. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2878. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2879. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2880. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2881. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2882. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2883. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2884. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2885. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2886. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2887. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2888. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2889. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2890. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2891. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2892. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2893. \end{tikzpicture}
  2894. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2895. \label{fig:reg-alloc-passes}
  2896. \end{figure}
  2897. \begin{exercise}\normalfont
  2898. Implement the pass \code{allocate-registers}, which should come
  2899. after the \code{build-interference} pass. The three new passes,
  2900. \code{uncover-live}, \code{build-interference}, and
  2901. \code{allocate-registers} replace the \code{assign-homes} pass of
  2902. Section~\ref{sec:assign-r1}.
  2903. We recommend that you create a helper function named
  2904. \code{color-graph} that takes an interference graph and a list of
  2905. all the variables in the program. This function should return a
  2906. mapping of variables to their colors (represented as natural
  2907. numbers). By creating this helper function, you will be able to
  2908. reuse it in Chapter~\ref{ch:functions} when you add support for
  2909. functions.
  2910. Once you have obtained the coloring from \code{color-graph}, you can
  2911. assign the variables to registers or stack locations and then reuse
  2912. code from the \code{assign-homes} pass from
  2913. Section~\ref{sec:assign-r1} to replace the variables with their
  2914. assigned location.
  2915. Test your updated compiler by creating new example programs that
  2916. exercise all of the register allocation algorithm, such as forcing
  2917. variables to be spilled to the stack.
  2918. \end{exercise}
  2919. \section{Print x86 and Conventions for Registers}
  2920. \label{sec:print-x86-reg-alloc}
  2921. Recall that the \code{print-x86} pass generates the prelude and
  2922. conclusion instructions for the \code{main} function.
  2923. %
  2924. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2925. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2926. reason for this is that our \code{main} function must adhere to the
  2927. x86 calling conventions that we described in
  2928. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2929. function needs to restore (in the conclusion) any callee-saved
  2930. registers that get used during register allocation. The simplest
  2931. approach is to save and restore all of the callee-saved registers. The
  2932. more efficient approach is to keep track of which callee-saved
  2933. registers were used and only save and restore them. Either way, make
  2934. sure to take this use of stack space into account when you are
  2935. calculating the size of the frame. Also, don't forget that the size of
  2936. the frame needs to be a multiple of 16 bytes.
  2937. \section{Challenge: Move Biasing$^{*}$}
  2938. \label{sec:move-biasing}
  2939. This section describes an optional enhancement to register allocation
  2940. for those students who are looking for an extra challenge or who have
  2941. a deeper interest in register allocation.
  2942. We return to the running example, but we remove the supposition that
  2943. we only have one register to use. So we have the following mapping of
  2944. color numbers to registers.
  2945. \[
  2946. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  2947. \]
  2948. Using the same assignment of variables to color numbers that was
  2949. produced by the register allocator described in the last section, we
  2950. get the following program.
  2951. \begin{minipage}{0.3\textwidth}
  2952. \begin{lstlisting}
  2953. movq $1, v
  2954. movq $46, w
  2955. movq v, x
  2956. addq $7, x
  2957. movq x, y
  2958. addq $4, y
  2959. movq x, z
  2960. addq w, z
  2961. movq y, t.1
  2962. negq t.1
  2963. movq z, %rax
  2964. addq t.1, %rax
  2965. jmp conclusion
  2966. \end{lstlisting}
  2967. \end{minipage}
  2968. $\Rightarrow\qquad$
  2969. \begin{minipage}{0.45\textwidth}
  2970. \begin{lstlisting}
  2971. movq $1, %rbx
  2972. movq $46, %rdx
  2973. movq %rbx, %rcx
  2974. addq $7, %rcx
  2975. movq %rcx, %rbx
  2976. addq $4, %rbx
  2977. movq %rcx, %rcx
  2978. addq %rdx, %rcx
  2979. movq %rbx, %rbx
  2980. negq %rbx
  2981. movq %rcx, %rax
  2982. addq %rbx, %rax
  2983. jmp conclusion
  2984. \end{lstlisting}
  2985. \end{minipage}
  2986. While this allocation is quite good, we could do better. For example,
  2987. the variables \key{v} and \key{x} ended up in different registers, but
  2988. if they had been placed in the same register, then the move from
  2989. \key{v} to \key{x} could be removed.
  2990. We say that two variables $p$ and $q$ are \emph{move related} if they
  2991. participate together in a \key{movq} instruction, that is, \key{movq}
  2992. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  2993. allocator chooses a color for a variable, it should prefer a color
  2994. that has already been used for a move-related variable (assuming that
  2995. they do not interfere). Of course, this preference should not override
  2996. the preference for registers over stack locations. This preference
  2997. should be used as a tie breaker when choosing between registers or
  2998. when choosing between stack locations.
  2999. We recommend representing the move relationships in a graph, similar
  3000. to how we represented interference. The following is the \emph{move
  3001. graph} for our running example.
  3002. \[
  3003. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3004. \node (v) at (0,0) {$v$};
  3005. \node (w) at (3,0) {$w$};
  3006. \node (x) at (6,0) {$x$};
  3007. \node (y) at (3,-1.5) {$y$};
  3008. \node (z) at (6,-1.5) {$z$};
  3009. \node (t1) at (9,-1.5) {$t.1$};
  3010. \draw[bend left=15] (t1) to (y);
  3011. \draw[bend left=15] (v) to (x);
  3012. \draw (x) to (y);
  3013. \draw (x) to (z);
  3014. \end{tikzpicture}
  3015. \]
  3016. Now we replay the graph coloring, pausing to see the coloring of $x$
  3017. and $v$. So we have the following coloring and the most saturated
  3018. vertex is $x$.
  3019. \[
  3020. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3021. \node (v) at (0,0) {$v:-,\{2\}$};
  3022. \node (w) at (3,0) {$w:2,\{0,1\}$};
  3023. \node (x) at (6,0) {$x:-,\{0,2\}$};
  3024. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3025. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3026. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3027. \draw (t1) to (z);
  3028. \draw (v) to (w);
  3029. \foreach \i in {w,x,y}
  3030. {
  3031. \foreach \j in {w,x,y}
  3032. {
  3033. \draw (\i) to (\j);
  3034. }
  3035. }
  3036. \draw (z) to (w);
  3037. \draw (z) to (y);
  3038. \end{tikzpicture}
  3039. \]
  3040. Last time we chose to color $x$ with $1$,
  3041. %
  3042. which so happens to be the color of $z$, and $x$ is move related to
  3043. $z$. This was lucky, and if the program had been a little different,
  3044. and say $z$ had been already assigned to $2$, then $x$ would still get
  3045. $1$ and our luck would have run out. With move biasing, we use the
  3046. fact that $x$ and $z$ are move related to influence the choice of
  3047. color for $x$, in this case choosing $1$ because that is the color of
  3048. $z$.
  3049. \[
  3050. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3051. \node (v) at (0,0) {$v:-,\{2\}$};
  3052. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3053. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  3054. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  3055. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3056. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3057. \draw (t1) to (z);
  3058. \draw (v) to (w);
  3059. \foreach \i in {w,x,y}
  3060. {
  3061. \foreach \j in {w,x,y}
  3062. {
  3063. \draw (\i) to (\j);
  3064. }
  3065. }
  3066. \draw (z) to (w);
  3067. \draw (z) to (y);
  3068. \end{tikzpicture}
  3069. \]
  3070. Next we consider coloring the variable $v$. We need to avoid choosing
  3071. $2$ because of the interference with $w$. Last time we chose the color
  3072. $0$ because it was the lowest, but this time we know that $v$ is move
  3073. related to $x$, so we choose the color $1$.
  3074. \[
  3075. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3076. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  3077. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3078. \node (x) at (6,0) {$x:1,\{0,2\}$};
  3079. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3080. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3081. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3082. \draw (t1) to (z);
  3083. \draw (v) to (w);
  3084. \foreach \i in {w,x,y}
  3085. {
  3086. \foreach \j in {w,x,y}
  3087. {
  3088. \draw (\i) to (\j);
  3089. }
  3090. }
  3091. \draw (z) to (w);
  3092. \draw (z) to (y);
  3093. \end{tikzpicture}
  3094. \]
  3095. We apply this register assignment to the running example, on the left,
  3096. to obtain the code on right.
  3097. \begin{minipage}{0.3\textwidth}
  3098. \begin{lstlisting}
  3099. movq $1, v
  3100. movq $46, w
  3101. movq v, x
  3102. addq $7, x
  3103. movq x, y
  3104. addq $4, y
  3105. movq x, z
  3106. addq w, z
  3107. movq y, t.1
  3108. negq t.1
  3109. movq z, %rax
  3110. addq t.1, %rax
  3111. jmp conclusion
  3112. \end{lstlisting}
  3113. \end{minipage}
  3114. $\Rightarrow\qquad$
  3115. \begin{minipage}{0.45\textwidth}
  3116. \begin{lstlisting}
  3117. movq $1, %rcx
  3118. movq $46, %rbx
  3119. movq %rcx, %rcx
  3120. addq $7, %rcx
  3121. movq %rcx, %rdx
  3122. addq $4, %rdx
  3123. movq %rcx, %rcx
  3124. addq %rbx, %rcx
  3125. movq %rdx, %rbx
  3126. negq %rbx
  3127. movq %rcx, %rax
  3128. addq %rbx, %rax
  3129. jmp conclusion
  3130. \end{lstlisting}
  3131. \end{minipage}
  3132. The \code{patch-instructions} then removes the trivial moves from
  3133. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  3134. result.
  3135. \begin{minipage}{0.45\textwidth}
  3136. \begin{lstlisting}
  3137. movq $1 %rcx
  3138. movq $46 %rbx
  3139. addq $7 %rcx
  3140. movq %rcx %rdx
  3141. addq $4 %rdx
  3142. addq %rbx %rcx
  3143. movq %rdx %rbx
  3144. negq %rbx
  3145. movq %rcx %rax
  3146. addq %rbx %rax
  3147. jmp conclusion
  3148. \end{lstlisting}
  3149. \end{minipage}
  3150. \begin{exercise}\normalfont
  3151. Change your implementation of \code{allocate-registers} to take move
  3152. biasing into account. Make sure that your compiler still passes all of
  3153. the previous tests. Create two new tests that include at least one
  3154. opportunity for move biasing and visually inspect the output x86
  3155. programs to make sure that your move biasing is working properly.
  3156. \end{exercise}
  3157. \margincomment{\footnotesize To do: another neat challenge would be to do
  3158. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3159. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3160. \chapter{Booleans and Control Flow}
  3161. \label{ch:bool-types}
  3162. The $R_0$ and $R_1$ languages only had a single kind of value, the
  3163. integers. In this chapter we add a second kind of value, the Booleans,
  3164. to create the $R_2$ language. The Boolean values \emph{true} and
  3165. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3166. Racket. The $R_2$ language includes several operations that involve
  3167. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3168. conditional \key{if} expression. With the addition of \key{if}
  3169. expressions, programs can have non-trivial control flow which has an
  3170. impact on several parts of the compiler. Also, because we now have two
  3171. kinds of values, we need to worry about programs that apply an
  3172. operation to the wrong kind of value, such as \code{(not 1)}.
  3173. There are two language design options for such situations. One option
  3174. is to signal an error and the other is to provide a wider
  3175. interpretation of the operation. The Racket language uses a mixture of
  3176. these two options, depending on the operation and the kind of
  3177. value. For example, the result of \code{(not 1)} in Racket is
  3178. \code{\#f} because Racket treats non-zero integers as if they were
  3179. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3180. error in Racket stating that \code{car} expects a pair.
  3181. The Typed Racket language makes similar design choices as Racket,
  3182. except much of the error detection happens at compile time instead of
  3183. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3184. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3185. reports a compile-time error because Typed Racket expects the type of
  3186. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3187. For the $R_2$ language we choose to be more like Typed Racket in that
  3188. we shall perform type checking during compilation. In
  3189. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3190. is, how to compile a dynamically typed language like Racket. The
  3191. $R_2$ language is a subset of Typed Racket but by no means includes
  3192. all of Typed Racket. Furthermore, for many of the operations we shall
  3193. take a narrower interpretation than Typed Racket, for example,
  3194. rejecting \code{(not 1)}.
  3195. This chapter is organized as follows. We begin by defining the syntax
  3196. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3197. then introduce the idea of type checking and build a type checker for
  3198. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3199. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3200. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  3201. how our compiler passes need to change to accommodate Booleans and
  3202. conditional control flow.
  3203. \section{The $R_2$ Language}
  3204. \label{sec:r2-lang}
  3205. The concrete syntax of the $R_2$ language is defined in
  3206. Figure~\ref{fig:r2-concretesyntax} and the abstract syntax is defined
  3207. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3208. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3209. and the conditional \code{if} expression. Also, we expand the
  3210. operators to include subtraction, \key{and}, \key{or} and \key{not},
  3211. the \key{eq?} operations for comparing two integers or two Booleans,
  3212. and the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3213. comparing integers.
  3214. \begin{figure}[tp]
  3215. \centering
  3216. \fbox{
  3217. \begin{minipage}{0.96\textwidth}
  3218. \[
  3219. \begin{array}{lcl}
  3220. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3221. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \mid (\key{-}\;\Exp\;\Exp) \\
  3222. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  3223. &\mid& \key{\#t} \mid \key{\#f}
  3224. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3225. \mid (\key{not}\;\Exp) \\
  3226. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3227. R_2 &::=& \Exp
  3228. \end{array}
  3229. \]
  3230. \end{minipage}
  3231. }
  3232. \caption{The concrete syntax of $R_2$, extending $R_1$
  3233. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3234. \label{fig:r2-concrete-syntax}
  3235. \end{figure}
  3236. \begin{figure}[tp]
  3237. \centering
  3238. \fbox{
  3239. \begin{minipage}{0.96\textwidth}
  3240. \[
  3241. \begin{array}{lcl}
  3242. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3243. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3244. \Exp &::=& \gray{\INT{\Int} \mid \READ{} \mid \NEG{\Exp}} \\
  3245. &\mid& \gray{\ADD{\Exp}{\Exp}}
  3246. \mid \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3247. &\mid& \gray{\VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp}} \\
  3248. &\mid& \BOOL{\itm{bool}}
  3249. \mid \AND{\Exp}{\Exp}\\
  3250. &\mid& \OR{\Exp}{\Exp}
  3251. \mid \NOT{\Exp} \\
  3252. &\mid& \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3253. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3254. \end{array}
  3255. \]
  3256. \end{minipage}
  3257. }
  3258. \caption{The abstract syntax of $R_2$.}
  3259. \label{fig:r2-syntax}
  3260. \end{figure}
  3261. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3262. the parts that are the same as the interpreter for $R_1$
  3263. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3264. simply evaluate to themselves. The conditional expression $(\key{if}\,
  3265. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  3266. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3267. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3268. operations \code{not} and \code{and} behave as you might expect, but
  3269. note that the \code{and} operation is short-circuiting. That is, given
  3270. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3271. evaluated if $e_1$ evaluates to \code{\#f}.
  3272. With the addition of the comparison operations, there are quite a few
  3273. primitive operations and the interpreter code for them is somewhat
  3274. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  3275. parts into the \code{interp-op} function and the similar parts into
  3276. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  3277. use \code{interp-op} for the \code{and} operation because of the
  3278. short-circuiting behavior in the order of evaluation of its arguments.
  3279. \begin{figure}[tbp]
  3280. \begin{lstlisting}
  3281. (define (interp-op op)
  3282. (match op
  3283. ...
  3284. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3285. ['eq? (lambda (v1 v2)
  3286. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3287. (and (boolean? v1) (boolean? v2)))
  3288. (eq? v1 v2)]))]
  3289. ['< (lambda (v1 v2)
  3290. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3291. ['<= (lambda (v1 v2)
  3292. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3293. ['> (lambda (v1 v2)
  3294. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3295. ['>= (lambda (v1 v2)
  3296. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3297. [else (error 'interp-op "unknown operator")]))
  3298. (define (interp-exp env)
  3299. (lambda (e)
  3300. (define recur (interp-exp env))
  3301. (match e
  3302. ...
  3303. [(Bool b) b]
  3304. [(If cnd thn els)
  3305. (define b (recur cnd))
  3306. (match b
  3307. [#t (recur thn)]
  3308. [#f (recur els)])]
  3309. [(Prim 'and (list e1 e2))
  3310. (define v1 (recur e1))
  3311. (match v1
  3312. [#t (match (recur e2) [#t #t] [#f #f])]
  3313. [#f #f])]
  3314. [(Prim op args)
  3315. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3316. )))
  3317. (define (interp-R2 p)
  3318. (match p
  3319. [(Program info e)
  3320. ((interp-exp '()) e)]
  3321. ))
  3322. \end{lstlisting}
  3323. \caption{Interpreter for the $R_2$ language.}
  3324. \label{fig:interp-R2}
  3325. \end{figure}
  3326. \section{Type Checking $R_2$ Programs}
  3327. \label{sec:type-check-r2}
  3328. It is helpful to think about type checking in two complementary
  3329. ways. A type checker predicts the \emph{type} of value that will be
  3330. produced by each expression in the program. For $R_2$, we have just
  3331. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3332. predict that
  3333. \begin{lstlisting}
  3334. (+ 10 (- (+ 12 20)))
  3335. \end{lstlisting}
  3336. produces an \key{Integer} while
  3337. \begin{lstlisting}
  3338. (and (not #f) #t)
  3339. \end{lstlisting}
  3340. produces a \key{Boolean}.
  3341. As mentioned at the beginning of this chapter, a type checker also
  3342. rejects programs that apply operators to the wrong type of value. Our
  3343. type checker for $R_2$ will signal an error for the below expression
  3344. because, as we have seen above, the expression \code{(+ 10 ...)} has
  3345. type \key{Integer}, and we require the argument of a \code{not} to
  3346. have type \key{Boolean}.
  3347. \begin{lstlisting}
  3348. (not (+ 10 (- (+ 12 20))))
  3349. \end{lstlisting}
  3350. The type checker for $R_2$ is best implemented as a structurally
  3351. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3352. many of the clauses for the \code{type-check-exp} function. Given an
  3353. input expression \code{e}, the type checker either returns the type
  3354. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3355. the type of an integer literal is \code{Integer} and the type of a
  3356. Boolean literal is \code{Boolean}. To handle variables, the type
  3357. checker, like the interpreter, uses an association list. However, in
  3358. this case the association list maps variables to types instead of
  3359. values. Consider the clause for \key{let}. We type check the
  3360. initializing expression to obtain its type \key{T} and then associate
  3361. type \code{T} with the variable \code{x}. When the type checker
  3362. encounters the use of a variable, it can find its type in the
  3363. association list.
  3364. \begin{figure}[tbp]
  3365. \begin{lstlisting}
  3366. (definepublic (type-check-exp env)
  3367. (lambda (e)
  3368. (match e
  3369. [(Var x) (dict-ref env x)]
  3370. [(Int n) 'Integer]
  3371. [(Bool b) 'Boolean]
  3372. [(Let x e body)
  3373. (define Te ((type-check-exp env) e))
  3374. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3375. Tb]
  3376. ...
  3377. [else
  3378. (error "type-check-exp couldn't match" e)])))
  3379. (define (type-check env)
  3380. (lambda (e)
  3381. (match e
  3382. [(Program info body)
  3383. (define Tb ((type-check-exp '()) body))
  3384. (unless (equal? Tb 'Integer)
  3385. (error "result of the program must be an integer, not " Tb))
  3386. (Program info body)]
  3387. )))
  3388. \end{lstlisting}
  3389. \caption{Skeleton of a type checker for the $R_2$ language.}
  3390. \label{fig:type-check-R2}
  3391. \end{figure}
  3392. %% To print the resulting value correctly, the overall type of the
  3393. %% program must be threaded through the remainder of the passes. We can
  3394. %% store the type within the \key{program} form as shown in Figure
  3395. %% \ref{fig:type-check-R2}. Let $R^\dagger_2$ be the name for the
  3396. %% intermediate language produced by the type checker, which we define as
  3397. %% follows: \\[1ex]
  3398. %% \fbox{
  3399. %% \begin{minipage}{0.87\textwidth}
  3400. %% \[
  3401. %% \begin{array}{lcl}
  3402. %% R^\dagger_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3403. %% \end{array}
  3404. %% \]
  3405. %% \end{minipage}
  3406. %% }
  3407. \begin{exercise}\normalfont
  3408. Complete the implementation of \code{type-check-R2} and test it on 10
  3409. new example programs in $R_2$ that you choose based on how thoroughly
  3410. they test the type checking algorithm. Half of the example programs
  3411. should have a type error, to make sure that your type checker properly
  3412. rejects them. The other half of the example programs should not have
  3413. type errors. Your testing should check that the result of the type
  3414. checker agrees with the value returned by the interpreter, that is, if
  3415. the type checker returns \key{Integer}, then the interpreter should
  3416. return an integer. Likewise, if the type checker returns
  3417. \key{Boolean}, then the interpreter should return \code{\#t} or
  3418. \code{\#f}. Note that if your type checker does not signal an error
  3419. for a program, then interpreting that program should not encounter an
  3420. error. If it does, there is something wrong with your type checker.
  3421. \end{exercise}
  3422. \section{Shrink the $R_2$ Language}
  3423. \label{sec:shrink-r2}
  3424. The $R_2$ language includes several operators that are easily
  3425. expressible in terms of other operators. For example, subtraction is
  3426. expressible in terms of addition and negation.
  3427. \[
  3428. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3429. \]
  3430. Several of the comparison operations are expressible in terms of
  3431. less-than and logical negation.
  3432. \[
  3433. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad
  3434. \LET{t_1}{e_1}{(\key{not}\;(\key{<}\;e_2\;t_1))}
  3435. \]
  3436. By performing these translations near the front-end of the compiler,
  3437. the later passes of the compiler do not need to deal with these
  3438. constructs, making those passes shorter. On the other hand, sometimes
  3439. these translations make it more difficult to generate the most
  3440. efficient code with respect to the number of instructions. However,
  3441. these differences typically do not affect the number of accesses to
  3442. memory, which is the primary factor that determines execution time on
  3443. modern computer architectures.
  3444. \begin{exercise}\normalfont
  3445. Implement the pass \code{shrink} that removes subtraction,
  3446. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3447. by translating them to other constructs in $R_2$. Create tests to
  3448. make sure that the behavior of all of these constructs stays the
  3449. same after translation.
  3450. \end{exercise}
  3451. \section{XOR, Comparisons, and Control Flow in x86}
  3452. \label{sec:x86-1}
  3453. To implement the new logical operations, the comparison operations,
  3454. and the \key{if} expression, we need to delve further into the x86
  3455. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3456. larger subset of x86 that includes instructions for logical
  3457. operations, comparisons, and jumps.
  3458. One small challenge is that x86 does not provide an instruction that
  3459. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3460. However, the \code{xorq} instruction can be used to encode \code{not}.
  3461. The \key{xorq} instruction takes two arguments, performs a pairwise
  3462. exclusive-or operation on each bit of its arguments, and writes the
  3463. results into its second argument. Recall the truth table for
  3464. exclusive-or:
  3465. \begin{center}
  3466. \begin{tabular}{l|cc}
  3467. & 0 & 1 \\ \hline
  3468. 0 & 0 & 1 \\
  3469. 1 & 1 & 0
  3470. \end{tabular}
  3471. \end{center}
  3472. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3473. in the row of the table for the bit $1$, the result is the opposite of the
  3474. second bit. Thus, the \code{not} operation can be implemented by
  3475. \code{xorq} with $1$ as the first argument:
  3476. \begin{align*}
  3477. 0001 \mathrel{\mathrm{XOR}} 0000 &= 0001\\
  3478. 0001 \mathrel{\mathrm{XOR}} 0001 &= 0000
  3479. \end{align*}
  3480. \begin{figure}[tp]
  3481. \fbox{
  3482. \begin{minipage}{0.96\textwidth}
  3483. \small
  3484. \[
  3485. \begin{array}{lcl}
  3486. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\code{'}\Reg} \mid \DEREF{\Reg}{\Int}}
  3487. \mid \BYTEREG{\code{'}\Reg} \\
  3488. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3489. \Instr &::=& \gray{\BININSTR{\code{'addq}}{\Arg}{\Arg}}
  3490. \mid \gray{\BININSTR{\code{'subq}}{\Arg}{\Arg}} \\
  3491. &\mid& \gray{\BININSTR{\code{'movq}}{\Arg}{\Arg}}
  3492. \mid \gray{\UNIINSTR{\code{'negq}}{\Arg}} \\
  3493. &\mid& \gray{\CALLQ{\itm{label}} \mid \RETQ{}}
  3494. \mid \gray{\PUSHQ{\Arg} \mid \POPQ{\Arg}} \\
  3495. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3496. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3497. &\mid& \BININSTR{\code{'set}}{\code{'}\itm{cc}}{\Arg}
  3498. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3499. &\mid& \JMP{\itm{label}}
  3500. \mid \JMPIF{\code{'}\itm{cc}}{\itm{label}} \\
  3501. % &\mid& (\key{label} \; \itm{label}) \\
  3502. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr^{+}}} \\
  3503. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}}
  3504. \end{array}
  3505. \]
  3506. \end{minipage}
  3507. }
  3508. \caption{The abstract syntax of $x86_1$ (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3509. \label{fig:x86-1}
  3510. \end{figure}
  3511. Next we consider the x86 instructions that are relevant for compiling
  3512. the comparison operations. The \key{cmpq} instruction compares its two
  3513. arguments to determine whether one argument is less than, equal, or
  3514. greater than the other argument. The \key{cmpq} instruction is unusual
  3515. regarding the order of its arguments and where the result is
  3516. placed. The argument order is backwards: if you want to test whether
  3517. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3518. \key{cmpq} is placed in the special EFLAGS register. This register
  3519. cannot be accessed directly but it can be queried by a number of
  3520. instructions, including the \key{set} instruction. The \key{set}
  3521. instruction puts a \key{1} or \key{0} into its destination depending
  3522. on whether the comparison came out according to the condition code
  3523. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3524. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3525. The \key{set} instruction has an annoying quirk in that its
  3526. destination argument must be single byte register, such as \code{al},
  3527. which is part of the \code{rax} register. Thankfully, the
  3528. \key{movzbq} instruction can then be used to move from a single byte
  3529. register to a normal 64-bit register.
  3530. For compiling the \key{if} expression, the x86 instructions for
  3531. jumping are relevant. The \key{Jmp} instruction updates the program
  3532. counter to point to the instruction after the indicated label. The
  3533. \key{JmpIf} instruction updates the program counter to point to the
  3534. instruction after the indicated label depending on whether the result
  3535. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3536. the \key{JmpIf} instruction falls through to the next
  3537. instruction. Because the \key{JmpIf} instruction relies on the EFLAGS
  3538. register, it is quite common for the \key{JmpIf} to be immediately
  3539. preceded by a \key{cmpq} instruction, to set the EFLAGS register.
  3540. Our abstract syntax for \key{JmpIf} differs from the concrete syntax
  3541. for x86 to separate the instruction name from the condition code. For
  3542. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}.
  3543. \section{The $C_1$ Intermediate Language}
  3544. \label{sec:c1}
  3545. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3546. language, but we need to grow that intermediate language to handle the
  3547. new features in $R_2$: Booleans and conditional expressions.
  3548. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3549. logic and comparison operators to the $\Exp$ non-terminal, the
  3550. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3551. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3552. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3553. goto's in the grammar for $\Tail$. This means that a sequence of
  3554. statements may now end with a \code{goto} or a conditional
  3555. \code{goto}, which jumps to one of two labeled pieces of code
  3556. depending on the outcome of the comparison. In
  3557. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3558. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3559. and \key{goto}'s.
  3560. \begin{figure}[tp]
  3561. \fbox{
  3562. \begin{minipage}{0.96\textwidth}
  3563. \small
  3564. \[
  3565. \begin{array}{lcl}
  3566. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3567. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3568. \Exp &::= & \gray{\Atm \mid \READ{} \mid \NEG{\Atm} }\\
  3569. &\mid& \gray{ \ADD{\Atm}{\Atm} }
  3570. \mid \UNIOP{\key{not}}{\Atm} \\
  3571. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \\
  3572. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3573. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} } \\
  3574. &\mid& \GOTO{\itm{label}} \mid \IFSTMT{\key{(}\itm{cmp}\,\Atm\,\Atm\key{)}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3575. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}}
  3576. \end{array}
  3577. \]
  3578. \end{minipage}
  3579. }
  3580. \caption{The abstract syntax of $C_1$, extending $C_0$ with Booleans and conditionals.}
  3581. \label{fig:c1-syntax}
  3582. \end{figure}
  3583. \section{Explicate Control}
  3584. \label{sec:explicate-control-r2}
  3585. Recall that the purpose of \code{explicate-control} is to make the
  3586. order of evaluation explicit in the syntax of the program. With the
  3587. addition of \key{if} in $R_2$, things get more interesting.
  3588. As a motivating example, consider the following program that has an
  3589. \key{if} expression nested in the predicate of another \key{if}.
  3590. % s1_38.rkt
  3591. \begin{center}
  3592. \begin{minipage}{0.96\textwidth}
  3593. \begin{lstlisting}
  3594. (if (if (eq? (read) 1)
  3595. (eq? (read) 0)
  3596. (eq? (read) 2))
  3597. (+ 10 32)
  3598. (+ 700 77))
  3599. \end{lstlisting}
  3600. \end{minipage}
  3601. \end{center}
  3602. %
  3603. The naive way to compile \key{if} and \key{eq?} would be to handle
  3604. each of them in isolation, regardless of their context. Each
  3605. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3606. by a couple instructions to move the result from the EFLAGS register
  3607. into a general purpose register or stack location. Each \key{if} would
  3608. be translated into the combination of a \key{cmpq} and \key{JmpIf}.
  3609. However, if we take context into account we can do better and reduce
  3610. the use of \key{cmpq} and EFLAG-accessing instructions.
  3611. One idea is to try and reorganize the code at the level of $R_2$,
  3612. pushing the outer \key{if} inside the inner one. This would yield the
  3613. following code.
  3614. \begin{center}
  3615. \begin{minipage}{0.96\textwidth}
  3616. \begin{lstlisting}
  3617. (if (eq? (read) 1)
  3618. (if (eq? (read) 0)
  3619. (+ 10 32)
  3620. (+ 700 77))
  3621. (if (eq? (read) 2))
  3622. (+ 10 32)
  3623. (+ 700 77))
  3624. \end{lstlisting}
  3625. \end{minipage}
  3626. \end{center}
  3627. Unfortunately, this approach duplicates the two branches, and a
  3628. compiler must never duplicate code!
  3629. We need a way to perform the above transformation, but without
  3630. duplicating code. The solution is straightforward if we think at the
  3631. level of x86 assembly: we can label the code for each of the branches
  3632. and insert jumps in all the places that need to execute the
  3633. branches. Put another way, we need to move away from abstract syntax
  3634. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3635. use a standard program representation called a \emph{control flow
  3636. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3637. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3638. each edge represents a jump to another block. The \key{Program}
  3639. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3640. as an association list mapping labels to basic blocks. Each block is
  3641. represented by the $\Tail$ non-terminal.
  3642. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3643. \code{remove-complex-opera*} pass and then the
  3644. \code{explicate-control} pass on the example program. We walk through
  3645. the output program and then discuss the algorithm.
  3646. %
  3647. Following the order of evaluation in the output of
  3648. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3649. comparison to \code{1} from the predicate of the inner \key{if}. In
  3650. the output of \code{explicate-control}, in the \code{start} block,
  3651. this becomes a \code{(read)} followed by a conditional goto to either
  3652. \code{block61} or \code{block62}. Each of these contains the
  3653. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3654. 1)}, respectively. Regarding \code{block61}, we start with the
  3655. \code{(read)} and comparison to \code{0} and then have a conditional
  3656. goto, either to \code{block59} or \code{block60}, which indirectly
  3657. take us to \code{block55} and \code{block56}, the two branches of the
  3658. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3659. story for \code{block62} is similar.
  3660. \begin{figure}[tbp]
  3661. \begin{tabular}{lll}
  3662. \begin{minipage}{0.4\textwidth}
  3663. \begin{lstlisting}
  3664. (if (if (eq? (read) 1)
  3665. (eq? (read) 0)
  3666. (eq? (read) 2))
  3667. (+ 10 32)
  3668. (+ 700 77))
  3669. \end{lstlisting}
  3670. \hspace{40pt}$\Downarrow$
  3671. \begin{lstlisting}
  3672. (if (if (let ([tmp52 (read)])
  3673. (eq? tmp52 1))
  3674. (let ([tmp53 (read)])
  3675. (eq? tmp53 0))
  3676. (let ([tmp54 (read)])
  3677. (eq? tmp54 2)))
  3678. (+ 10 32)
  3679. (+ 700 77))
  3680. \end{lstlisting}
  3681. \end{minipage}
  3682. &
  3683. $\Rightarrow$
  3684. &
  3685. \begin{minipage}{0.55\textwidth}
  3686. \begin{lstlisting}
  3687. block62:
  3688. tmp54 = (read);
  3689. if (eq? tmp54 2) then
  3690. goto block59;
  3691. else
  3692. goto block60;
  3693. block61:
  3694. tmp53 = (read);
  3695. if (eq? tmp53 0) then
  3696. goto block57;
  3697. else
  3698. goto block58;
  3699. block60:
  3700. goto block56;
  3701. block59:
  3702. goto block55;
  3703. block58:
  3704. goto block56;
  3705. block57:
  3706. goto block55;
  3707. block56:
  3708. return (+ 700 77);
  3709. block55:
  3710. return (+ 10 32);
  3711. start:
  3712. tmp52 = (read);
  3713. if (eq? tmp52 1) then
  3714. goto block61;
  3715. else
  3716. goto block62;
  3717. \end{lstlisting}
  3718. \end{minipage}
  3719. \end{tabular}
  3720. \caption{Example translation from $R_2$ to $C_1$
  3721. via the \code{explicate-control}.}
  3722. \label{fig:explicate-control-s1-38}
  3723. \end{figure}
  3724. The nice thing about the output of \code{explicate-control} is that
  3725. there are no unnecessary uses of \code{eq?} and every use of
  3726. \code{eq?} is part of a conditional jump. The down-side of this output
  3727. is that it includes trivial blocks, such as \code{block57} through
  3728. \code{block60}, that only jump to another block. We discuss a solution
  3729. to this problem in Section~\ref{sec:opt-jumps}.
  3730. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  3731. \code{explicate-control} for $R_1$ using two mutually recursive
  3732. functions, \code{explicate-tail} and \code{explicate-assign}. The
  3733. former function translates expressions in tail position whereas the
  3734. later function translates expressions on the right-hand-side of a
  3735. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  3736. new kind of context to deal with: the predicate position of the
  3737. \key{if}. We need another function, \code{explicate-pred}, that takes
  3738. an $R_2$ expression and two pieces of $C_1$ code (two $\Tail$'s) for
  3739. the then-branch and else-branch. The output of \code{explicate-pred}
  3740. is a $C_1$ $\Tail$. However, these three functions also need to
  3741. construct the control-flow graph, which we recommend they do via
  3742. updates to a global variable (be careful!). Next we consider the
  3743. specific additions to the tail and assign functions, and some of cases
  3744. for the pred function.
  3745. The \code{explicate-tail} function needs an additional case for
  3746. \key{if}. The branches of the \key{if} inherit the current context, so
  3747. they are in tail position. Let $B_1$ be the result of
  3748. \code{explicate-tail} on the $\itm{thn}$ branch and $B_2$ be the
  3749. result of apply \code{explicate-tail} to the $\itm{else}$ branch. Then
  3750. the \key{if} as a whole translates to the block $B_3$ which is the
  3751. result of applying \code{explicate-pred} to the predicate $\itm{cnd}$
  3752. and the blocks $B_1$ and $B_2$.
  3753. \[
  3754. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3755. \]
  3756. Next we consider the case for \key{if} in the
  3757. \code{explicate-assign} function. The context of the
  3758. \key{if} is an assignment to some variable $x$ and then the control
  3759. continues to some block $B_1$. The code that we generate for the
  3760. $\itm{thn}$ and $\itm{els}$ branches needs to continue to
  3761. $B_1$, so we add $B_1$ to the control flow graph with a fresh label
  3762. $\ell_1$. Again, the branches of the \key{if} inherit the current
  3763. context, so that are in assignment positions. Let $B_2$ be the result
  3764. of applying \code{explicate-assign} to the $\itm{thn}$ branch,
  3765. variable $x$, and the block \GOTO{$\ell_1$}. Let $B_3$ be the
  3766. result of applying \code{explicate-assign} to the $\itm{else}$
  3767. branch, variable $x$, and the block \GOTO{$\ell_1$}. The
  3768. \key{if} translates to the block $B_4$ which is the result of applying
  3769. \code{explicate-pred} to the predicate $\itm{cnd}$ and the
  3770. blocks $B_2$ and $B_3$.
  3771. \[
  3772. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3773. \]
  3774. The function \code{explicate-pred} will need a case for every
  3775. expression that can have type \code{Boolean}. We detail a few cases
  3776. here and leave the rest for the reader. The input to this function is
  3777. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3778. enclosing \key{if}. One of the base cases of this function is when the
  3779. expression is a less-than comparison. We translate it to a conditional
  3780. goto. We need labels for the two branches $B_1$ and $B_2$, so we add
  3781. them to the control flow graph and obtain some labels $\ell_1$ and
  3782. $\ell_2$. The translation of the less-than comparison is as follows.
  3783. \[
  3784. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  3785. \begin{array}{l}
  3786. \key{if}~(\key{<}~e_1~e_2)~\key{then} \\
  3787. \qquad\key{goto}~\ell_1\key{;}\\
  3788. \key{else}\\
  3789. \qquad\key{goto}~\ell_2\key{;}
  3790. \end{array}
  3791. \]
  3792. The case for \key{if} in \code{explicate-pred} is particularly
  3793. illuminating, as it deals with the challenges that we discussed above
  3794. regarding the example of the nested \key{if} expressions. Again, we
  3795. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3796. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3797. and $\itm{els}$ of the current \key{if} inherit their context from the
  3798. current one, i.e., predicate context. So we apply
  3799. \code{explicate-pred} to $\itm{thn}$ with the two blocks
  3800. \GOTO{$\ell_1$} and \GOTO{$\ell_2$}, to obtain $B_3$.
  3801. Proceed in a similar way with the $\itm{els}$ branch, to obtain $B_4$.
  3802. Finally, we apply \code{explicate-pred} to
  3803. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3804. to obtain the result $B_5$.
  3805. \[
  3806. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3807. \quad\Rightarrow\quad
  3808. B_5
  3809. \]
  3810. \begin{exercise}\normalfont
  3811. Implement the pass \code{explicate-code} by adding the cases for
  3812. \key{if} to the functions for tail and assignment contexts, and
  3813. implement the function for predicate contexts. Create test cases
  3814. that exercise all of the new cases in the code for this pass.
  3815. \end{exercise}
  3816. \section{Select Instructions}
  3817. \label{sec:select-r2}
  3818. Recall that the \code{select-instructions} pass lowers from our
  3819. $C$-like intermediate representation to the pseudo-x86 language, which
  3820. is suitable for conducting register allocation. The pass is
  3821. implemented using three auxiliary functions, one for each of the
  3822. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  3823. For $\Atm$, we have new cases for the Booleans. We take the usual
  3824. approach of encoding them as integers, with true as 1 and false as 0.
  3825. \[
  3826. \key{\#t} \Rightarrow \key{1}
  3827. \qquad
  3828. \key{\#f} \Rightarrow \key{0}
  3829. \]
  3830. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3831. be implemented in terms of \code{xorq} as we discussed at the
  3832. beginning of this section. Given an assignment
  3833. $\itm{lhs}$ \key{=} \key{(not} $\Arg$\key{);},
  3834. if the left-hand side $\itm{lhs}$ is
  3835. the same as $\Arg$, then just the \code{xorq} suffices.
  3836. \[
  3837. x~\key{=}~ \key{(not}\; x\key{);}
  3838. \quad\Rightarrow\quad
  3839. \key{xorq}~\key{\$}1\key{,}~x
  3840. \]
  3841. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3842. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3843. $\Arg$. Then we have
  3844. \[
  3845. \itm{lhs}~\key{=}~ \key{(not}\; \Arg\key{);}
  3846. \quad\Rightarrow\quad
  3847. \begin{array}{l}
  3848. \key{movq}~\Arg'\key{,}~\itm{lhs}\\
  3849. \key{xorq}~\key{\$}1\key{,}~\itm{lhs}
  3850. \end{array}
  3851. \]
  3852. Next consider the cases for \code{eq?} and less-than comparison.
  3853. Translating these operations to x86 is slightly involved due to the
  3854. unusual nature of the \key{cmpq} instruction discussed above. We
  3855. recommend translating an assignment from \code{eq?} into the following
  3856. sequence of three instructions. \\
  3857. \begin{tabular}{lll}
  3858. \begin{minipage}{0.4\textwidth}
  3859. \begin{lstlisting}
  3860. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3861. \end{lstlisting}
  3862. \end{minipage}
  3863. &
  3864. $\Rightarrow$
  3865. &
  3866. \begin{minipage}{0.4\textwidth}
  3867. \begin{lstlisting}
  3868. (cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3869. (set e (byte-reg al))
  3870. (movzbq (byte-reg al) |$\itm{lhs}'$|)
  3871. \end{lstlisting}
  3872. \end{minipage}
  3873. \end{tabular} \\
  3874. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3875. \key{goto} and conditional \key{goto}. Both are straightforward
  3876. to handle. A \key{goto} becomes a jump instruction.
  3877. \[
  3878. (\key{goto}\; \ell) \quad \Rightarrow \quad ((\key{jmp} \;\ell))
  3879. \]
  3880. A conditional \key{goto} becomes a compare instruction followed
  3881. by a conditional jump (for ``then'') and the fall-through is
  3882. to a regular jump (for ``else'').\\
  3883. \begin{tabular}{lll}
  3884. \begin{minipage}{0.4\textwidth}
  3885. \begin{lstlisting}
  3886. (if (eq? |$\Arg_1$| |$\Arg_2$|)
  3887. (goto |$\ell_1$|)
  3888. (goto |$\ell_2$|))
  3889. \end{lstlisting}
  3890. \end{minipage}
  3891. &
  3892. $\Rightarrow$
  3893. &
  3894. \begin{minipage}{0.4\textwidth}
  3895. \begin{lstlisting}
  3896. ((cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3897. (jmp-if e |$\ell_1$|)
  3898. (jmp |$\ell_2$|))
  3899. \end{lstlisting}
  3900. \end{minipage}
  3901. \end{tabular} \\
  3902. \begin{exercise}\normalfont
  3903. Expand your \code{select-instructions} pass to handle the new features
  3904. of the $R_2$ language. Test the pass on all the examples you have
  3905. created and make sure that you have some test programs that use the
  3906. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3907. the output using the \code{interp-x86} interpreter
  3908. (Appendix~\ref{appendix:interp}).
  3909. \end{exercise}
  3910. \section{Register Allocation}
  3911. \label{sec:register-allocation-r2}
  3912. The changes required for $R_2$ affect the liveness analysis, building
  3913. the interference graph, and assigning homes, but the graph coloring
  3914. algorithm itself does not need to change.
  3915. \subsection{Liveness Analysis}
  3916. \label{sec:liveness-analysis-r2}
  3917. Recall that for $R_1$ we implemented liveness analysis for a single
  3918. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3919. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3920. now produces many basic blocks arranged in a control-flow graph. The
  3921. first question we need to consider is in what order should we process
  3922. the basic blocks? Recall that to perform liveness analysis, we need to
  3923. know the live-after set. If a basic block has no successor blocks,
  3924. then it has an empty live-after set and we can immediately apply
  3925. liveness analysis to it. If a basic block has some successors, then we
  3926. need to complete liveness analysis on those blocks first.
  3927. Furthermore, we know that the control flow graph does not contain any
  3928. cycles (it is a DAG, that is, a directed acyclic graph)\footnote{If we
  3929. were to add loops to the language, then the CFG could contain cycles
  3930. and we would instead need to use the classic worklist algorithm for
  3931. computing the fixed point of the liveness
  3932. analysis~\citep{Aho:1986qf}.}. What all this amounts to is that we
  3933. need to process the basic blocks in reverse topological order. We
  3934. recommend using the \code{tsort} and \code{transpose} functions of the
  3935. Racket \code{graph} package to obtain this ordering.
  3936. The next question is how to compute the live-after set of a block
  3937. given the live-before sets of all its successor blocks. During
  3938. compilation we do not know which way the branch will go, so we do not
  3939. know which of the successor's live-before set to use. The solution
  3940. comes from the observation that there is no harm in identifying more
  3941. variables as live than absolutely necessary. Thus, we can take the
  3942. union of the live-before sets from all the successors to be the
  3943. live-after set for the block. Once we have computed the live-after
  3944. set, we can proceed to perform liveness analysis on the block just as
  3945. we did in Section~\ref{sec:liveness-analysis-r1}.
  3946. The helper functions for computing the variables in an instruction's
  3947. argument and for computing the variables read-from ($R$) or written-to
  3948. ($W$) by an instruction need to be updated to handle the new kinds of
  3949. arguments and instructions in x86$_1$.
  3950. \subsection{Build Interference}
  3951. \label{sec:build-interference-r2}
  3952. Many of the new instructions in x86$_1$ can be handled in the same way
  3953. as the instructions in x86$_0$. Thus, if your code was already quite
  3954. general, it will not need to be changed to handle the new
  3955. instructions. If not, I recommend that you change your code to be more
  3956. general. The \key{movzbq} instruction should be handled like the
  3957. \key{movq} instruction.
  3958. %% \subsection{Assign Homes}
  3959. %% \label{sec:assign-homes-r2}
  3960. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3961. %% to be updated to handle the \key{if} statement, simply by recursively
  3962. %% processing the child nodes. Hopefully your code already handles the
  3963. %% other new instructions, but if not, you can generalize your code.
  3964. \begin{exercise}\normalfont
  3965. Update the \code{register-allocation} pass so that it works for $R_2$
  3966. and test your compiler using your previously created programs on the
  3967. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3968. \end{exercise}
  3969. %% \section{Lower Conditionals (New Pass)}
  3970. %% \label{sec:lower-conditionals}
  3971. %% In the \code{select-instructions} pass we decided to procrastinate in
  3972. %% the lowering of the \key{if} statement, thereby making liveness
  3973. %% analysis easier. Now we need to make up for that and turn the \key{if}
  3974. %% statement into the appropriate instruction sequence. The following
  3975. %% translation gives the general idea. If the condition is true, we need
  3976. %% to execute the $\itm{thns}$ branch and otherwise we need to execute
  3977. %% the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3978. %% jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3979. %% is appropriate for the comparison operator \itm{cmp}. If the
  3980. %% condition is false, we fall through to the $\itm{elss}$ branch. At the
  3981. %% end of the $\itm{elss}$ branch we need to take care to not fall
  3982. %% through to the $\itm{thns}$ branch. So we jump to the
  3983. %% $\itm{endlabel}$. All of the labels in the generated code should be
  3984. %% created with \code{gensym}.
  3985. %% \begin{tabular}{lll}
  3986. %% \begin{minipage}{0.4\textwidth}
  3987. %% \begin{lstlisting}
  3988. %% (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3989. %% \end{lstlisting}
  3990. %% \end{minipage}
  3991. %% &
  3992. %% $\Rightarrow$
  3993. %% &
  3994. %% \begin{minipage}{0.4\textwidth}
  3995. %% \begin{lstlisting}
  3996. %% (cmpq |$\Arg_2$| |$\Arg_1$|)
  3997. %% (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3998. %% |$\itm{elss}$|
  3999. %% (jmp |$\itm{endlabel}$|)
  4000. %% (label |$\itm{thenlabel}$|)
  4001. %% |$\itm{thns}$|
  4002. %% (label |$\itm{endlabel}$|)
  4003. %% \end{lstlisting}
  4004. %% \end{minipage}
  4005. %% \end{tabular}
  4006. %% \begin{exercise}\normalfont
  4007. %% Implement the \code{lower-conditionals} pass. Test your compiler using
  4008. %% your previously created programs on the \code{interp-x86} interpreter
  4009. %% (Appendix~\ref{appendix:interp}).
  4010. %% \end{exercise}
  4011. \section{Patch Instructions}
  4012. The second argument of the \key{cmpq} instruction must not be an
  4013. immediate value (such as a literal integer). So if you are comparing
  4014. two immediates, we recommend inserting a \key{movq} instruction to put
  4015. the second argument in \key{rax}.
  4016. %
  4017. The second argument of the \key{movzbq} must be a register.
  4018. %
  4019. There are no special restrictions on the x86 instructions
  4020. \key{jmp-if}, \key{jmp}, and \key{label}.
  4021. \begin{exercise}\normalfont
  4022. Update \code{patch-instructions} to handle the new x86 instructions.
  4023. Test your compiler using your previously created programs on the
  4024. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4025. \end{exercise}
  4026. \section{An Example Translation}
  4027. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4028. $R_2$ translated to x86, showing the results of
  4029. \code{explicate-control}, \code{select-instructions}, and the final
  4030. x86 assembly code.
  4031. \begin{figure}[tbp]
  4032. \begin{tabular}{lll}
  4033. \begin{minipage}{0.5\textwidth}
  4034. % s1_20.rkt
  4035. \begin{lstlisting}
  4036. (program ()
  4037. (if (eq? (read) 1) 42 0))
  4038. \end{lstlisting}
  4039. $\Downarrow$
  4040. \begin{lstlisting}
  4041. (program ()
  4042. ((block32 . (return 0))
  4043. (block31 . (return 42))
  4044. (start .
  4045. (seq (assign tmp30 (read))
  4046. (if (eq? tmp30 1)
  4047. (goto block31)
  4048. (goto block32))))))
  4049. \end{lstlisting}
  4050. $\Downarrow$
  4051. \begin{lstlisting}
  4052. (program ((locals . (tmp30)))
  4053. ((block32 .
  4054. (block ()
  4055. (movq (int 0) %rax)
  4056. (jmp conclusion)))
  4057. (block31 .
  4058. (block ()
  4059. (movq (int 42) (reg rax))
  4060. (jmp conclusion)))
  4061. (start .
  4062. (block ()
  4063. (callq read_int)
  4064. (movq (reg rax) tmp30)
  4065. (cmpq (int 1) tmp30)
  4066. (jmp-if e block31)
  4067. (jmp block32)))))
  4068. \end{lstlisting}
  4069. \end{minipage}
  4070. &
  4071. $\Rightarrow$
  4072. \begin{minipage}{0.4\textwidth}
  4073. \begin{lstlisting}
  4074. _block31:
  4075. movq $42, %rax
  4076. jmp _conclusion
  4077. _block32:
  4078. movq $0, %rax
  4079. jmp _conclusion
  4080. _start:
  4081. callq _read_int
  4082. movq %rax, %rcx
  4083. cmpq $1, %rcx
  4084. je _block31
  4085. jmp _block32
  4086. .globl _main
  4087. _main:
  4088. pushq %rbp
  4089. movq %rsp, %rbp
  4090. pushq %r12
  4091. pushq %rbx
  4092. pushq %r13
  4093. pushq %r14
  4094. subq $0, %rsp
  4095. jmp _start
  4096. _conclusion:
  4097. addq $0, %rsp
  4098. popq %r14
  4099. popq %r13
  4100. popq %rbx
  4101. popq %r12
  4102. popq %rbp
  4103. retq
  4104. \end{lstlisting}
  4105. \end{minipage}
  4106. \end{tabular}
  4107. \caption{Example compilation of an \key{if} expression to x86.}
  4108. \label{fig:if-example-x86}
  4109. \end{figure}
  4110. \begin{figure}[p]
  4111. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4112. \node (R2) at (0,2) {\large $R_2$};
  4113. \node (R2-2) at (3,2) {\large $R_2$};
  4114. \node (R2-3) at (6,2) {\large $R_2$};
  4115. \node (R2-4) at (9,2) {\large $R_2$};
  4116. \node (R2-5) at (12,2) {\large $R_2$};
  4117. \node (C1-1) at (6,0) {\large $C_1$};
  4118. \node (C1-2) at (3,0) {\large $C_1$};
  4119. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4120. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4121. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4122. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  4123. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4124. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4125. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4126. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4127. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4128. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4129. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4130. \path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  4131. \path[->,bend right=15] (C1-2) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4132. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4133. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4134. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4135. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4136. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4137. \end{tikzpicture}
  4138. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4139. \label{fig:R2-passes}
  4140. \end{figure}
  4141. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4142. compilation of $R_2$.
  4143. \section{Challenge: Optimize Jumps$^{*}$}
  4144. \label{sec:opt-jumps}
  4145. UNDER CONSTRUCTION
  4146. %% \section{Challenge: Optimizing Conditions$^{*}$}
  4147. %% \label{sec:opt-if}
  4148. %% A close inspection of the x86 code generated in
  4149. %% Figure~\ref{fig:if-example-x86} reveals some redundant computation
  4150. %% regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  4151. %% twice using \key{cmpq} as follows.
  4152. %% % Wierd LaTeX bug if I remove the following. -Jeremy
  4153. %% % Does it have to do with page breaks?
  4154. %% \begin{lstlisting}
  4155. %% \end{lstlisting}
  4156. %% \begin{lstlisting}
  4157. %% cmpq $1, %rcx
  4158. %% sete %al
  4159. %% movzbq %al, %rcx
  4160. %% cmpq $1, %rcx
  4161. %% je then21288
  4162. %% \end{lstlisting}
  4163. %% The reason for this non-optimal code has to do with the \code{flatten}
  4164. %% pass earlier in this Chapter. We recommended flattening the condition
  4165. %% to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  4166. %% is already an \code{eq?} test, then we would like to use that
  4167. %% directly. In fact, for many of the expressions of Boolean type, we can
  4168. %% generate more optimized code. For example, if the condition is
  4169. %% \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  4170. %% all. If the condition is a \code{let}, we can optimize based on the
  4171. %% form of its body. If the condition is a \code{not}, then we can flip
  4172. %% the two branches.
  4173. %% %
  4174. %% \margincomment{\tiny We could do even better by converting to basic
  4175. %% blocks.\\ --Jeremy}
  4176. %% %
  4177. %% On the other hand, if the condition is a \code{and}
  4178. %% or another \code{if}, we should flatten them into an $\Arg$ to avoid
  4179. %% code duplication.
  4180. %% Figure~\ref{fig:opt-if} shows an example program and the result of
  4181. %% applying the above suggested optimizations.
  4182. %% \begin{exercise}\normalfont
  4183. %% Change the \code{flatten} pass to improve the code that gets
  4184. %% generated for \code{if} expressions. We recommend writing a helper
  4185. %% function that recursively traverses the condition of the \code{if}.
  4186. %% \end{exercise}
  4187. %% \begin{figure}[tbp]
  4188. %% \begin{tabular}{lll}
  4189. %% \begin{minipage}{0.5\textwidth}
  4190. %% \begin{lstlisting}
  4191. %% (program
  4192. %% (if (let ([x 1])
  4193. %% (not (eq? x (read))))
  4194. %% 777
  4195. %% 42))
  4196. %% \end{lstlisting}
  4197. %% $\Downarrow$
  4198. %% \begin{lstlisting}
  4199. %% (program (x.1 if.2 tmp.3)
  4200. %% (type Integer)
  4201. %% (assign x.1 1)
  4202. %% (assign tmp.3 (read))
  4203. %% (if (eq? x.1 tmp.3)
  4204. %% ((assign if.2 42))
  4205. %% ((assign if.2 777)))
  4206. %% (return if.2))
  4207. %% \end{lstlisting}
  4208. %% $\Downarrow$
  4209. %% \begin{lstlisting}
  4210. %% (program (x.1 if.2 tmp.3)
  4211. %% (type Integer)
  4212. %% (movq (int 1) (var x.1))
  4213. %% (callq read_int)
  4214. %% (movq (reg rax) (var tmp.3))
  4215. %% (if (eq? (var x.1) (var tmp.3))
  4216. %% ((movq (int 42) (var if.2)))
  4217. %% ((movq (int 777) (var if.2))))
  4218. %% (movq (var if.2) (reg rax)))
  4219. %% \end{lstlisting}
  4220. %% \end{minipage}
  4221. %% &
  4222. %% $\Rightarrow$
  4223. %% \begin{minipage}{0.4\textwidth}
  4224. %% \begin{lstlisting}
  4225. %% .globl _main
  4226. %% _main:
  4227. %% pushq %rbp
  4228. %% movq %rsp, %rbp
  4229. %% pushq %r13
  4230. %% pushq %r14
  4231. %% pushq %r12
  4232. %% pushq %rbx
  4233. %% subq $0, %rsp
  4234. %% movq $1, %rbx
  4235. %% callq _read_int
  4236. %% movq %rax, %rcx
  4237. %% cmpq %rcx, %rbx
  4238. %% je then35989
  4239. %% movq $777, %rbx
  4240. %% jmp if_end35990
  4241. %% then35989:
  4242. %% movq $42, %rbx
  4243. %% if_end35990:
  4244. %% movq %rbx, %rax
  4245. %% movq %rax, %rdi
  4246. %% callq _print_int
  4247. %% movq $0, %rax
  4248. %% addq $0, %rsp
  4249. %% popq %rbx
  4250. %% popq %r12
  4251. %% popq %r14
  4252. %% popq %r13
  4253. %% popq %rbp
  4254. %% retq
  4255. %% \end{lstlisting}
  4256. %% \end{minipage}
  4257. %% \end{tabular}
  4258. %% \caption{Example program with optimized conditionals.}
  4259. %% \label{fig:opt-if}
  4260. %% \end{figure}
  4261. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4262. \chapter{Tuples and Garbage Collection}
  4263. \label{ch:tuples}
  4264. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4265. things to discuss in this chapter. \\ --Jeremy}
  4266. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4267. all the IR grammars are spelled out! \\ --Jeremy}
  4268. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4269. but keep type annotations on vector creation and local variables, function
  4270. parameters, etc. \\ --Jeremy}
  4271. \margincomment{\scriptsize Be more explicit about how to deal with
  4272. the root stack. \\ --Jeremy}
  4273. In this chapter we study the implementation of mutable tuples (called
  4274. ``vectors'' in Racket). This language feature is the first to use the
  4275. computer's \emph{heap} because the lifetime of a Racket tuple is
  4276. indefinite, that is, a tuple lives forever from the programmer's
  4277. viewpoint. Of course, from an implementer's viewpoint, it is important
  4278. to reclaim the space associated with a tuple when it is no longer
  4279. needed, which is why we also study \emph{garbage collection}
  4280. techniques in this chapter.
  4281. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4282. interpreter and type checker. The $R_3$ language extends the $R_2$
  4283. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4284. ``void'' value. The reason for including the later is that the
  4285. \code{vector-set!} operation returns a value of type
  4286. \code{Void}\footnote{This may sound contradictory, but Racket's
  4287. \code{Void} type corresponds to what is more commonly called the
  4288. \code{Unit} type. This type is inhabited by a single value that is
  4289. usually written \code{unit} or \code{()}\citep{Pierce:2002hj}.}.
  4290. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4291. copying live objects back and forth between two halves of the
  4292. heap. The garbage collector requires coordination with the compiler so
  4293. that it can see all of the \emph{root} pointers, that is, pointers in
  4294. registers or on the procedure call stack.
  4295. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4296. discuss all the necessary changes and additions to the compiler
  4297. passes, including a new compiler pass named \code{expose-allocation}.
  4298. \section{The $R_3$ Language}
  4299. \label{sec:r3}
  4300. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  4301. includes three new forms for creating a tuple, reading an element of a
  4302. tuple, and writing to an element of a tuple. The program in
  4303. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4304. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  4305. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  4306. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  4307. ``then'' branch is taken. The element at index $0$ of \code{t} is
  4308. $40$, to which we add the $2$, the element at index $0$ of the
  4309. 1-tuple.
  4310. \begin{figure}[tbp]
  4311. \begin{lstlisting}
  4312. (let ([t (vector 40 #t (vector 2))])
  4313. (if (vector-ref t 1)
  4314. (+ (vector-ref t 0)
  4315. (vector-ref (vector-ref t 2) 0))
  4316. 44))
  4317. \end{lstlisting}
  4318. \caption{Example program that creates tuples and reads from them.}
  4319. \label{fig:vector-eg}
  4320. \end{figure}
  4321. \begin{figure}[tbp]
  4322. \centering
  4323. \fbox{
  4324. \begin{minipage}{0.96\textwidth}
  4325. \[
  4326. \begin{array}{lcl}
  4327. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4328. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4329. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4330. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4331. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4332. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4333. \mid (\key{and}\;\Exp\;\Exp)
  4334. \mid (\key{or}\;\Exp\;\Exp)
  4335. \mid (\key{not}\;\Exp) } \\
  4336. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4337. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4338. &\mid& (\key{vector}\;\Exp^{+})
  4339. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4340. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4341. &\mid& (\key{void}) \\
  4342. R_3 &::=& (\key{program} \; \Exp)
  4343. \end{array}
  4344. \]
  4345. \end{minipage}
  4346. }
  4347. \caption{The syntax of $R_3$, extending $R_2$
  4348. (Figure~\ref{fig:r2-syntax}) with tuples.}
  4349. \label{fig:r3-syntax}
  4350. \end{figure}
  4351. Tuples are our first encounter with heap-allocated data, which raises
  4352. several interesting issues. First, variable binding performs a
  4353. shallow-copy when dealing with tuples, which means that different
  4354. variables can refer to the same tuple, i.e., different variables can
  4355. be \emph{aliases} for the same thing. Consider the following example
  4356. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4357. the mutation through \code{t2} is visible when referencing the tuple
  4358. from \code{t1}, so the result of this program is \code{42}.
  4359. \begin{lstlisting}
  4360. (let ([t1 (vector 3 7)])
  4361. (let ([t2 t1])
  4362. (let ([_ (vector-set! t2 0 42)])
  4363. (vector-ref t1 0))))
  4364. \end{lstlisting}
  4365. The next issue concerns the lifetime of tuples. Of course, they are
  4366. created by the \code{vector} form, but when does their lifetime end?
  4367. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4368. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4369. is not tied to any notion of static scoping. For example, the
  4370. following program returns \code{3} even though the variable \code{t}
  4371. goes out of scope prior to accessing the vector.
  4372. \begin{lstlisting}
  4373. (vector-ref
  4374. (let ([t (vector 3 7)])
  4375. t)
  4376. 0)
  4377. \end{lstlisting}
  4378. From the perspective of programmer-observable behavior, tuples live
  4379. forever. Of course, if they really lived forever, then many programs
  4380. would run out of memory.\footnote{The $R_3$ language does not have
  4381. looping or recursive function, so it is nigh impossible to write a
  4382. program in $R_3$ that will run out of memory. However, we add
  4383. recursive functions in the next Chapter!} A Racket implementation
  4384. must therefore perform automatic garbage collection.
  4385. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4386. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4387. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4388. operations in Racket. One subtle point is that the \code{vector-set!}
  4389. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4390. can be passed around just like other values inside an $R_3$ program,
  4391. but there are no operations specific to the the \code{\#<void>} value
  4392. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4393. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4394. otherwise.
  4395. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$ , which
  4396. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4397. need to know which variables are pointers into the heap, that is,
  4398. which variables are vectors. Also, when allocating a vector, we shall
  4399. need to know which elements of the vector are pointers. We can obtain
  4400. this information during type checking and when we uncover local
  4401. variables. The type checker in Figure~\ref{fig:typecheck-R3} not only
  4402. computes the type of an expression, it also wraps every sub-expression
  4403. $e$ with the form $(\key{has-type}\; e\; T)$, where $T$ is $e$'s
  4404. type. Subsequently, in the \code{uncover-locals} pass
  4405. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4406. propagated to all variables (including the temporaries generated by
  4407. \code{remove-complex-opera*}).
  4408. \begin{figure}[tbp]
  4409. \begin{lstlisting}
  4410. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4411. (define (interp-op op)
  4412. (match op
  4413. ...
  4414. ['vector vector]
  4415. ['vector-ref vector-ref]
  4416. ['vector-set! vector-set!]
  4417. [else (error 'interp-op "unknown operator")]))
  4418. (define (interp-R3 env)
  4419. (lambda (e)
  4420. (match e
  4421. ...
  4422. [else (error 'interp-R3 "unrecognized expression")]
  4423. )))
  4424. \end{lstlisting}
  4425. \caption{Interpreter for the $R_3$ language.}
  4426. \label{fig:interp-R3}
  4427. \end{figure}
  4428. \begin{figure}[tbp]
  4429. \begin{lstlisting}
  4430. (define (type-check-exp env)
  4431. (lambda (e)
  4432. (define recur (type-check-exp env))
  4433. (match e
  4434. ...
  4435. ['(void) (values '(has-type (void) Void) 'Void)]
  4436. [`(vector ,es ...)
  4437. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4438. (recur e)))
  4439. (let ([t `(Vector ,@t*)])
  4440. (debug "vector/type-check-exp finished vector" t)
  4441. (values `(has-type (vector ,@e*) ,t) t))]
  4442. [`(vector-ref ,e ,i)
  4443. (define-values (e^ t) (recur e))
  4444. (match t
  4445. [`(Vector ,ts ...)
  4446. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4447. (error 'type-check-exp "invalid index ~a" i))
  4448. (let ([t (list-ref ts i)])
  4449. (values `(has-type (vector-ref ,e^ (has-type ,i Integer)) ,t)
  4450. t))]
  4451. [else (error "expected a vector in vector-ref, not" t)])]
  4452. [`(eq? ,arg1 ,arg2)
  4453. (define-values (e1 t1) (recur arg1))
  4454. (define-values (e2 t2) (recur arg2))
  4455. (match* (t1 t2)
  4456. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  4457. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  4458. [(other wise) ((super type-check-exp env) e)])]
  4459. ...
  4460. )))
  4461. \end{lstlisting}
  4462. \caption{Type checker for the $R_3$ language.}
  4463. \label{fig:typecheck-R3}
  4464. \end{figure}
  4465. \section{Garbage Collection}
  4466. \label{sec:GC}
  4467. Here we study a relatively simple algorithm for garbage collection
  4468. that is the basis of state-of-the-art garbage
  4469. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4470. particular, we describe a two-space copying
  4471. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4472. perform the
  4473. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4474. coarse-grained depiction of what happens in a two-space collector,
  4475. showing two time steps, prior to garbage collection on the top and
  4476. after garbage collection on the bottom. In a two-space collector, the
  4477. heap is divided into two parts, the FromSpace and the
  4478. ToSpace. Initially, all allocations go to the FromSpace until there is
  4479. not enough room for the next allocation request. At that point, the
  4480. garbage collector goes to work to make more room.
  4481. The garbage collector must be careful not to reclaim tuples that will
  4482. be used by the program in the future. Of course, it is impossible in
  4483. general to predict what a program will do, but we can over approximate
  4484. the will-be-used tuples by preserving all tuples that could be
  4485. accessed by \emph{any} program given the current computer state. A
  4486. program could access any tuple whose address is in a register or on
  4487. the procedure call stack. These addresses are called the \emph{root
  4488. set}. In addition, a program could access any tuple that is
  4489. transitively reachable from the root set. Thus, it is safe for the
  4490. garbage collector to reclaim the tuples that are not reachable in this
  4491. way.
  4492. So the goal of the garbage collector is twofold:
  4493. \begin{enumerate}
  4494. \item preserve all tuple that are reachable from the root set via a
  4495. path of pointers, that is, the \emph{live} tuples, and
  4496. \item reclaim the memory of everything else, that is, the
  4497. \emph{garbage}.
  4498. \end{enumerate}
  4499. A copying collector accomplishes this by copying all of the live
  4500. objects from the FromSpace into the ToSpace and then performs a slight
  4501. of hand, treating the ToSpace as the new FromSpace and the old
  4502. FromSpace as the new ToSpace. In the example of
  4503. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4504. root set, one in a register and two on the stack. All of the live
  4505. objects have been copied to the ToSpace (the right-hand side of
  4506. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4507. pointer relationships. For example, the pointer in the register still
  4508. points to a 2-tuple whose first element is a 3-tuple and second
  4509. element is a 2-tuple. There are four tuples that are not reachable
  4510. from the root set and therefore do not get copied into the ToSpace.
  4511. (The situation in Figure~\ref{fig:copying-collector}, with a
  4512. cycle, cannot be created by a well-typed program in $R_3$. However,
  4513. creating cycles will be possible once we get to $R_6$. We design
  4514. the garbage collector to deal with cycles to begin with, so we will
  4515. not need to revisit this issue.)
  4516. \begin{figure}[tbp]
  4517. \centering
  4518. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4519. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4520. \caption{A copying collector in action.}
  4521. \label{fig:copying-collector}
  4522. \end{figure}
  4523. There are many alternatives to copying collectors (and their older
  4524. siblings, the generational collectors) when its comes to garbage
  4525. collection, such as mark-and-sweep and reference counting. The
  4526. strengths of copying collectors are that allocation is fast (just a
  4527. test and pointer increment), there is no fragmentation, cyclic garbage
  4528. is collected, and the time complexity of collection only depends on
  4529. the amount of live data, and not on the amount of
  4530. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4531. copying collectors is that they use a lot of space, though that
  4532. problem is ameliorated in generational collectors. Racket and Scheme
  4533. programs tend to allocate many small objects and generate a lot of
  4534. garbage, so copying and generational collectors are a good fit. Of
  4535. course, garbage collection is an active research topic, especially
  4536. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4537. continuously developing new techniques and revisiting old
  4538. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4539. \subsection{Graph Copying via Cheney's Algorithm}
  4540. \label{sec:cheney}
  4541. Let us take a closer look at how the copy works. The allocated objects
  4542. and pointers can be viewed as a graph and we need to copy the part of
  4543. the graph that is reachable from the root set. To make sure we copy
  4544. all of the reachable vertices in the graph, we need an exhaustive
  4545. graph traversal algorithm, such as depth-first search or breadth-first
  4546. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4547. take into account the possibility of cycles by marking which vertices
  4548. have already been visited, so as to ensure termination of the
  4549. algorithm. These search algorithms also use a data structure such as a
  4550. stack or queue as a to-do list to keep track of the vertices that need
  4551. to be visited. We shall use breadth-first search and a trick due to
  4552. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4553. copying tuples into the ToSpace.
  4554. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4555. copy progresses. The queue is represented by a chunk of contiguous
  4556. memory at the beginning of the ToSpace, using two pointers to track
  4557. the front and the back of the queue. The algorithm starts by copying
  4558. all tuples that are immediately reachable from the root set into the
  4559. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4560. old tuple to indicate that it has been visited. (We discuss the
  4561. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4562. inside the copied tuples in the queue still point back to the
  4563. FromSpace. Once the initial queue has been created, the algorithm
  4564. enters a loop in which it repeatedly processes the tuple at the front
  4565. of the queue and pops it off the queue. To process a tuple, the
  4566. algorithm copies all the tuple that are directly reachable from it to
  4567. the ToSpace, placing them at the back of the queue. The algorithm then
  4568. updates the pointers in the popped tuple so they point to the newly
  4569. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4570. step we copy the tuple whose second element is $42$ to the back of the
  4571. queue. The other pointer goes to a tuple that has already been copied,
  4572. so we do not need to copy it again, but we do need to update the
  4573. pointer to the new location. This can be accomplished by storing a
  4574. \emph{forwarding} pointer to the new location in the old tuple, back
  4575. when we initially copied the tuple into the ToSpace. This completes
  4576. one step of the algorithm. The algorithm continues in this way until
  4577. the front of the queue is empty, that is, until the front catches up
  4578. with the back.
  4579. \begin{figure}[tbp]
  4580. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4581. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4582. \label{fig:cheney}
  4583. \end{figure}
  4584. \subsection{Data Representation}
  4585. \label{sec:data-rep-gc}
  4586. The garbage collector places some requirements on the data
  4587. representations used by our compiler. First, the garbage collector
  4588. needs to distinguish between pointers and other kinds of data. There
  4589. are several ways to accomplish this.
  4590. \begin{enumerate}
  4591. \item Attached a tag to each object that identifies what type of
  4592. object it is~\citep{McCarthy:1960dz}.
  4593. \item Store different types of objects in different
  4594. regions~\citep{Steele:1977ab}.
  4595. \item Use type information from the program to either generate
  4596. type-specific code for collecting or to generate tables that can
  4597. guide the
  4598. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4599. \end{enumerate}
  4600. Dynamically typed languages, such as Lisp, need to tag objects
  4601. anyways, so option 1 is a natural choice for those languages.
  4602. However, $R_3$ is a statically typed language, so it would be
  4603. unfortunate to require tags on every object, especially small and
  4604. pervasive objects like integers and Booleans. Option 3 is the
  4605. best-performing choice for statically typed languages, but comes with
  4606. a relatively high implementation complexity. To keep this chapter to a
  4607. 2-week time budget, we recommend a combination of options 1 and 2,
  4608. with separate strategies used for the stack and the heap.
  4609. Regarding the stack, we recommend using a separate stack for
  4610. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4611. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4612. local variable needs to be spilled and is of type \code{(Vector
  4613. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4614. of the normal procedure call stack. Furthermore, we always spill
  4615. vector-typed variables if they are live during a call to the
  4616. collector, thereby ensuring that no pointers are in registers during a
  4617. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4618. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4619. layout using a root stack. The root stack contains the two pointers
  4620. from the regular stack and also the pointer in the second
  4621. register.
  4622. \begin{figure}[tbp]
  4623. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4624. \caption{Maintaining a root stack to facilitate garbage collection.}
  4625. \label{fig:shadow-stack}
  4626. \end{figure}
  4627. The problem of distinguishing between pointers and other kinds of data
  4628. also arises inside of each tuple. We solve this problem by attaching a
  4629. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4630. in on the tags for two of the tuples in the example from
  4631. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4632. in a big-endian way, from right-to-left, with bit location 0 (the
  4633. least significant bit) on the far right, which corresponds to the
  4634. directional of the x86 shifting instructions \key{salq} (shift
  4635. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4636. specifying which elements of the tuple are pointers, the part labeled
  4637. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4638. a pointer and a 0 bit indicates some other kind of data. The pointer
  4639. mask starts at bit location 7. We have limited tuples to a maximum
  4640. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4641. tag also contains two other pieces of information. The length of the
  4642. tuple (number of elements) is stored in bits location 1 through
  4643. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4644. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4645. has not yet been copied. If the bit has value 0 then the entire tag
  4646. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4647. always zero anyways because our tuples are 8-byte aligned.)
  4648. \begin{figure}[tbp]
  4649. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4650. \caption{Representation for tuples in the heap.}
  4651. \label{fig:tuple-rep}
  4652. \end{figure}
  4653. \subsection{Implementation of the Garbage Collector}
  4654. \label{sec:organize-gz}
  4655. The implementation of the garbage collector needs to do a lot of
  4656. bit-level data manipulation and we need to link it with our
  4657. compiler-generated x86 code. Thus, we recommend implementing the
  4658. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4659. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4660. interface to the garbage collector. The \code{initialize} function
  4661. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4662. function is meant to be called near the beginning of \code{main},
  4663. before the rest of the program executes. The \code{initialize}
  4664. function puts the address of the beginning of the FromSpace into the
  4665. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4666. points to the address that is 1-past the last element of the
  4667. FromSpace. (We use half-open intervals to represent chunks of
  4668. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4669. points to the first element of the root stack.
  4670. As long as there is room left in the FromSpace, your generated code
  4671. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4672. %
  4673. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4674. --Jeremy}
  4675. %
  4676. The amount of room left in FromSpace is the difference between the
  4677. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4678. function should be called when there is not enough room left in the
  4679. FromSpace for the next allocation. The \code{collect} function takes
  4680. a pointer to the current top of the root stack (one past the last item
  4681. that was pushed) and the number of bytes that need to be
  4682. allocated. The \code{collect} function performs the copying collection
  4683. and leaves the heap in a state such that the next allocation will
  4684. succeed.
  4685. \begin{figure}[tbp]
  4686. \begin{lstlisting}
  4687. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4688. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4689. int64_t* free_ptr;
  4690. int64_t* fromspace_begin;
  4691. int64_t* fromspace_end;
  4692. int64_t** rootstack_begin;
  4693. \end{lstlisting}
  4694. \caption{The compiler's interface to the garbage collector.}
  4695. \label{fig:gc-header}
  4696. \end{figure}
  4697. \begin{exercise}
  4698. In the file \code{runtime.c} you will find the implementation of
  4699. \code{initialize} and a partial implementation of \code{collect}.
  4700. The \code{collect} function calls another function, \code{cheney},
  4701. to perform the actual copy, and that function is left to the reader
  4702. to implement. The following is the prototype for \code{cheney}.
  4703. \begin{lstlisting}
  4704. static void cheney(int64_t** rootstack_ptr);
  4705. \end{lstlisting}
  4706. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4707. rootstack (which is an array of pointers). The \code{cheney} function
  4708. also communicates with \code{collect} through the global
  4709. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4710. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4711. the ToSpace:
  4712. \begin{lstlisting}
  4713. static int64_t* tospace_begin;
  4714. static int64_t* tospace_end;
  4715. \end{lstlisting}
  4716. The job of the \code{cheney} function is to copy all the live
  4717. objects (reachable from the root stack) into the ToSpace, update
  4718. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4719. update the root stack so that it points to the objects in the
  4720. ToSpace, and finally to swap the global pointers for the FromSpace
  4721. and ToSpace.
  4722. \end{exercise}
  4723. %% \section{Compiler Passes}
  4724. %% \label{sec:code-generation-gc}
  4725. The introduction of garbage collection has a non-trivial impact on our
  4726. compiler passes. We introduce one new compiler pass called
  4727. \code{expose-allocation} and make non-trivial changes to
  4728. \code{type-check}, \code{flatten}, \code{select-instructions},
  4729. \code{allocate-registers}, and \code{print-x86}. The following
  4730. program will serve as our running example. It creates two tuples, one
  4731. nested inside the other. Both tuples have length one. The example then
  4732. accesses the element in the inner tuple tuple via two vector
  4733. references.
  4734. % tests/s2_17.rkt
  4735. \begin{lstlisting}
  4736. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4737. \end{lstlisting}
  4738. Next we proceed to discuss the new \code{expose-allocation} pass.
  4739. \section{Expose Allocation}
  4740. \label{sec:expose-allocation}
  4741. The pass \code{expose-allocation} lowers the \code{vector} creation
  4742. form into a conditional call to the collector followed by the
  4743. allocation. We choose to place the \code{expose-allocation} pass
  4744. before \code{flatten} because \code{expose-allocation} introduces new
  4745. variables, which can be done locally with \code{let}, but \code{let}
  4746. is gone after \code{flatten}. In the following, we show the
  4747. transformation for the \code{vector} form into let-bindings for the
  4748. initializing expressions, by a conditional \code{collect}, an
  4749. \code{allocate}, and the initialization of the vector.
  4750. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4751. total bytes need to be allocated for the vector, which is 8 for the
  4752. tag plus \itm{len} times 8.)
  4753. \begin{lstlisting}
  4754. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4755. |$\Longrightarrow$|
  4756. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4757. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4758. (global-value fromspace_end))
  4759. (void)
  4760. (collect |\itm{bytes}|))])
  4761. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4762. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4763. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4764. |$v$|) ... )))) ...)
  4765. \end{lstlisting}
  4766. (In the above, we suppressed all of the \code{has-type} forms in the
  4767. output for the sake of readability.) The placement of the initializing
  4768. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4769. the sequence of \code{vector-set!}'s is important, as those expressions
  4770. may trigger garbage collection and we do not want an allocated but
  4771. uninitialized tuple to be present during a garbage collection.
  4772. The output of \code{expose-allocation} is a language that extends
  4773. $R_3$ with the three new forms that we use above in the translation of
  4774. \code{vector}.
  4775. \[
  4776. \begin{array}{lcl}
  4777. \Exp &::=& \cdots
  4778. \mid (\key{collect} \,\itm{int})
  4779. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4780. \mid (\key{global-value} \,\itm{name})
  4781. \end{array}
  4782. \]
  4783. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4784. %% the beginning of the program which will instruct the garbage collector
  4785. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4786. %% two arguments of \code{initialize} specify the initial allocated space
  4787. %% for the root stack and for the heap.
  4788. %
  4789. %% The \code{expose-allocation} pass annotates all of the local variables
  4790. %% in the \code{program} form with their type.
  4791. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4792. \code{expose-allocation} pass on our running example.
  4793. \begin{figure}[tbp]
  4794. \begin{lstlisting}
  4795. (program ()
  4796. (vector-ref
  4797. (vector-ref
  4798. (let ((vecinit48
  4799. (let ((vecinit44 42))
  4800. (let ((collectret46
  4801. (if (<
  4802. (+ (global-value free_ptr) 16)
  4803. (global-value fromspace_end))
  4804. (void)
  4805. (collect 16))))
  4806. (let ((alloc43 (allocate 1 (Vector Integer))))
  4807. (let ((initret45 (vector-set! alloc43 0 vecinit44)))
  4808. alloc43))))))
  4809. (let ((collectret50
  4810. (if (< (+ (global-value free_ptr) 16)
  4811. (global-value fromspace_end))
  4812. (void)
  4813. (collect 16))))
  4814. (let ((alloc47 (allocate 1 (Vector (Vector Integer)))))
  4815. (let ((initret49 (vector-set! alloc47 0 vecinit48)))
  4816. alloc47))))
  4817. 0)
  4818. 0))
  4819. \end{lstlisting}
  4820. \caption{Output of the \code{expose-allocation} pass, minus
  4821. all of the \code{has-type} forms.}
  4822. \label{fig:expose-alloc-output}
  4823. \end{figure}
  4824. %\clearpage
  4825. \section{Explicate Control and the $C_2$ language}
  4826. \label{sec:explicate-control-r3}
  4827. \begin{figure}[tp]
  4828. \fbox{
  4829. \begin{minipage}{0.96\textwidth}
  4830. \[
  4831. \begin{array}{lcl}
  4832. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4833. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4834. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4835. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4836. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4837. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4838. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4839. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4840. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4841. \mid (\key{collect} \,\itm{int}) \\
  4842. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4843. &\mid& \gray{(\key{goto}\,\itm{label})
  4844. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4845. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4846. \end{array}
  4847. \]
  4848. \end{minipage}
  4849. }
  4850. \caption{The $C_2$ language, extending $C_1$
  4851. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4852. \label{fig:c2-syntax}
  4853. \end{figure}
  4854. The output of \code{explicate-control} is a program in the
  4855. intermediate language $C_2$, whose syntax is defined in
  4856. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4857. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4858. \key{global-value} expressions and the \code{collect} statement. The
  4859. \code{explicate-control} pass can treat these new forms much like the
  4860. other forms.
  4861. \section{Uncover Locals}
  4862. \label{sec:uncover-locals-r3}
  4863. Recall that the \code{uncover-locals} function collects all of the
  4864. local variables so that it can store them in the $\itm{info}$ field of
  4865. the \code{program} form. Also recall that we need to know the types of
  4866. all the local variables for purposes of identifying the root set for
  4867. the garbage collector. Thus, we change \code{uncover-locals} to
  4868. collect not just the variables, but the variables and their types in
  4869. the form of an association list. Thanks to the \code{has-type} forms,
  4870. the types are readily available. Figure~\ref{fig:uncover-locals-r3}
  4871. lists the output of the \code{uncover-locals} pass on the running
  4872. example.
  4873. \begin{figure}[tbp]
  4874. \begin{lstlisting}
  4875. (program
  4876. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4877. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4878. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4879. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4880. (tmp52 . Integer) (tmp57 . (Vector Integer))
  4881. (vecinit44 . Integer) (tmp56 . Integer) (initret49 . Void)
  4882. (collectret50 . Void))))
  4883. ((block63 . (seq (collect 16) (goto block61)))
  4884. (block62 . (seq (assign collectret46 (void)) (goto block61)))
  4885. (block61 . (seq (assign alloc43 (allocate 1 (Vector Integer)))
  4886. (seq (assign initret45 (vector-set! alloc43 0 vecinit44))
  4887. (seq (assign vecinit48 alloc43)
  4888. (seq (assign tmp54 (global-value free_ptr))
  4889. (seq (assign tmp55 (+ tmp54 16))
  4890. (seq (assign tmp56 (global-value fromspace_end))
  4891. (if (< tmp55 tmp56) (goto block59) (goto block60)))))))))
  4892. (block60 . (seq (collect 16) (goto block58)))
  4893. (block59 . (seq (assign collectret50 (void)) (goto block58)))
  4894. (block58 . (seq (assign alloc47 (allocate 1 (Vector (Vector Integer))))
  4895. (seq (assign initret49 (vector-set! alloc47 0 vecinit48))
  4896. (seq (assign tmp57 (vector-ref alloc47 0))
  4897. (return (vector-ref tmp57 0))))))
  4898. (start . (seq (assign vecinit44 42)
  4899. (seq (assign tmp51 (global-value free_ptr))
  4900. (seq (assign tmp52 (+ tmp51 16))
  4901. (seq (assign tmp53 (global-value fromspace_end))
  4902. (if (< tmp52 tmp53) (goto block62) (goto block63)))))))))
  4903. \end{lstlisting}
  4904. \caption{Output of \code{uncover-locals} for the running example.}
  4905. \label{fig:uncover-locals-r3}
  4906. \end{figure}
  4907. \clearpage
  4908. \section{Select Instructions}
  4909. \label{sec:select-instructions-gc}
  4910. %% void (rep as zero)
  4911. %% allocate
  4912. %% collect (callq collect)
  4913. %% vector-ref
  4914. %% vector-set!
  4915. %% global-value (postpone)
  4916. In this pass we generate x86 code for most of the new operations that
  4917. were needed to compile tuples, including \code{allocate},
  4918. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4919. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4920. The \code{vector-ref} and \code{vector-set!} forms translate into
  4921. \code{movq} instructions with the appropriate \key{deref}. (The
  4922. plus one is to get past the tag at the beginning of the tuple
  4923. representation.)
  4924. \begin{lstlisting}
  4925. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4926. |$\Longrightarrow$|
  4927. (movq |$\itm{vec}'$| (reg r11))
  4928. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4929. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4930. |$\Longrightarrow$|
  4931. (movq |$\itm{vec}'$| (reg r11))
  4932. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4933. (movq (int 0) |$\itm{lhs}$|)
  4934. \end{lstlisting}
  4935. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4936. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4937. register \code{r11} ensures that offsets are only performed with
  4938. register operands. This requires removing \code{r11} from
  4939. consideration by the register allocating.
  4940. We compile the \code{allocate} form to operations on the
  4941. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4942. is the next free address in the FromSpace, so we move it into the
  4943. \itm{lhs} and then move it forward by enough space for the tuple being
  4944. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4945. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4946. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4947. how the tag is organized. We recommend using the Racket operations
  4948. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4949. The type annotation in the \code{vector} form is used to determine the
  4950. pointer mask region of the tag.
  4951. \begin{lstlisting}
  4952. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4953. |$\Longrightarrow$|
  4954. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4955. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4956. (movq |$\itm{lhs}'$| (reg r11))
  4957. (movq (int |$\itm{tag}$|) (deref r11 0))
  4958. \end{lstlisting}
  4959. The \code{collect} form is compiled to a call to the \code{collect}
  4960. function in the runtime. The arguments to \code{collect} are the top
  4961. of the root stack and the number of bytes that need to be allocated.
  4962. We shall use a dedicated register, \code{r15}, to store the pointer to
  4963. the top of the root stack. So \code{r15} is not available for use by
  4964. the register allocator.
  4965. \begin{lstlisting}
  4966. (collect |$\itm{bytes}$|)
  4967. |$\Longrightarrow$|
  4968. (movq (reg r15) (reg rdi))
  4969. (movq |\itm{bytes}| (reg rsi))
  4970. (callq collect)
  4971. \end{lstlisting}
  4972. \begin{figure}[tp]
  4973. \fbox{
  4974. \begin{minipage}{0.96\textwidth}
  4975. \[
  4976. \begin{array}{lcl}
  4977. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  4978. \mid (\key{deref}\,\Reg\,\Int) } \\
  4979. &\mid& \gray{ (\key{byte-reg}\; \Reg) }
  4980. \mid (\key{global-value}\; \itm{name}) \\
  4981. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4982. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4983. (\key{subq} \; \Arg\; \Arg) \mid
  4984. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4985. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4986. (\key{pushq}\;\Arg) \mid
  4987. (\key{popq}\;\Arg) \mid
  4988. (\key{retq})} \\
  4989. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4990. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4991. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4992. \mid (\key{jmp} \; \itm{label})
  4993. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  4994. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  4995. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4996. \end{array}
  4997. \]
  4998. \end{minipage}
  4999. }
  5000. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5001. \label{fig:x86-2}
  5002. \end{figure}
  5003. The syntax of the $x86_2$ language is defined in
  5004. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  5005. of the form for global variables.
  5006. %
  5007. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5008. \code{select-instructions} pass on the running example.
  5009. \begin{figure}[tbp]
  5010. \centering
  5011. \begin{minipage}{0.75\textwidth}
  5012. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5013. (program
  5014. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  5015. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  5016. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  5017. (collectret46 . Void) (vecinit48 . (Vector Integer))
  5018. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  5019. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  5020. ((block63 . (block ()
  5021. (movq (reg r15) (reg rdi))
  5022. (movq (int 16) (reg rsi))
  5023. (callq collect)
  5024. (jmp block61)))
  5025. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  5026. (block61 . (block ()
  5027. (movq (global-value free_ptr) (var alloc43))
  5028. (addq (int 16) (global-value free_ptr))
  5029. (movq (var alloc43) (reg r11))
  5030. (movq (int 3) (deref r11 0))
  5031. (movq (var alloc43) (reg r11))
  5032. (movq (var vecinit44) (deref r11 8))
  5033. (movq (int 0) (var initret45))
  5034. (movq (var alloc43) (var vecinit48))
  5035. (movq (global-value free_ptr) (var tmp54))
  5036. (movq (var tmp54) (var tmp55))
  5037. (addq (int 16) (var tmp55))
  5038. (movq (global-value fromspace_end) (var tmp56))
  5039. (cmpq (var tmp56) (var tmp55))
  5040. (jmp-if l block59)
  5041. (jmp block60)))
  5042. (block60 . (block ()
  5043. (movq (reg r15) (reg rdi))
  5044. (movq (int 16) (reg rsi))
  5045. (callq collect)
  5046. (jmp block58))
  5047. (block59 . (block ()
  5048. (movq (int 0) (var collectret50))
  5049. (jmp block58)))
  5050. (block58 . (block ()
  5051. (movq (global-value free_ptr) (var alloc47))
  5052. (addq (int 16) (global-value free_ptr))
  5053. (movq (var alloc47) (reg r11))
  5054. (movq (int 131) (deref r11 0))
  5055. (movq (var alloc47) (reg r11))
  5056. (movq (var vecinit48) (deref r11 8))
  5057. (movq (int 0) (var initret49))
  5058. (movq (var alloc47) (reg r11))
  5059. (movq (deref r11 8) (var tmp57))
  5060. (movq (var tmp57) (reg r11))
  5061. (movq (deref r11 8) (reg rax))
  5062. (jmp conclusion)))
  5063. (start . (block ()
  5064. (movq (int 42) (var vecinit44))
  5065. (movq (global-value free_ptr) (var tmp51))
  5066. (movq (var tmp51) (var tmp52))
  5067. (addq (int 16) (var tmp52))
  5068. (movq (global-value fromspace_end) (var tmp53))
  5069. (cmpq (var tmp53) (var tmp52))
  5070. (jmp-if l block62)
  5071. (jmp block63))))))
  5072. \end{lstlisting}
  5073. \end{minipage}
  5074. \caption{Output of the \code{select-instructions} pass.}
  5075. \label{fig:select-instr-output-gc}
  5076. \end{figure}
  5077. \clearpage
  5078. \section{Register Allocation}
  5079. \label{sec:reg-alloc-gc}
  5080. As discussed earlier in this chapter, the garbage collector needs to
  5081. access all the pointers in the root set, that is, all variables that
  5082. are vectors. It will be the responsibility of the register allocator
  5083. to make sure that:
  5084. \begin{enumerate}
  5085. \item the root stack is used for spilling vector-typed variables, and
  5086. \item if a vector-typed variable is live during a call to the
  5087. collector, it must be spilled to ensure it is visible to the
  5088. collector.
  5089. \end{enumerate}
  5090. The later responsibility can be handled during construction of the
  5091. inference graph, by adding interference edges between the call-live
  5092. vector-typed variables and all the callee-saved registers. (They
  5093. already interfere with the caller-saved registers.) The type
  5094. information for variables is in the \code{program} form, so we
  5095. recommend adding another parameter to the \code{build-interference}
  5096. function to communicate this association list.
  5097. The spilling of vector-typed variables to the root stack can be
  5098. handled after graph coloring, when choosing how to assign the colors
  5099. (integers) to registers and stack locations. The \code{program} output
  5100. of this pass changes to also record the number of spills to the root
  5101. stack.
  5102. % build-interference
  5103. %
  5104. % callq
  5105. % extra parameter for var->type assoc. list
  5106. % update 'program' and 'if'
  5107. % allocate-registers
  5108. % allocate spilled vectors to the rootstack
  5109. % don't change color-graph
  5110. \section{Print x86}
  5111. \label{sec:print-x86-gc}
  5112. \margincomment{\scriptsize We need to show the translation to x86 and what
  5113. to do about global-value. \\ --Jeremy}
  5114. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5115. \code{print-x86} pass on the running example. In the prelude and
  5116. conclusion of the \code{main} function, we treat the root stack very
  5117. much like the regular stack in that we move the root stack pointer
  5118. (\code{r15}) to make room for all of the spills to the root stack,
  5119. except that the root stack grows up instead of down. For the running
  5120. example, there was just one spill so we increment \code{r15} by 8
  5121. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5122. One issue that deserves special care is that there may be a call to
  5123. \code{collect} prior to the initializing assignments for all the
  5124. variables in the root stack. We do not want the garbage collector to
  5125. accidentally think that some uninitialized variable is a pointer that
  5126. needs to be followed. Thus, we zero-out all locations on the root
  5127. stack in the prelude of \code{main}. In
  5128. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5129. %
  5130. \lstinline{movq $0, (%r15)}
  5131. %
  5132. accomplishes this task. The garbage collector tests each root to see
  5133. if it is null prior to dereferencing it.
  5134. \begin{figure}[htbp]
  5135. \begin{minipage}[t]{0.5\textwidth}
  5136. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5137. _block58:
  5138. movq _free_ptr(%rip), %rcx
  5139. addq $16, _free_ptr(%rip)
  5140. movq %rcx, %r11
  5141. movq $131, 0(%r11)
  5142. movq %rcx, %r11
  5143. movq -8(%r15), %rax
  5144. movq %rax, 8(%r11)
  5145. movq $0, %rdx
  5146. movq %rcx, %r11
  5147. movq 8(%r11), %rcx
  5148. movq %rcx, %r11
  5149. movq 8(%r11), %rax
  5150. jmp _conclusion
  5151. _block59:
  5152. movq $0, %rcx
  5153. jmp _block58
  5154. _block62:
  5155. movq $0, %rcx
  5156. jmp _block61
  5157. _block60:
  5158. movq %r15, %rdi
  5159. movq $16, %rsi
  5160. callq _collect
  5161. jmp _block58
  5162. _block63:
  5163. movq %r15, %rdi
  5164. movq $16, %rsi
  5165. callq _collect
  5166. jmp _block61
  5167. _start:
  5168. movq $42, %rbx
  5169. movq _free_ptr(%rip), %rdx
  5170. addq $16, %rdx
  5171. movq _fromspace_end(%rip), %rcx
  5172. cmpq %rcx, %rdx
  5173. jl _block62
  5174. jmp _block63
  5175. \end{lstlisting}
  5176. \end{minipage}
  5177. \begin{minipage}[t]{0.45\textwidth}
  5178. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5179. _block61:
  5180. movq _free_ptr(%rip), %rcx
  5181. addq $16, _free_ptr(%rip)
  5182. movq %rcx, %r11
  5183. movq $3, 0(%r11)
  5184. movq %rcx, %r11
  5185. movq %rbx, 8(%r11)
  5186. movq $0, %rdx
  5187. movq %rcx, -8(%r15)
  5188. movq _free_ptr(%rip), %rcx
  5189. addq $16, %rcx
  5190. movq _fromspace_end(%rip), %rdx
  5191. cmpq %rdx, %rcx
  5192. jl _block59
  5193. jmp _block60
  5194. .globl _main
  5195. _main:
  5196. pushq %rbp
  5197. movq %rsp, %rbp
  5198. pushq %r12
  5199. pushq %rbx
  5200. pushq %r13
  5201. pushq %r14
  5202. subq $0, %rsp
  5203. movq $16384, %rdi
  5204. movq $16, %rsi
  5205. callq _initialize
  5206. movq _rootstack_begin(%rip), %r15
  5207. movq $0, (%r15)
  5208. addq $8, %r15
  5209. jmp _start
  5210. _conclusion:
  5211. subq $8, %r15
  5212. addq $0, %rsp
  5213. popq %r14
  5214. popq %r13
  5215. popq %rbx
  5216. popq %r12
  5217. popq %rbp
  5218. retq
  5219. \end{lstlisting}
  5220. \end{minipage}
  5221. \caption{Output of the \code{print-x86} pass.}
  5222. \label{fig:print-x86-output-gc}
  5223. \end{figure}
  5224. \margincomment{\scriptsize Suggest an implementation strategy
  5225. in which the students first do the code gen and test that
  5226. without GC (just use a big heap), then after that is debugged,
  5227. implement the GC. \\ --Jeremy}
  5228. \begin{figure}[p]
  5229. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5230. \node (R3) at (0,2) {\large $R_3$};
  5231. \node (R3-2) at (3,2) {\large $R_3$};
  5232. \node (R3-3) at (6,2) {\large $R_3$};
  5233. \node (R3-4) at (9,2) {\large $R_3$};
  5234. \node (R3-5) at (12,2) {\large $R_3$};
  5235. \node (C2-4) at (3,0) {\large $C_2$};
  5236. \node (C2-3) at (6,0) {\large $C_2$};
  5237. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5238. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5239. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5240. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5241. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5242. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5243. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5244. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5245. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5246. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5247. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5248. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5249. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5250. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5251. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5252. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5253. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5254. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5255. \end{tikzpicture}
  5256. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5257. \label{fig:R3-passes}
  5258. \end{figure}
  5259. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5260. for the compilation of $R_3$.
  5261. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5262. \chapter{Functions}
  5263. \label{ch:functions}
  5264. This chapter studies the compilation of functions at the level of
  5265. abstraction of the C language. This corresponds to a subset of Typed
  5266. Racket in which only top-level function definitions are allowed. These
  5267. kind of functions are an important stepping stone to implementing
  5268. lexically-scoped functions in the form of \key{lambda} abstractions,
  5269. which is the topic of Chapter~\ref{ch:lambdas}.
  5270. \section{The $R_4$ Language}
  5271. The syntax for function definitions and function application is shown
  5272. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5273. Programs in $R_4$ start with zero or more function definitions. The
  5274. function names from these definitions are in-scope for the entire
  5275. program, including all other function definitions (so the ordering of
  5276. function definitions does not matter). The syntax for function
  5277. application does not include an explicit keyword, which is error prone
  5278. when using \code{match}. To alleviate this problem, we change the
  5279. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5280. during type checking.
  5281. Functions are first-class in the sense that a function pointer is data
  5282. and can be stored in memory or passed as a parameter to another
  5283. function. Thus, we introduce a function type, written
  5284. \begin{lstlisting}
  5285. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5286. \end{lstlisting}
  5287. for a function whose $n$ parameters have the types $\Type_1$ through
  5288. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5289. these functions (with respect to Racket functions) is that they are
  5290. not lexically scoped. That is, the only external entities that can be
  5291. referenced from inside a function body are other globally-defined
  5292. functions. The syntax of $R_4$ prevents functions from being nested
  5293. inside each other.
  5294. \begin{figure}[tp]
  5295. \centering
  5296. \fbox{
  5297. \begin{minipage}{0.96\textwidth}
  5298. \[
  5299. \begin{array}{lcl}
  5300. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5301. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5302. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5303. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5304. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5305. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5306. \mid (\key{and}\;\Exp\;\Exp)
  5307. \mid (\key{or}\;\Exp\;\Exp)
  5308. \mid (\key{not}\;\Exp)} \\
  5309. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5310. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5311. (\key{vector-ref}\;\Exp\;\Int)} \\
  5312. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5313. &\mid& (\Exp \; \Exp^{*}) \\
  5314. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5315. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5316. \end{array}
  5317. \]
  5318. \end{minipage}
  5319. }
  5320. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5321. with functions.}
  5322. \label{fig:r4-syntax}
  5323. \end{figure}
  5324. The program in Figure~\ref{fig:r4-function-example} is a
  5325. representative example of defining and using functions in $R_4$. We
  5326. define a function \code{map-vec} that applies some other function
  5327. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5328. vector containing the results. We also define a function \code{add1}
  5329. that does what its name suggests. The program then applies
  5330. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5331. \code{(vector 1 42)}, from which we return the \code{42}.
  5332. \begin{figure}[tbp]
  5333. \begin{lstlisting}
  5334. (program ()
  5335. (define (map-vec [f : (Integer -> Integer)]
  5336. [v : (Vector Integer Integer)])
  5337. : (Vector Integer Integer)
  5338. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5339. (define (add1 [x : Integer]) : Integer
  5340. (+ x 1))
  5341. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5342. )
  5343. \end{lstlisting}
  5344. \caption{Example of using functions in $R_4$.}
  5345. \label{fig:r4-function-example}
  5346. \end{figure}
  5347. The definitional interpreter for $R_4$ is in
  5348. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5349. responsible for setting up the mutual recursion between the top-level
  5350. function definitions. We use the classic back-patching approach that
  5351. uses mutable variables and makes two passes over the function
  5352. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5353. top-level environment using a mutable cons cell for each function
  5354. definition. Note that the \code{lambda} value for each function is
  5355. incomplete; it does not yet include the environment. Once the
  5356. top-level environment is constructed, we then iterate over it and
  5357. update the \code{lambda} value's to use the top-level environment.
  5358. \begin{figure}[tp]
  5359. \begin{lstlisting}
  5360. (define (interp-exp env)
  5361. (lambda (e)
  5362. (define recur (interp-exp env))
  5363. (match e
  5364. ...
  5365. [`(,fun ,args ...)
  5366. (define arg-vals (for/list ([e args]) (recur e)))
  5367. (define fun-val (recur fun))
  5368. (match fun-val
  5369. [`(lambda (,xs ...) ,body ,fun-env)
  5370. (define new-env (append (map cons xs arg-vals) fun-env))
  5371. ((interp-exp new-env) body)]
  5372. [else (error "interp-exp, expected function, not" fun-val)])]
  5373. [else (error 'interp-exp "unrecognized expression")]
  5374. )))
  5375. (define (interp-def d)
  5376. (match d
  5377. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5378. (mcons f `(lambda ,xs ,body ()))]
  5379. ))
  5380. (define (interp-R4 p)
  5381. (match p
  5382. [`(program ,ds ... ,body)
  5383. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5384. (for/list ([b top-level])
  5385. (set-mcdr! b (match (mcdr b)
  5386. [`(lambda ,xs ,body ())
  5387. `(lambda ,xs ,body ,top-level)])))
  5388. ((interp-exp top-level) body))]
  5389. ))
  5390. \end{lstlisting}
  5391. \caption{Interpreter for the $R_4$ language.}
  5392. \label{fig:interp-R4}
  5393. \end{figure}
  5394. \section{Functions in x86}
  5395. \label{sec:fun-x86}
  5396. \margincomment{\tiny Make sure callee-saved registers are discussed
  5397. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5398. \margincomment{\tiny Talk about the return address on the
  5399. stack and what callq and retq does.\\ --Jeremy }
  5400. The x86 architecture provides a few features to support the
  5401. implementation of functions. We have already seen that x86 provides
  5402. labels so that one can refer to the location of an instruction, as is
  5403. needed for jump instructions. Labels can also be used to mark the
  5404. beginning of the instructions for a function. Going further, we can
  5405. obtain the address of a label by using the \key{leaq} instruction and
  5406. \key{rip}-relative addressing. For example, the following puts the
  5407. address of the \code{add1} label into the \code{rbx} register.
  5408. \begin{lstlisting}
  5409. leaq add1(%rip), %rbx
  5410. \end{lstlisting}
  5411. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5412. instruction for jumping to a function whose location is given by a
  5413. label. Here we instead will be jumping to a function whose location is
  5414. given by an address, that is, we need to make an \emph{indirect
  5415. function call}. The x86 syntax is to give the register name prefixed
  5416. with an asterisk.
  5417. \begin{lstlisting}
  5418. callq *%rbx
  5419. \end{lstlisting}
  5420. \subsection{Calling Conventions}
  5421. The \code{callq} instruction provides partial support for implementing
  5422. functions, but it does not handle (1) parameter passing, (2) saving
  5423. and restoring frames on the procedure call stack, or (3) determining
  5424. how registers are shared by different functions. These issues require
  5425. coordination between the caller and the callee, which is often
  5426. assembly code written by different programmers or generated by
  5427. different compilers. As a result, people have developed
  5428. \emph{conventions} that govern how functions calls are performed.
  5429. Here we shall use the same conventions used by the \code{gcc}
  5430. compiler~\citep{Matz:2013aa}.
  5431. Regarding (1) parameter passing, the convention is to use the
  5432. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5433. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5434. than six arguments, then the convention is to use space on the frame
  5435. of the caller for the rest of the arguments. However, to ease the
  5436. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5437. we shall arrange to never have more than six arguments.
  5438. %
  5439. The register \code{rax} is for the return value of the function.
  5440. Regarding (2) frames and the procedure call stack, the convention is
  5441. that the stack grows down, with each function call using a chunk of
  5442. space called a frame. The caller sets the stack pointer, register
  5443. \code{rsp}, to the last data item in its frame. The callee must not
  5444. change anything in the caller's frame, that is, anything that is at or
  5445. above the stack pointer. The callee is free to use locations that are
  5446. below the stack pointer.
  5447. Regarding (3) the sharing of registers between different functions,
  5448. recall from Section~\ref{sec:calling-conventions} that the registers
  5449. are divided into two groups, the caller-saved registers and the
  5450. callee-saved registers. The caller should assume that all the
  5451. caller-saved registers get overwritten with arbitrary values by the
  5452. callee. Thus, the caller should either 1) not put values that are live
  5453. across a call in caller-saved registers, or 2) save and restore values
  5454. that are live across calls. We shall recommend option 1). On the flip
  5455. side, if the callee wants to use a callee-saved register, the callee
  5456. must save the contents of those registers on their stack frame and
  5457. then put them back prior to returning to the caller. The base
  5458. pointer, register \code{rbp}, is used as a point-of-reference within a
  5459. frame, so that each local variable can be accessed at a fixed offset
  5460. from the base pointer.
  5461. %
  5462. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5463. frames.
  5464. %% If we were to use stack arguments, they would be between the
  5465. %% caller locals and the callee return address.
  5466. \begin{figure}[tbp]
  5467. \centering
  5468. \begin{tabular}{r|r|l|l} \hline
  5469. Caller View & Callee View & Contents & Frame \\ \hline
  5470. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5471. 0(\key{\%rbp}) & & old \key{rbp} \\
  5472. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5473. \ldots & & \ldots \\
  5474. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5475. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5476. \ldots & & \ldots \\
  5477. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5478. %% & & \\
  5479. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5480. %% & \ldots & \ldots \\
  5481. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5482. \hline
  5483. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5484. & 0(\key{\%rbp}) & old \key{rbp} \\
  5485. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5486. & \ldots & \ldots \\
  5487. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5488. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5489. & \ldots & \ldots \\
  5490. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5491. \end{tabular}
  5492. \caption{Memory layout of caller and callee frames.}
  5493. \label{fig:call-frames}
  5494. \end{figure}
  5495. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5496. %% local variables and for storing the values of callee-saved registers
  5497. %% (we shall refer to all of these collectively as ``locals''), and that
  5498. %% at the beginning of a function we move the stack pointer \code{rsp}
  5499. %% down to make room for them.
  5500. %% We recommend storing the local variables
  5501. %% first and then the callee-saved registers, so that the local variables
  5502. %% can be accessed using \code{rbp} the same as before the addition of
  5503. %% functions.
  5504. %% To make additional room for passing arguments, we shall
  5505. %% move the stack pointer even further down. We count how many stack
  5506. %% arguments are needed for each function call that occurs inside the
  5507. %% body of the function and find their maximum. Adding this number to the
  5508. %% number of locals gives us how much the \code{rsp} should be moved at
  5509. %% the beginning of the function. In preparation for a function call, we
  5510. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5511. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5512. %% so on.
  5513. %% Upon calling the function, the stack arguments are retrieved by the
  5514. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5515. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5516. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5517. %% the layout of the caller and callee frames. Notice how important it is
  5518. %% that we correctly compute the maximum number of arguments needed for
  5519. %% function calls; if that number is too small then the arguments and
  5520. %% local variables will smash into each other!
  5521. \subsection{Efficient Tail Calls}
  5522. \label{sec:tail-call}
  5523. In general, the amount of stack space used by a program is determined
  5524. by the longest chain of nested function calls. That is, if function
  5525. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5526. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5527. $n$ can grow quite large in the case of recursive or mutually
  5528. recursive functions. However, in some cases we can arrange to use only
  5529. constant space, i.e. $O(1)$, instead of $O(n)$.
  5530. If a function call is the last action in a function body, then that
  5531. call is said to be a \emph{tail call}. In such situations, the frame
  5532. of the caller is no longer needed, so we can pop the caller's frame
  5533. before making the tail call. With this approach, a recursive function
  5534. that only makes tail calls will only use $O(1)$ stack space.
  5535. Functional languages like Racket typically rely heavily on recursive
  5536. functions, so they typically guarantee that all tail calls will be
  5537. optimized in this way.
  5538. However, some care is needed with regards to argument passing in tail
  5539. calls. As mentioned above, for arguments beyond the sixth, the
  5540. convention is to use space in the caller's frame for passing
  5541. arguments. But here we've popped the caller's frame and can no longer
  5542. use it. Another alternative is to use space in the callee's frame for
  5543. passing arguments. However, this option is also problematic because
  5544. the caller and callee's frame overlap in memory. As we begin to copy
  5545. the arguments from their sources in the caller's frame, the target
  5546. locations in the callee's frame might overlap with the sources for
  5547. later arguments! We solve this problem by not using the stack for
  5548. parameter passing but instead use the heap, as we describe in the
  5549. Section~\ref{sec:limit-functions-r4}.
  5550. As mentioned above, for a tail call we pop the caller's frame prior to
  5551. making the tail call. The instructions for popping a frame are the
  5552. instructions that we usually place in the conclusion of a
  5553. function. Thus, we also need to place such code immediately before
  5554. each tail call. These instructions include restoring the callee-saved
  5555. registers, so it is good that the argument passing registers are all
  5556. caller-saved registers.
  5557. One last note regarding which instruction to use to make the tail
  5558. call. When the callee is finished, it should not return to the current
  5559. function, but it should return to the function that called the current
  5560. one. Thus, the return address that is already on the stack is the
  5561. right one, and we should not use \key{callq} to make the tail call, as
  5562. that would unnecessarily overwrite the return address. Instead we can
  5563. simply use the \key{jmp} instruction. Like the indirect function call,
  5564. we write an indirect jump with a register prefixed with an asterisk.
  5565. We recommend using \code{rax} to hold the jump target because the
  5566. preceding ``conclusion'' overwrites just about everything else.
  5567. \begin{lstlisting}
  5568. jmp *%rax
  5569. \end{lstlisting}
  5570. %% Now that we have a good understanding of functions as they appear in
  5571. %% $R_4$ and the support for functions in x86, we need to plan the
  5572. %% changes to our compiler, that is, do we need any new passes and/or do
  5573. %% we need to change any existing passes? Also, do we need to add new
  5574. %% kinds of AST nodes to any of the intermediate languages?
  5575. \section{Shrink $R_4$}
  5576. \label{sec:shrink-r4}
  5577. The \code{shrink} pass performs a couple minor modifications to the
  5578. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5579. field to each function definition:
  5580. \begin{lstlisting}
  5581. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5582. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5583. \end{lstlisting}
  5584. and introduces an explicit \code{main} function.\\
  5585. \begin{tabular}{lll}
  5586. \begin{minipage}{0.45\textwidth}
  5587. \begin{lstlisting}
  5588. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5589. \end{lstlisting}
  5590. \end{minipage}
  5591. &
  5592. $\Rightarrow$
  5593. &
  5594. \begin{minipage}{0.45\textwidth}
  5595. \begin{lstlisting}
  5596. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5597. \end{lstlisting}
  5598. \end{minipage}
  5599. \end{tabular} \\
  5600. where $\itm{mainDef}$ is
  5601. \begin{lstlisting}
  5602. (define (main) : Integer () |$\Exp'$|)
  5603. \end{lstlisting}
  5604. \section{Reveal Functions}
  5605. \label{sec:reveal-functions-r4}
  5606. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5607. compilation because it conflates the use of function names and local
  5608. variables. This is a problem because we need to compile the use of a
  5609. function name differently than the use of a local variable; we need to
  5610. use \code{leaq} to convert the function name (a label in x86) to an
  5611. address in a register. Thus, it is a good idea to create a new pass
  5612. that changes function references from just a symbol $f$ to
  5613. \code{(fun-ref $f$)}. A good name for this pass is
  5614. \code{reveal-functions} and the output language, $F_1$, is defined in
  5615. Figure~\ref{fig:f1-syntax}.
  5616. \begin{figure}[tp]
  5617. \centering
  5618. \fbox{
  5619. \begin{minipage}{0.96\textwidth}
  5620. \[
  5621. \begin{array}{lcl}
  5622. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5623. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5624. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5625. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5626. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5627. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5628. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5629. (\key{vector-ref}\;\Exp\;\Int)} \\
  5630. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5631. (\key{app}\; \Exp \; \Exp^{*})} \\
  5632. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5633. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5634. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5635. \end{array}
  5636. \]
  5637. \end{minipage}
  5638. }
  5639. \caption{The $F_1$ language, an extension of $R_4$
  5640. (Figure~\ref{fig:r4-syntax}).}
  5641. \label{fig:f1-syntax}
  5642. \end{figure}
  5643. %% Distinguishing between calls in tail position and non-tail position
  5644. %% requires the pass to have some notion of context. We recommend using
  5645. %% two mutually recursive functions, one for processing expressions in
  5646. %% tail position and another for the rest.
  5647. Placing this pass after \code{uniquify} is a good idea, because it
  5648. will make sure that there are no local variables and functions that
  5649. share the same name. On the other hand, \code{reveal-functions} needs
  5650. to come before the \code{explicate-control} pass because that pass
  5651. will help us compile \code{fun-ref} into assignment statements.
  5652. \section{Limit Functions}
  5653. \label{sec:limit-functions-r4}
  5654. This pass transforms functions so that they have at most six
  5655. parameters and transforms all function calls so that they pass at most
  5656. six arguments. A simple strategy for imposing an argument limit of
  5657. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5658. into a vector, making that subsequent vector the $n$th argument.
  5659. \begin{tabular}{lll}
  5660. \begin{minipage}{0.2\textwidth}
  5661. \begin{lstlisting}
  5662. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5663. \end{lstlisting}
  5664. \end{minipage}
  5665. &
  5666. $\Rightarrow$
  5667. &
  5668. \begin{minipage}{0.4\textwidth}
  5669. \begin{lstlisting}
  5670. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5671. \end{lstlisting}
  5672. \end{minipage}
  5673. \end{tabular}
  5674. In the body of the function, all occurrences of the $i$th argument in
  5675. which $i>5$ must be replaced with a \code{vector-ref}.
  5676. \section{Remove Complex Operators and Operands}
  5677. \label{sec:rco-r4}
  5678. The primary decisions to make for this pass is whether to classify
  5679. \code{fun-ref} and \code{app} as either simple or complex
  5680. expressions. Recall that a simple expression will eventually end up as
  5681. just an ``immediate'' argument of an x86 instruction. Function
  5682. application will be translated to a sequence of instructions, so
  5683. \code{app} must be classified as complex expression. Regarding
  5684. \code{fun-ref}, as discussed above, the function label needs to
  5685. be converted to an address using the \code{leaq} instruction. Thus,
  5686. even though \code{fun-ref} seems rather simple, it needs to be
  5687. classified as a complex expression so that we generate an assignment
  5688. statement with a left-hand side that can serve as the target of the
  5689. \code{leaq}.
  5690. \section{Explicate Control and the $C_3$ language}
  5691. \label{sec:explicate-control-r4}
  5692. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5693. \key{explicate-control}. The three mutually recursive functions for
  5694. this pass, for assignment, tail, and predicate contexts, must all be
  5695. updated with cases for \code{fun-ref} and \code{app}. In
  5696. assignment and predicate contexts, \code{app} becomes \code{call},
  5697. whereas in tail position \code{app} becomes \code{tailcall}. We
  5698. recommend defining a new function for processing function definitions.
  5699. This code is similar to the case for \code{program} in $R_3$. The
  5700. top-level \code{explicate-control} function that handles the
  5701. \code{program} form of $R_4$ can then apply this new function to all
  5702. the function definitions.
  5703. \begin{figure}[tp]
  5704. \fbox{
  5705. \begin{minipage}{0.96\textwidth}
  5706. \[
  5707. \begin{array}{lcl}
  5708. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5709. \\
  5710. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5711. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5712. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5713. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5714. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5715. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5716. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5717. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5718. \mid (\key{collect} \,\itm{int}) }\\
  5719. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5720. &\mid& \gray{(\key{goto}\,\itm{label})
  5721. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5722. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5723. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5724. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5725. \end{array}
  5726. \]
  5727. \end{minipage}
  5728. }
  5729. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5730. \label{fig:c3-syntax}
  5731. \end{figure}
  5732. \section{Uncover Locals}
  5733. \label{sec:uncover-locals-r4}
  5734. The function for processing $\Tail$ should be updated with a case for
  5735. \code{tailcall}. We also recommend creating a new function for
  5736. processing function definitions. Each function definition in $C_3$ has
  5737. its own set of local variables, so the code for function definitions
  5738. should be similar to the case for the \code{program} form in $C_2$.
  5739. \section{Select Instructions}
  5740. \label{sec:select-r4}
  5741. The output of select instructions is a program in the x86$_3$
  5742. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5743. \begin{figure}[tp]
  5744. \fbox{
  5745. \begin{minipage}{0.96\textwidth}
  5746. \[
  5747. \begin{array}{lcl}
  5748. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5749. \mid (\key{deref}\,\Reg\,\Int) } \\
  5750. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  5751. \mid (\key{global-value}\; \itm{name}) } \\
  5752. &\mid& (\key{fun-ref}\; \itm{label})\\
  5753. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5754. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5755. (\key{subq} \; \Arg\; \Arg) \mid
  5756. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5757. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5758. (\key{pushq}\;\Arg) \mid
  5759. (\key{popq}\;\Arg) \mid
  5760. (\key{retq}) } \\
  5761. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5762. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5763. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5764. \mid (\key{jmp} \; \itm{label})
  5765. \mid (\key{j}\itm{cc} \; \itm{label})
  5766. \mid (\key{label} \; \itm{label}) } \\
  5767. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5768. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5769. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5770. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5771. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5772. \end{array}
  5773. \]
  5774. \end{minipage}
  5775. }
  5776. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5777. \label{fig:x86-3}
  5778. \end{figure}
  5779. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5780. as follows: \\
  5781. \begin{tabular}{lll}
  5782. \begin{minipage}{0.45\textwidth}
  5783. \begin{lstlisting}
  5784. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5785. \end{lstlisting}
  5786. \end{minipage}
  5787. &
  5788. $\Rightarrow$
  5789. &
  5790. \begin{minipage}{0.4\textwidth}
  5791. \begin{lstlisting}
  5792. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5793. \end{lstlisting}
  5794. \end{minipage}
  5795. \end{tabular} \\
  5796. Regarding function definitions, we need to remove their parameters and
  5797. instead perform parameter passing in terms of the conventions
  5798. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5799. in the argument passing registers, and inside the function we should
  5800. generate a \code{movq} instruction for each parameter, to move the
  5801. argument value from the appropriate register to a new local variable
  5802. with the same name as the old parameter.
  5803. Next, consider the compilation of function calls, which have the
  5804. following form upon input to \code{select-instructions}.
  5805. \begin{lstlisting}
  5806. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5807. \end{lstlisting}
  5808. In the mirror image of handling the parameters of function
  5809. definitions, the arguments \itm{args} need to be moved to the argument
  5810. passing registers.
  5811. %
  5812. Once the instructions for parameter passing have been generated, the
  5813. function call itself can be performed with an indirect function call,
  5814. for which I recommend creating the new instruction
  5815. \code{indirect-callq}. Of course, the return value from the function
  5816. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5817. \begin{lstlisting}
  5818. (indirect-callq |\itm{fun}|)
  5819. (movq (reg rax) |\itm{lhs}|)
  5820. \end{lstlisting}
  5821. Regarding tail calls, the parameter passing is the same as non-tail
  5822. calls: generate instructions to move the arguments into to the
  5823. argument passing registers. After that we need to pop the frame from
  5824. the procedure call stack. However, we do not yet know how big the
  5825. frame is; that gets determined during register allocation. So instead
  5826. of generating those instructions here, we invent a new instruction
  5827. that means ``pop the frame and then do an indirect jump'', which we
  5828. name \code{tail-jmp}.
  5829. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5830. using the label \code{start} for the initial block of a program, and
  5831. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5832. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5833. can be compiled to an assignment to \code{rax} followed by a jump to
  5834. \code{conclusion}. With the addition of function definitions, we will
  5835. have a starting block and conclusion for each function, but their
  5836. labels need to be unique. We recommend prepending the function's name
  5837. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5838. labels. (Alternatively, one could \code{gensym} labels for the start
  5839. and conclusion and store them in the $\itm{info}$ field of the
  5840. function definition.)
  5841. \section{Uncover Live}
  5842. %% The rest of the passes need only minor modifications to handle the new
  5843. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5844. %% \code{leaq}.
  5845. Inside \code{uncover-live}, when computing the $W$ set (written
  5846. variables) for an \code{indirect-callq} instruction, we recommend
  5847. including all the caller-saved registers, which will have the affect
  5848. of making sure that no caller-saved register actually needs to be
  5849. saved.
  5850. \section{Build Interference Graph}
  5851. With the addition of function definitions, we compute an interference
  5852. graph for each function (not just one for the whole program).
  5853. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5854. spill vector-typed variables that are live during a call to the
  5855. \code{collect}. With the addition of functions to our language, we
  5856. need to revisit this issue. Many functions will perform allocation and
  5857. therefore have calls to the collector inside of them. Thus, we should
  5858. not only spill a vector-typed variable when it is live during a call
  5859. to \code{collect}, but we should spill the variable if it is live
  5860. during any function call. Thus, in the \code{build-interference} pass,
  5861. we recommend adding interference edges between call-live vector-typed
  5862. variables and the callee-saved registers (in addition to the usual
  5863. addition of edges between call-live variables and the caller-saved
  5864. registers).
  5865. \section{Patch Instructions}
  5866. In \code{patch-instructions}, you should deal with the x86
  5867. idiosyncrasy that the destination argument of \code{leaq} must be a
  5868. register. Additionally, you should ensure that the argument of
  5869. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5870. code generation more convenient, because we will be trampling many
  5871. registers before the tail call (as explained below).
  5872. \section{Print x86}
  5873. For the \code{print-x86} pass, we recommend the following translations:
  5874. \begin{lstlisting}
  5875. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5876. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5877. \end{lstlisting}
  5878. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5879. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5880. is what we will want to do, but before the jump we need to pop the
  5881. current frame. So we need to restore the state of the registers to the
  5882. point they were at when the current function was called. This
  5883. sequence of instructions is the same as the code for the conclusion of
  5884. a function.
  5885. Note that your \code{print-x86} pass needs to add the code for saving
  5886. and restoring callee-saved registers, if you have not already
  5887. implemented that. This is necessary when generating code for function
  5888. definitions.
  5889. \section{An Example Translation}
  5890. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5891. function in $R_4$ to x86. The figure also includes the results of the
  5892. \code{explicate-control} and \code{select-instructions} passes. We
  5893. have omitted the \code{has-type} AST nodes for readability. Can you
  5894. see any ways to improve the translation?
  5895. \begin{figure}[tbp]
  5896. \begin{tabular}{ll}
  5897. \begin{minipage}{0.45\textwidth}
  5898. % s3_2.rkt
  5899. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5900. (program
  5901. (define (add [x : Integer]
  5902. [y : Integer])
  5903. : Integer (+ x y))
  5904. (add 40 2))
  5905. \end{lstlisting}
  5906. $\Downarrow$
  5907. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5908. (program ()
  5909. (define (add86 [x87 : Integer]
  5910. [y88 : Integer]) : Integer ()
  5911. ((add86start . (return (+ x87 y88)))))
  5912. (define (main) : Integer ()
  5913. ((mainstart .
  5914. (seq (assign tmp89 (fun-ref add86))
  5915. (tailcall tmp89 40 2))))))
  5916. \end{lstlisting}
  5917. \end{minipage}
  5918. &
  5919. $\Rightarrow$
  5920. \begin{minipage}{0.5\textwidth}
  5921. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5922. (program ()
  5923. (define (add86)
  5924. ((locals (x87 . Integer) (y88 . Integer))
  5925. (num-params . 2))
  5926. ((add86start .
  5927. (block ()
  5928. (movq (reg rcx) (var x87))
  5929. (movq (reg rdx) (var y88))
  5930. (movq (var x87) (reg rax))
  5931. (addq (var y88) (reg rax))
  5932. (jmp add86conclusion)))))
  5933. (define (main)
  5934. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5935. (num-params . 0))
  5936. ((mainstart .
  5937. (block ()
  5938. (leaq (fun-ref add86) (var tmp89))
  5939. (movq (int 40) (reg rcx))
  5940. (movq (int 2) (reg rdx))
  5941. (tail-jmp (var tmp89))))))
  5942. \end{lstlisting}
  5943. $\Downarrow$
  5944. \end{minipage}
  5945. \end{tabular}
  5946. \begin{tabular}{lll}
  5947. \begin{minipage}{0.3\textwidth}
  5948. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5949. _add90start:
  5950. movq %rcx, %rsi
  5951. movq %rdx, %rcx
  5952. movq %rsi, %rax
  5953. addq %rcx, %rax
  5954. jmp _add90conclusion
  5955. .globl _add90
  5956. .align 16
  5957. _add90:
  5958. pushq %rbp
  5959. movq %rsp, %rbp
  5960. pushq %r12
  5961. pushq %rbx
  5962. pushq %r13
  5963. pushq %r14
  5964. subq $0, %rsp
  5965. jmp _add90start
  5966. _add90conclusion:
  5967. addq $0, %rsp
  5968. popq %r14
  5969. popq %r13
  5970. popq %rbx
  5971. popq %r12
  5972. subq $0, %r15
  5973. popq %rbp
  5974. retq
  5975. \end{lstlisting}
  5976. \end{minipage}
  5977. &
  5978. \begin{minipage}{0.3\textwidth}
  5979. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5980. _mainstart:
  5981. leaq _add90(%rip), %rsi
  5982. movq $40, %rcx
  5983. movq $2, %rdx
  5984. movq %rsi, %rax
  5985. addq $0, %rsp
  5986. popq %r14
  5987. popq %r13
  5988. popq %rbx
  5989. popq %r12
  5990. subq $0, %r15
  5991. popq %rbp
  5992. jmp *%rax
  5993. .globl _main
  5994. .align 16
  5995. _main:
  5996. pushq %rbp
  5997. movq %rsp, %rbp
  5998. pushq %r12
  5999. pushq %rbx
  6000. pushq %r13
  6001. pushq %r14
  6002. subq $0, %rsp
  6003. movq $16384, %rdi
  6004. movq $16, %rsi
  6005. callq _initialize
  6006. movq _rootstack_begin(%rip), %r15
  6007. jmp _mainstart
  6008. \end{lstlisting}
  6009. \end{minipage}
  6010. &
  6011. \begin{minipage}{0.3\textwidth}
  6012. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6013. _mainconclusion:
  6014. addq $0, %rsp
  6015. popq %r14
  6016. popq %r13
  6017. popq %rbx
  6018. popq %r12
  6019. subq $0, %r15
  6020. popq %rbp
  6021. retq
  6022. \end{lstlisting}
  6023. \end{minipage}
  6024. \end{tabular}
  6025. \caption{Example compilation of a simple function to x86.}
  6026. \label{fig:add-fun}
  6027. \end{figure}
  6028. \begin{exercise}\normalfont
  6029. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6030. Create 5 new programs that use functions, including examples that pass
  6031. functions and return functions from other functions and including
  6032. recursive functions. Test your compiler on these new programs and all
  6033. of your previously created test programs.
  6034. \end{exercise}
  6035. \begin{figure}[p]
  6036. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6037. \node (R4) at (0,2) {\large $R_4$};
  6038. \node (R4-2) at (3,2) {\large $R_4$};
  6039. \node (R4-3) at (6,2) {\large $R_4$};
  6040. \node (F1-1) at (12,0) {\large $F_1$};
  6041. \node (F1-2) at (9,0) {\large $F_1$};
  6042. \node (F1-3) at (6,0) {\large $F_1$};
  6043. \node (F1-4) at (3,0) {\large $F_1$};
  6044. \node (C3-1) at (6,-2) {\large $C_3$};
  6045. \node (C3-2) at (3,-2) {\large $C_3$};
  6046. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6047. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6048. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6049. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6050. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6051. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6052. \path[->,bend left=15] (R4) edge [above] node
  6053. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6054. \path[->,bend left=15] (R4-2) edge [above] node
  6055. {\ttfamily\footnotesize uniquify} (R4-3);
  6056. \path[->,bend left=15] (R4-3) edge [right] node
  6057. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6058. \path[->,bend left=15] (F1-1) edge [below] node
  6059. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6060. \path[->,bend right=15] (F1-2) edge [above] node
  6061. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6062. \path[->,bend right=15] (F1-3) edge [above] node
  6063. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6064. \path[->,bend left=15] (F1-4) edge [right] node
  6065. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6066. \path[->,bend left=15] (C3-1) edge [below] node
  6067. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6068. \path[->,bend right=15] (C3-2) edge [left] node
  6069. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6070. \path[->,bend left=15] (x86-2) edge [left] node
  6071. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6072. \path[->,bend right=15] (x86-2-1) edge [below] node
  6073. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6074. \path[->,bend right=15] (x86-2-2) edge [left] node
  6075. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6076. \path[->,bend left=15] (x86-3) edge [above] node
  6077. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6078. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6079. \end{tikzpicture}
  6080. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6081. \label{fig:R4-passes}
  6082. \end{figure}
  6083. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6084. the compilation of $R_4$.
  6085. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6086. \chapter{Lexically Scoped Functions}
  6087. \label{ch:lambdas}
  6088. This chapter studies lexically scoped functions as they appear in
  6089. functional languages such as Racket. By lexical scoping we mean that a
  6090. function's body may refer to variables whose binding site is outside
  6091. of the function, in an enclosing scope.
  6092. %
  6093. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6094. anonymous function defined using the \key{lambda} form. The body of
  6095. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6096. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6097. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6098. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6099. returned from the function \code{f}. Below the definition of \code{f},
  6100. we have two calls to \code{f} with different arguments for \code{x},
  6101. first \code{5} then \code{3}. The functions returned from \code{f} are
  6102. bound to variables \code{g} and \code{h}. Even though these two
  6103. functions were created by the same \code{lambda}, they are really
  6104. different functions because they use different values for
  6105. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6106. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6107. the result of this program is \code{42}.
  6108. \begin{figure}[btp]
  6109. % s4_6.rkt
  6110. \begin{lstlisting}
  6111. (define (f [x : Integer]) : (Integer -> Integer)
  6112. (let ([y 4])
  6113. (lambda: ([z : Integer]) : Integer
  6114. (+ x (+ y z)))))
  6115. (let ([g (f 5)])
  6116. (let ([h (f 3)])
  6117. (+ (g 11) (h 15))))
  6118. \end{lstlisting}
  6119. \caption{Example of a lexically scoped function.}
  6120. \label{fig:lexical-scoping}
  6121. \end{figure}
  6122. \section{The $R_5$ Language}
  6123. The syntax for this language with anonymous functions and lexical
  6124. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6125. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6126. for function application. In this chapter we shall describe how to
  6127. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6128. into a combination of functions (as in $R_4$) and tuples (as in
  6129. $R_3$).
  6130. \begin{figure}[tp]
  6131. \centering
  6132. \fbox{
  6133. \begin{minipage}{0.96\textwidth}
  6134. \[
  6135. \begin{array}{lcl}
  6136. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6137. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6138. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6139. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6140. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6141. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6142. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6143. \mid (\key{and}\;\Exp\;\Exp)
  6144. \mid (\key{or}\;\Exp\;\Exp)
  6145. \mid (\key{not}\;\Exp) } \\
  6146. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6147. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6148. (\key{vector-ref}\;\Exp\;\Int)} \\
  6149. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6150. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6151. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6152. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6153. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6154. \end{array}
  6155. \]
  6156. \end{minipage}
  6157. }
  6158. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6159. with \key{lambda}.}
  6160. \label{fig:r5-syntax}
  6161. \end{figure}
  6162. To compile lexically-scoped functions to top-level function
  6163. definitions, the compiler will need to provide special treatment to
  6164. variable occurrences such as \code{x} and \code{y} in the body of the
  6165. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6166. of $R_4$ may not refer to variables defined outside the function. To
  6167. identify such variable occurrences, we review the standard notion of
  6168. free variable.
  6169. \begin{definition}
  6170. A variable is \emph{free with respect to an expression} $e$ if the
  6171. variable occurs inside $e$ but does not have an enclosing binding in
  6172. $e$.
  6173. \end{definition}
  6174. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6175. free with respect to the expression \code{(+ x (+ y z))}. On the
  6176. other hand, only \code{x} and \code{y} are free with respect to the
  6177. following expression because \code{z} is bound by the \code{lambda}.
  6178. \begin{lstlisting}
  6179. (lambda: ([z : Integer]) : Integer
  6180. (+ x (+ y z)))
  6181. \end{lstlisting}
  6182. Once we have identified the free variables of a \code{lambda}, we need
  6183. to arrange for some way to transport, at runtime, the values of those
  6184. variables from the point where the \code{lambda} was created to the
  6185. point where the \code{lambda} is applied. Referring again to
  6186. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6187. needs to be used in the application of \code{g} to \code{11}, but the
  6188. binding of \code{x} to \code{3} needs to be used in the application of
  6189. \code{h} to \code{15}. An efficient solution to the problem, due to
  6190. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6191. free variables together with the function pointer for the lambda's
  6192. code, an arrangement called a \emph{flat closure} (which we shorten to
  6193. just ``closure'') . Fortunately, we have all the ingredients to make
  6194. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6195. Chapter~\ref{ch:functions} gave us function pointers. The function
  6196. pointer shall reside at index $0$ and the values for free variables
  6197. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6198. the two closures created by the two calls to \code{f} in
  6199. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6200. the same \key{lambda}, they share the same function pointer but differ
  6201. in the values for the free variable \code{x}.
  6202. \begin{figure}[tbp]
  6203. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6204. \caption{Example closure representation for the \key{lambda}'s
  6205. in Figure~\ref{fig:lexical-scoping}.}
  6206. \label{fig:closures}
  6207. \end{figure}
  6208. \section{Interpreting $R_5$}
  6209. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6210. $R_5$. The clause for \key{lambda} saves the current environment
  6211. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6212. the environment from the \key{lambda}, the \code{lam-env}, when
  6213. interpreting the body of the \key{lambda}. The \code{lam-env}
  6214. environment is extended with the mapping of parameters to argument
  6215. values.
  6216. \begin{figure}[tbp]
  6217. \begin{lstlisting}
  6218. (define (interp-exp env)
  6219. (lambda (e)
  6220. (define recur (interp-exp env))
  6221. (match e
  6222. ...
  6223. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6224. `(lambda ,xs ,body ,env)]
  6225. [`(app ,fun ,args ...)
  6226. (define fun-val ((interp-exp env) fun))
  6227. (define arg-vals (map (interp-exp env) args))
  6228. (match fun-val
  6229. [`(lambda (,xs ...) ,body ,lam-env)
  6230. (define new-env (append (map cons xs arg-vals) lam-env))
  6231. ((interp-exp new-env) body)]
  6232. [else (error "interp-exp, expected function, not" fun-val)])]
  6233. [else (error 'interp-exp "unrecognized expression")]
  6234. )))
  6235. \end{lstlisting}
  6236. \caption{Interpreter for $R_5$.}
  6237. \label{fig:interp-R5}
  6238. \end{figure}
  6239. \section{Type Checking $R_5$}
  6240. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6241. \key{lambda} form. The body of the \key{lambda} is checked in an
  6242. environment that includes the current environment (because it is
  6243. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6244. require the body's type to match the declared return type.
  6245. \begin{figure}[tbp]
  6246. \begin{lstlisting}
  6247. (define (typecheck-R5 env)
  6248. (lambda (e)
  6249. (match e
  6250. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6251. (define new-env (append (map cons xs Ts) env))
  6252. (define bodyT ((typecheck-R5 new-env) body))
  6253. (cond [(equal? rT bodyT)
  6254. `(,@Ts -> ,rT)]
  6255. [else
  6256. (error "mismatch in return type" bodyT rT)])]
  6257. ...
  6258. )))
  6259. \end{lstlisting}
  6260. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6261. \label{fig:typecheck-R5}
  6262. \end{figure}
  6263. \section{Closure Conversion}
  6264. The compiling of lexically-scoped functions into top-level function
  6265. definitions is accomplished in the pass \code{convert-to-closures}
  6266. that comes after \code{reveal-functions} and before
  6267. \code{limit-functions}.
  6268. As usual, we shall implement the pass as a recursive function over the
  6269. AST. All of the action is in the clauses for \key{lambda} and
  6270. \key{app}. We transform a \key{lambda} expression into an expression
  6271. that creates a closure, that is, creates a vector whose first element
  6272. is a function pointer and the rest of the elements are the free
  6273. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6274. generated to identify the function.
  6275. \begin{tabular}{lll}
  6276. \begin{minipage}{0.4\textwidth}
  6277. \begin{lstlisting}
  6278. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6279. \end{lstlisting}
  6280. \end{minipage}
  6281. &
  6282. $\Rightarrow$
  6283. &
  6284. \begin{minipage}{0.4\textwidth}
  6285. \begin{lstlisting}
  6286. (vector |\itm{name}| |\itm{fvs}| ...)
  6287. \end{lstlisting}
  6288. \end{minipage}
  6289. \end{tabular} \\
  6290. %
  6291. In addition to transforming each \key{lambda} into a \key{vector}, we
  6292. must create a top-level function definition for each \key{lambda}, as
  6293. shown below.\\
  6294. \begin{minipage}{0.8\textwidth}
  6295. \begin{lstlisting}
  6296. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6297. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6298. ...
  6299. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6300. |\itm{body'}|)...))
  6301. \end{lstlisting}
  6302. \end{minipage}\\
  6303. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6304. parameters are the normal parameters of the \key{lambda}. The types
  6305. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6306. underscore is a dummy type because it is rather difficult to give a
  6307. type to the function in the closure's type, and it does not matter.
  6308. The sequence of \key{let} forms bind the free variables to their
  6309. values obtained from the closure.
  6310. We transform function application into code that retrieves the
  6311. function pointer from the closure and then calls the function, passing
  6312. in the closure as the first argument. We bind $e'$ to a temporary
  6313. variable to avoid code duplication.
  6314. \begin{tabular}{lll}
  6315. \begin{minipage}{0.3\textwidth}
  6316. \begin{lstlisting}
  6317. (app |$e$| |\itm{es}| ...)
  6318. \end{lstlisting}
  6319. \end{minipage}
  6320. &
  6321. $\Rightarrow$
  6322. &
  6323. \begin{minipage}{0.5\textwidth}
  6324. \begin{lstlisting}
  6325. (let ([|\itm{tmp}| |$e'$|])
  6326. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6327. \end{lstlisting}
  6328. \end{minipage}
  6329. \end{tabular} \\
  6330. There is also the question of what to do with top-level function
  6331. definitions. To maintain a uniform translation of function
  6332. application, we turn function references into closures.
  6333. \begin{tabular}{lll}
  6334. \begin{minipage}{0.3\textwidth}
  6335. \begin{lstlisting}
  6336. (fun-ref |$f$|)
  6337. \end{lstlisting}
  6338. \end{minipage}
  6339. &
  6340. $\Rightarrow$
  6341. &
  6342. \begin{minipage}{0.5\textwidth}
  6343. \begin{lstlisting}
  6344. (vector (fun-ref |$f$|))
  6345. \end{lstlisting}
  6346. \end{minipage}
  6347. \end{tabular} \\
  6348. %
  6349. The top-level function definitions need to be updated as well to take
  6350. an extra closure parameter.
  6351. \section{An Example Translation}
  6352. \label{sec:example-lambda}
  6353. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6354. conversion for the example program demonstrating lexical scoping that
  6355. we discussed at the beginning of this chapter.
  6356. \begin{figure}[h]
  6357. \begin{minipage}{0.8\textwidth}
  6358. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6359. (program
  6360. (define (f [x : Integer]) : (Integer -> Integer)
  6361. (let ([y 4])
  6362. (lambda: ([z : Integer]) : Integer
  6363. (+ x (+ y z)))))
  6364. (let ([g (f 5)])
  6365. (let ([h (f 3)])
  6366. (+ (g 11) (h 15)))))
  6367. \end{lstlisting}
  6368. $\Downarrow$
  6369. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6370. (program (type Integer)
  6371. (define (f (x : Integer)) : (Integer -> Integer)
  6372. (let ((y 4))
  6373. (lambda: ((z : Integer)) : Integer
  6374. (+ x (+ y z)))))
  6375. (let ((g (app (fun-ref f) 5)))
  6376. (let ((h (app (fun-ref f) 3)))
  6377. (+ (app g 11) (app h 15)))))
  6378. \end{lstlisting}
  6379. $\Downarrow$
  6380. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6381. (program (type Integer)
  6382. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6383. (let ((y 4))
  6384. (vector (fun-ref lam.1) x y)))
  6385. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6386. (let ((x (vector-ref clos.2 1)))
  6387. (let ((y (vector-ref clos.2 2)))
  6388. (+ x (+ y z)))))
  6389. (let ((g (let ((t.1 (vector (fun-ref f))))
  6390. (app (vector-ref t.1 0) t.1 5))))
  6391. (let ((h (let ((t.2 (vector (fun-ref f))))
  6392. (app (vector-ref t.2 0) t.2 3))))
  6393. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6394. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6395. \end{lstlisting}
  6396. \end{minipage}
  6397. \caption{Example of closure conversion.}
  6398. \label{fig:lexical-functions-example}
  6399. \end{figure}
  6400. \begin{figure}[p]
  6401. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6402. \node (R4) at (0,2) {\large $R_4$};
  6403. \node (R4-2) at (3,2) {\large $R_4$};
  6404. \node (R4-3) at (6,2) {\large $R_4$};
  6405. \node (F1-1) at (12,0) {\large $F_1$};
  6406. \node (F1-2) at (9,0) {\large $F_1$};
  6407. \node (F1-3) at (6,0) {\large $F_1$};
  6408. \node (F1-4) at (3,0) {\large $F_1$};
  6409. \node (F1-5) at (0,0) {\large $F_1$};
  6410. \node (C3-1) at (6,-2) {\large $C_3$};
  6411. \node (C3-2) at (3,-2) {\large $C_3$};
  6412. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6413. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6414. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6415. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6416. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6417. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6418. \path[->,bend left=15] (R4) edge [above] node
  6419. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6420. \path[->,bend left=15] (R4-2) edge [above] node
  6421. {\ttfamily\footnotesize uniquify} (R4-3);
  6422. \path[->] (R4-3) edge [right] node
  6423. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6424. \path[->,bend left=15] (F1-1) edge [below] node
  6425. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6426. \path[->,bend right=15] (F1-2) edge [above] node
  6427. {\ttfamily\footnotesize limit-functions} (F1-3);
  6428. \path[->,bend right=15] (F1-3) edge [above] node
  6429. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6430. \path[->,bend right=15] (F1-4) edge [above] node
  6431. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6432. \path[->] (F1-5) edge [left] node
  6433. {\ttfamily\footnotesize explicate-control} (C3-1);
  6434. \path[->,bend left=15] (C3-1) edge [below] node
  6435. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6436. \path[->,bend right=15] (C3-2) edge [left] node
  6437. {\ttfamily\footnotesize select-instr.} (x86-2);
  6438. \path[->,bend left=15] (x86-2) edge [left] node
  6439. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6440. \path[->,bend right=15] (x86-2-1) edge [below] node
  6441. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6442. \path[->,bend right=15] (x86-2-2) edge [left] node
  6443. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6444. \path[->,bend left=15] (x86-3) edge [above] node
  6445. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6446. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6447. \end{tikzpicture}
  6448. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6449. functions.}
  6450. \label{fig:R5-passes}
  6451. \end{figure}
  6452. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6453. for the compilation of $R_5$.
  6454. \begin{exercise}\normalfont
  6455. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6456. Create 5 new programs that use \key{lambda} functions and make use of
  6457. lexical scoping. Test your compiler on these new programs and all of
  6458. your previously created test programs.
  6459. \end{exercise}
  6460. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6461. \chapter{Dynamic Typing}
  6462. \label{ch:type-dynamic}
  6463. In this chapter we discuss the compilation of a dynamically typed
  6464. language, named $R_7$, that is a subset of the Racket
  6465. language. (Recall that in the previous chapters we have studied
  6466. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6467. languages, an expression may produce values of differing
  6468. type. Consider the following example with a conditional expression
  6469. that may return a Boolean or an integer depending on the input to the
  6470. program.
  6471. \begin{lstlisting}
  6472. (not (if (eq? (read) 1) #f 0))
  6473. \end{lstlisting}
  6474. Languages that allow expressions to produce different kinds of values
  6475. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6476. such as subtype polymorphism and parametric
  6477. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6478. talking about here does not have a special name, but it is the usual
  6479. kind that arises in dynamically typed languages.
  6480. Another characteristic of dynamically typed languages is that
  6481. primitive operations, such as \code{not}, are often defined to operate
  6482. on many different types of values. In fact, in Racket, the \code{not}
  6483. operator produces a result for any kind of value: given \code{\#f} it
  6484. returns \code{\#t} and given anything else it returns \code{\#f}.
  6485. Furthermore, even when primitive operations restrict their inputs to
  6486. values of a certain type, this restriction is enforced at runtime
  6487. instead of during compilation. For example, the following vector
  6488. reference results in a run-time contract violation.
  6489. \begin{lstlisting}
  6490. (vector-ref (vector 42) #t)
  6491. \end{lstlisting}
  6492. \begin{figure}[tp]
  6493. \centering
  6494. \fbox{
  6495. \begin{minipage}{0.97\textwidth}
  6496. \[
  6497. \begin{array}{rcl}
  6498. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6499. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6500. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6501. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6502. &\mid& \key{\#t} \mid \key{\#f}
  6503. \mid (\key{and}\;\Exp\;\Exp)
  6504. \mid (\key{or}\;\Exp\;\Exp)
  6505. \mid (\key{not}\;\Exp) \\
  6506. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6507. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6508. (\key{vector-ref}\;\Exp\;\Exp) \\
  6509. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6510. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6511. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6512. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6513. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6514. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6515. \end{array}
  6516. \]
  6517. \end{minipage}
  6518. }
  6519. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6520. \label{fig:r7-syntax}
  6521. \end{figure}
  6522. The syntax of $R_7$, our subset of Racket, is defined in
  6523. Figure~\ref{fig:r7-syntax}.
  6524. %
  6525. The definitional interpreter for $R_7$ is given in
  6526. Figure~\ref{fig:interp-R7}.
  6527. \begin{figure}[tbp]
  6528. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6529. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6530. (define (valid-op? op) (member op '(+ - and or not)))
  6531. (define (interp-r7 env)
  6532. (lambda (ast)
  6533. (define recur (interp-r7 env))
  6534. (match ast
  6535. [(? symbol?) (lookup ast env)]
  6536. [(? integer?) `(inject ,ast Integer)]
  6537. [#t `(inject #t Boolean)]
  6538. [#f `(inject #f Boolean)]
  6539. [`(read) `(inject ,(read-fixnum) Integer)]
  6540. [`(lambda (,xs ...) ,body)
  6541. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6542. [`(define (,f ,xs ...) ,body)
  6543. (mcons f `(lambda ,xs ,body))]
  6544. [`(program ,ds ... ,body)
  6545. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6546. (for/list ([b top-level])
  6547. (set-mcdr! b (match (mcdr b)
  6548. [`(lambda ,xs ,body)
  6549. `(inject (lambda ,xs ,body ,top-level)
  6550. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6551. ((interp-r7 top-level) body))]
  6552. [`(vector ,(app recur elts) ...)
  6553. (define tys (map get-tagged-type elts))
  6554. `(inject ,(apply vector elts) (Vector ,@tys))]
  6555. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6556. (match v1
  6557. [`(inject ,vec ,ty)
  6558. (vector-set! vec n v2)
  6559. `(inject (void) Void)])]
  6560. [`(vector-ref ,(app recur v) ,n)
  6561. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6562. [`(let ([,x ,(app recur v)]) ,body)
  6563. ((interp-r7 (cons (cons x v) env)) body)]
  6564. [`(,op ,es ...) #:when (valid-op? op)
  6565. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6566. [`(eq? ,(app recur l) ,(app recur r))
  6567. `(inject ,(equal? l r) Boolean)]
  6568. [`(if ,(app recur q) ,t ,f)
  6569. (match q
  6570. [`(inject #f Boolean) (recur f)]
  6571. [else (recur t)])]
  6572. [`(,(app recur f-val) ,(app recur vs) ...)
  6573. (match f-val
  6574. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6575. (define new-env (append (map cons xs vs) lam-env))
  6576. ((interp-r7 new-env) body)]
  6577. [else (error "interp-r7, expected function, not" f-val)])])))
  6578. \end{lstlisting}
  6579. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6580. \label{fig:interp-R7}
  6581. \end{figure}
  6582. Let us consider how we might compile $R_7$ to x86, thinking about the
  6583. first example above. Our bit-level representation of the Boolean
  6584. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6585. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6586. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6587. general, cannot be determined at compile time, but depends on the
  6588. runtime type of its input, as in the example above that depends on the
  6589. result of \code{(read)}.
  6590. The way around this problem is to include information about a value's
  6591. runtime type in the value itself, so that this information can be
  6592. inspected by operators such as \code{not}. In particular, we shall
  6593. steal the 3 right-most bits from our 64-bit values to encode the
  6594. runtime type. We shall use $001$ to identify integers, $100$ for
  6595. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6596. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6597. define the following auxiliary function.
  6598. \begin{align*}
  6599. \itm{tagof}(\key{Integer}) &= 001 \\
  6600. \itm{tagof}(\key{Boolean}) &= 100 \\
  6601. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6602. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6603. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6604. \itm{tagof}(\key{Void}) &= 101
  6605. \end{align*}
  6606. (We shall say more about the new \key{Vectorof} type shortly.)
  6607. This stealing of 3 bits comes at some
  6608. price: our integers are reduced to ranging from $-2^{60}$ to
  6609. $2^{60}$. The stealing does not adversely affect vectors and
  6610. procedures because those values are addresses, and our addresses are
  6611. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6612. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6613. bits with the tag and we can simply zero-out the tag to recover the
  6614. original address.
  6615. In some sense, these tagged values are a new kind of value. Indeed,
  6616. we can extend our \emph{typed} language with tagged values by adding a
  6617. new type to classify them, called \key{Any}, and with operations for
  6618. creating and using tagged values, yielding the $R_6$ language that we
  6619. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6620. fundamental support for polymorphism and runtime types that we need to
  6621. support dynamic typing.
  6622. There is an interesting interaction between tagged values and garbage
  6623. collection. A variable of type \code{Any} might refer to a vector and
  6624. therefore it might be a root that needs to be inspected and copied
  6625. during garbage collection. Thus, we need to treat variables of type
  6626. \code{Any} in a similar way to variables of type \code{Vector} for
  6627. purposes of register allocation, which we discuss in
  6628. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6629. variable of type \code{Any} is spilled, it must be spilled to the root
  6630. stack. But this means that the garbage collector needs to be able to
  6631. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6632. value that points to a tuple, and (3) a tagged value that is not a
  6633. tuple. We enable this differentiation by choosing not to use the tag
  6634. $000$. Instead, that bit pattern is reserved for identifying plain old
  6635. pointers to tuples. On the other hand, if one of the first three bits
  6636. is set, then we have a tagged value, and inspecting the tag can
  6637. differentiation between vectors ($010$) and the other kinds of values.
  6638. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6639. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6640. extend our compiler to handle the new features of $R_6$
  6641. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6642. \ref{sec:register-allocation-r6}).
  6643. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6644. \label{sec:r6-lang}
  6645. \begin{figure}[tp]
  6646. \centering
  6647. \fbox{
  6648. \begin{minipage}{0.97\textwidth}
  6649. \[
  6650. \begin{array}{lcl}
  6651. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6652. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6653. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6654. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6655. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6656. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6657. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6658. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6659. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6660. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6661. \mid (\key{and}\;\Exp\;\Exp)
  6662. \mid (\key{or}\;\Exp\;\Exp)
  6663. \mid (\key{not}\;\Exp)} \\
  6664. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6665. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6666. (\key{vector-ref}\;\Exp\;\Int)} \\
  6667. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6668. &\mid& \gray{(\Exp \; \Exp^{*})
  6669. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6670. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6671. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6672. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6673. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6674. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6675. \end{array}
  6676. \]
  6677. \end{minipage}
  6678. }
  6679. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6680. with \key{Any}.}
  6681. \label{fig:r6-syntax}
  6682. \end{figure}
  6683. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6684. $(\key{inject}\; e\; T)$ form converts the value produced by
  6685. expression $e$ of type $T$ into a tagged value. The
  6686. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6687. expression $e$ into a value of type $T$ or else halts the program if
  6688. the type tag is equivalent to $T$. We treat
  6689. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6690. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6691. Note that in both \key{inject} and
  6692. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6693. which simplifies the implementation and corresponds with what is
  6694. needed for compiling untyped Racket. The type predicates,
  6695. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6696. if the tag corresponds to the predicate, and return \key{\#t}
  6697. otherwise.
  6698. %
  6699. Selections from the type checker for $R_6$ are shown in
  6700. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6701. Figure~\ref{fig:interp-R6}.
  6702. \begin{figure}[btp]
  6703. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6704. (define (flat-ty? ty) ...)
  6705. (define (typecheck-R6 env)
  6706. (lambda (e)
  6707. (define recur (typecheck-R6 env))
  6708. (match e
  6709. [`(inject ,e ,ty)
  6710. (unless (flat-ty? ty)
  6711. (error "may only inject a value of flat type, not ~a" ty))
  6712. (define-values (new-e e-ty) (recur e))
  6713. (cond
  6714. [(equal? e-ty ty)
  6715. (values `(inject ,new-e ,ty) 'Any)]
  6716. [else
  6717. (error "inject expected ~a to have type ~a" e ty)])]
  6718. [`(project ,e ,ty)
  6719. (unless (flat-ty? ty)
  6720. (error "may only project to a flat type, not ~a" ty))
  6721. (define-values (new-e e-ty) (recur e))
  6722. (cond
  6723. [(equal? e-ty 'Any)
  6724. (values `(project ,new-e ,ty) ty)]
  6725. [else
  6726. (error "project expected ~a to have type Any" e)])]
  6727. [`(vector-ref ,e ,i)
  6728. (define-values (new-e e-ty) (recur e))
  6729. (match e-ty
  6730. [`(Vector ,ts ...) ...]
  6731. [`(Vectorof ,ty)
  6732. (unless (exact-nonnegative-integer? i)
  6733. (error 'type-check "invalid index ~a" i))
  6734. (values `(vector-ref ,new-e ,i) ty)]
  6735. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6736. ...
  6737. )))
  6738. \end{lstlisting}
  6739. \caption{Type checker for parts of the $R_6$ language.}
  6740. \label{fig:typecheck-R6}
  6741. \end{figure}
  6742. % to do: add rules for vector-ref, etc. for Vectorof
  6743. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6744. \begin{figure}[btp]
  6745. \begin{lstlisting}
  6746. (define primitives (set 'boolean? ...))
  6747. (define (interp-op op)
  6748. (match op
  6749. ['boolean? (lambda (v)
  6750. (match v
  6751. [`(tagged ,v1 Boolean) #t]
  6752. [else #f]))]
  6753. ...))
  6754. ;; Equivalence of flat types
  6755. (define (tyeq? t1 t2)
  6756. (match `(,t1 ,t2)
  6757. [`((Vectorof Any) (Vector ,t2s ...))
  6758. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6759. [`((Vector ,t1s ...) (Vectorof Any))
  6760. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6761. [else (equal? t1 t2)]))
  6762. (define (interp-R6 env)
  6763. (lambda (ast)
  6764. (match ast
  6765. [`(inject ,e ,t)
  6766. `(tagged ,((interp-R6 env) e) ,t)]
  6767. [`(project ,e ,t2)
  6768. (define v ((interp-R6 env) e))
  6769. (match v
  6770. [`(tagged ,v1 ,t1)
  6771. (cond [(tyeq? t1 t2)
  6772. v1]
  6773. [else
  6774. (error "in project, type mismatch" t1 t2)])]
  6775. [else
  6776. (error "in project, expected tagged value" v)])]
  6777. ...)))
  6778. \end{lstlisting}
  6779. \caption{Interpreter for $R_6$.}
  6780. \label{fig:interp-R6}
  6781. \end{figure}
  6782. %\clearpage
  6783. \section{Shrinking $R_6$}
  6784. \label{sec:shrink-r6}
  6785. In the \code{shrink} pass we recommend compiling \code{project} into
  6786. an explicit \code{if} expression that uses three new operations:
  6787. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6788. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6789. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6790. value from a tagged value. Finally, the \code{exit} operation ends the
  6791. execution of the program by invoking the operating system's
  6792. \code{exit} function. So the translation for \code{project} is as
  6793. follows. (We have omitted the \code{has-type} AST nodes to make this
  6794. output more readable.)
  6795. \begin{tabular}{lll}
  6796. \begin{minipage}{0.3\textwidth}
  6797. \begin{lstlisting}
  6798. (project |$e$| |$\Type$|)
  6799. \end{lstlisting}
  6800. \end{minipage}
  6801. &
  6802. $\Rightarrow$
  6803. &
  6804. \begin{minipage}{0.5\textwidth}
  6805. \begin{lstlisting}
  6806. (let ([|$\itm{tmp}$| |$e'$|])
  6807. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6808. (value-of-any |$\itm{tmp}$|)
  6809. (exit)))
  6810. \end{lstlisting}
  6811. \end{minipage}
  6812. \end{tabular} \\
  6813. Similarly, we recommend translating the type predicates
  6814. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6815. \section{Instruction Selection for $R_6$}
  6816. \label{sec:select-r6}
  6817. \paragraph{Inject}
  6818. We recommend compiling an \key{inject} as follows if the type is
  6819. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6820. destination to the left by the number of bits specified its source
  6821. argument (in this case $3$, the length of the tag) and it preserves
  6822. the sign of the integer. We use the \key{orq} instruction to combine
  6823. the tag and the value to form the tagged value. \\
  6824. \begin{tabular}{lll}
  6825. \begin{minipage}{0.4\textwidth}
  6826. \begin{lstlisting}
  6827. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6828. \end{lstlisting}
  6829. \end{minipage}
  6830. &
  6831. $\Rightarrow$
  6832. &
  6833. \begin{minipage}{0.5\textwidth}
  6834. \begin{lstlisting}
  6835. (movq |$e'$| |\itm{lhs}'|)
  6836. (salq (int 3) |\itm{lhs}'|)
  6837. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6838. \end{lstlisting}
  6839. \end{minipage}
  6840. \end{tabular} \\
  6841. The instruction selection for vectors and procedures is different
  6842. because their is no need to shift them to the left. The rightmost 3
  6843. bits are already zeros as described above. So we just combine the
  6844. value and the tag using \key{orq}. \\
  6845. \begin{tabular}{lll}
  6846. \begin{minipage}{0.4\textwidth}
  6847. \begin{lstlisting}
  6848. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6849. \end{lstlisting}
  6850. \end{minipage}
  6851. &
  6852. $\Rightarrow$
  6853. &
  6854. \begin{minipage}{0.5\textwidth}
  6855. \begin{lstlisting}
  6856. (movq |$e'$| |\itm{lhs}'|)
  6857. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6858. \end{lstlisting}
  6859. \end{minipage}
  6860. \end{tabular}
  6861. \paragraph{Tag of Any}
  6862. Recall that the \code{tag-of-any} operation extracts the type tag from
  6863. a value of type \code{Any}. The type tag is the bottom three bits, so
  6864. we obtain the tag by taking the bitwise-and of the value with $111$
  6865. ($7$ in decimal).
  6866. \begin{tabular}{lll}
  6867. \begin{minipage}{0.4\textwidth}
  6868. \begin{lstlisting}
  6869. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6870. \end{lstlisting}
  6871. \end{minipage}
  6872. &
  6873. $\Rightarrow$
  6874. &
  6875. \begin{minipage}{0.5\textwidth}
  6876. \begin{lstlisting}
  6877. (movq |$e'$| |\itm{lhs}'|)
  6878. (andq (int 7) |\itm{lhs}'|)
  6879. \end{lstlisting}
  6880. \end{minipage}
  6881. \end{tabular}
  6882. \paragraph{Value of Any}
  6883. Like \key{inject}, the instructions for \key{value-of-any} are
  6884. different depending on whether the type $T$ is a pointer (vector or
  6885. procedure) or not (Integer or Boolean). The following shows the
  6886. instruction selection for Integer and Boolean. We produce an untagged
  6887. value by shifting it to the right by 3 bits.
  6888. %
  6889. \\
  6890. \begin{tabular}{lll}
  6891. \begin{minipage}{0.4\textwidth}
  6892. \begin{lstlisting}
  6893. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6894. \end{lstlisting}
  6895. \end{minipage}
  6896. &
  6897. $\Rightarrow$
  6898. &
  6899. \begin{minipage}{0.5\textwidth}
  6900. \begin{lstlisting}
  6901. (movq |$e'$| |\itm{lhs}'|)
  6902. (sarq (int 3) |\itm{lhs}'|)
  6903. \end{lstlisting}
  6904. \end{minipage}
  6905. \end{tabular} \\
  6906. %
  6907. In the case for vectors and procedures, there is no need to
  6908. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6909. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6910. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6911. \code{movq} into the destination $\itm{lhs}$. We then generate
  6912. \code{andq} with the tagged value to get the desired result. \\
  6913. %
  6914. \begin{tabular}{lll}
  6915. \begin{minipage}{0.4\textwidth}
  6916. \begin{lstlisting}
  6917. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6918. \end{lstlisting}
  6919. \end{minipage}
  6920. &
  6921. $\Rightarrow$
  6922. &
  6923. \begin{minipage}{0.5\textwidth}
  6924. \begin{lstlisting}
  6925. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6926. (andq |$e'$| |\itm{lhs}'|)
  6927. \end{lstlisting}
  6928. \end{minipage}
  6929. \end{tabular}
  6930. %% \paragraph{Type Predicates} We leave it to the reader to
  6931. %% devise a sequence of instructions to implement the type predicates
  6932. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6933. \section{Register Allocation for $R_6$}
  6934. \label{sec:register-allocation-r6}
  6935. As mentioned above, a variable of type \code{Any} might refer to a
  6936. vector. Thus, the register allocator for $R_6$ needs to treat variable
  6937. of type \code{Any} in the same way that it treats variables of type
  6938. \code{Vector} for purposes of garbage collection. In particular,
  6939. \begin{itemize}
  6940. \item If a variable of type \code{Any} is live during a function call,
  6941. then it must be spilled. One way to accomplish this is to augment
  6942. the pass \code{build-interference} to mark all variables that are
  6943. live after a \code{callq} as interfering with all the registers.
  6944. \item If a variable of type \code{Any} is spilled, it must be spilled
  6945. to the root stack instead of the normal procedure call stack.
  6946. \end{itemize}
  6947. \begin{exercise}\normalfont
  6948. Expand your compiler to handle $R_6$ as discussed in the last few
  6949. sections. Create 5 new programs that use the \code{Any} type and the
  6950. new operations (\code{inject}, \code{project}, \code{boolean?},
  6951. etc.). Test your compiler on these new programs and all of your
  6952. previously created test programs.
  6953. \end{exercise}
  6954. \section{Compiling $R_7$ to $R_6$}
  6955. \label{sec:compile-r7}
  6956. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  6957. $R_7$ forms into $R_6$. An important invariant of this pass is that
  6958. given a subexpression $e$ of $R_7$, the pass will produce an
  6959. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  6960. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  6961. the Boolean \code{\#t}, which must be injected to produce an
  6962. expression of type \key{Any}.
  6963. %
  6964. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  6965. addition, is representative of compilation for many operations: the
  6966. arguments have type \key{Any} and must be projected to \key{Integer}
  6967. before the addition can be performed.
  6968. The compilation of \key{lambda} (third row of
  6969. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  6970. produce type annotations: we simply use \key{Any}.
  6971. %
  6972. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  6973. has to account for some differences in behavior between $R_7$ and
  6974. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  6975. kind of values can be used in various places. For example, the
  6976. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  6977. the arguments need not be of the same type (but in that case, the
  6978. result will be \code{\#f}).
  6979. \begin{figure}[btp]
  6980. \centering
  6981. \begin{tabular}{|lll|} \hline
  6982. \begin{minipage}{0.25\textwidth}
  6983. \begin{lstlisting}
  6984. #t
  6985. \end{lstlisting}
  6986. \end{minipage}
  6987. &
  6988. $\Rightarrow$
  6989. &
  6990. \begin{minipage}{0.6\textwidth}
  6991. \begin{lstlisting}
  6992. (inject #t Boolean)
  6993. \end{lstlisting}
  6994. \end{minipage}
  6995. \\[2ex]\hline
  6996. \begin{minipage}{0.25\textwidth}
  6997. \begin{lstlisting}
  6998. (+ |$e_1$| |$e_2$|)
  6999. \end{lstlisting}
  7000. \end{minipage}
  7001. &
  7002. $\Rightarrow$
  7003. &
  7004. \begin{minipage}{0.6\textwidth}
  7005. \begin{lstlisting}
  7006. (inject
  7007. (+ (project |$e'_1$| Integer)
  7008. (project |$e'_2$| Integer))
  7009. Integer)
  7010. \end{lstlisting}
  7011. \end{minipage}
  7012. \\[2ex]\hline
  7013. \begin{minipage}{0.25\textwidth}
  7014. \begin{lstlisting}
  7015. (lambda (|$x_1 \ldots$|) |$e$|)
  7016. \end{lstlisting}
  7017. \end{minipage}
  7018. &
  7019. $\Rightarrow$
  7020. &
  7021. \begin{minipage}{0.6\textwidth}
  7022. \begin{lstlisting}
  7023. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7024. (Any|$\ldots$|Any -> Any))
  7025. \end{lstlisting}
  7026. \end{minipage}
  7027. \\[2ex]\hline
  7028. \begin{minipage}{0.25\textwidth}
  7029. \begin{lstlisting}
  7030. (app |$e_0$| |$e_1 \ldots e_n$|)
  7031. \end{lstlisting}
  7032. \end{minipage}
  7033. &
  7034. $\Rightarrow$
  7035. &
  7036. \begin{minipage}{0.6\textwidth}
  7037. \begin{lstlisting}
  7038. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7039. |$e'_1 \ldots e'_n$|)
  7040. \end{lstlisting}
  7041. \end{minipage}
  7042. \\[2ex]\hline
  7043. \begin{minipage}{0.25\textwidth}
  7044. \begin{lstlisting}
  7045. (vector-ref |$e_1$| |$e_2$|)
  7046. \end{lstlisting}
  7047. \end{minipage}
  7048. &
  7049. $\Rightarrow$
  7050. &
  7051. \begin{minipage}{0.6\textwidth}
  7052. \begin{lstlisting}
  7053. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7054. (let ([tmp2 (project |$e'_2$| Integer)])
  7055. (vector-ref tmp1 tmp2)))
  7056. \end{lstlisting}
  7057. \end{minipage}
  7058. \\[2ex]\hline
  7059. \begin{minipage}{0.25\textwidth}
  7060. \begin{lstlisting}
  7061. (if |$e_1$| |$e_2$| |$e_3$|)
  7062. \end{lstlisting}
  7063. \end{minipage}
  7064. &
  7065. $\Rightarrow$
  7066. &
  7067. \begin{minipage}{0.6\textwidth}
  7068. \begin{lstlisting}
  7069. (if (eq? |$e'_1$| (inject #f Boolean))
  7070. |$e'_3$|
  7071. |$e'_2$|)
  7072. \end{lstlisting}
  7073. \end{minipage}
  7074. \\[2ex]\hline
  7075. \begin{minipage}{0.25\textwidth}
  7076. \begin{lstlisting}
  7077. (eq? |$e_1$| |$e_2$|)
  7078. \end{lstlisting}
  7079. \end{minipage}
  7080. &
  7081. $\Rightarrow$
  7082. &
  7083. \begin{minipage}{0.6\textwidth}
  7084. \begin{lstlisting}
  7085. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7086. \end{lstlisting}
  7087. \end{minipage}
  7088. \\[2ex]\hline
  7089. \end{tabular}
  7090. \caption{Compiling $R_7$ to $R_6$.}
  7091. \label{fig:compile-r7-r6}
  7092. \end{figure}
  7093. \begin{exercise}\normalfont
  7094. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7095. Create tests for $R_7$ by adapting all of your previous test programs
  7096. by removing type annotations. Add 5 more tests programs that
  7097. specifically rely on the language being dynamically typed. That is,
  7098. they should not be legal programs in a statically typed language, but
  7099. nevertheless, they should be valid $R_7$ programs that run to
  7100. completion without error.
  7101. \end{exercise}
  7102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7103. \chapter{Gradual Typing}
  7104. \label{ch:gradual-typing}
  7105. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7107. \chapter{Parametric Polymorphism}
  7108. \label{ch:parametric-polymorphism}
  7109. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7110. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7111. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7112. \chapter{High-level Optimization}
  7113. \label{ch:high-level-optimization}
  7114. This chapter will present a procedure inlining pass based on the
  7115. algorithm of \citet{Waddell:1997fk}.
  7116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7117. \chapter{Appendix}
  7118. \section{Interpreters}
  7119. \label{appendix:interp}
  7120. We provide several interpreters in the \key{interp.rkt} file. The
  7121. \key{interp-scheme} function takes an AST in one of the Racket-like
  7122. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7123. the program, returning the result value. The \key{interp-C} function
  7124. interprets an AST for a program in one of the C-like languages ($C_0,
  7125. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7126. for an x86 program.
  7127. \section{Utility Functions}
  7128. \label{appendix:utilities}
  7129. The utility function described in this section can be found in the
  7130. \key{utilities.rkt} file.
  7131. The \key{read-program} function takes a file path and parses that file
  7132. (it must be a Racket program) into an abstract syntax tree with a
  7133. \key{Program} node at the top.
  7134. The \key{parse-program} function takes an S-expression representation
  7135. of an AST and converts it into the struct-based representation.
  7136. The \key{assert} function displays the error message \key{msg} if the
  7137. Boolean \key{bool} is false.
  7138. \begin{lstlisting}
  7139. (define (assert msg bool) ...)
  7140. \end{lstlisting}
  7141. The \key{lookup} function takes a key and an association list (a list
  7142. of key-value pairs), and returns the first value that is associated
  7143. with the given key, if there is one. If not, an error is triggered.
  7144. The association list may contain both immutable pairs (built with
  7145. \key{cons}) and mutable pairs (built with \key{mcons}).
  7146. The \key{map2} function ...
  7147. %% \subsection{Graphs}
  7148. %% \begin{itemize}
  7149. %% \item The \code{make-graph} function takes a list of vertices
  7150. %% (symbols) and returns a graph.
  7151. %% \item The \code{add-edge} function takes a graph and two vertices and
  7152. %% adds an edge to the graph that connects the two vertices. The graph
  7153. %% is updated in-place. There is no return value for this function.
  7154. %% \item The \code{adjacent} function takes a graph and a vertex and
  7155. %% returns the set of vertices that are adjacent to the given
  7156. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7157. %% used with functions from the \code{racket/set} module.
  7158. %% \item The \code{vertices} function takes a graph and returns the list
  7159. %% of vertices in the graph.
  7160. %% \end{itemize}
  7161. \subsection{Testing}
  7162. The \key{interp-tests} function takes a compiler name (a string), a
  7163. description of the passes, an interpreter for the source language, a
  7164. test family name (a string), and a list of test numbers, and runs the
  7165. compiler passes and the interpreters to check whether the passes
  7166. correct. The description of the passes is a list with one entry per
  7167. pass. An entry is a list with three things: a string giving the name
  7168. of the pass, the function that implements the pass (a translator from
  7169. AST to AST), and a function that implements the interpreter (a
  7170. function from AST to result value) for the language of the output of
  7171. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7172. good choice. The \key{interp-tests} function assumes that the
  7173. subdirectory \key{tests} has a collection of Scheme programs whose names
  7174. all start with the family name, followed by an underscore and then the
  7175. test number, ending in \key{.scm}. Also, for each Scheme program there
  7176. is a file with the same number except that it ends with \key{.in} that
  7177. provides the input for the Scheme program.
  7178. \begin{lstlisting}
  7179. (define (interp-tests name passes test-family test-nums) ...)
  7180. \end{lstlisting}
  7181. The compiler-tests function takes a compiler name (a string) a
  7182. description of the passes (as described above for
  7183. \code{interp-tests}), a test family name (a string), and a list of
  7184. test numbers (see the comment for interp-tests), and runs the compiler
  7185. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7186. machine code. It runs the machine code and checks that the output is
  7187. 42.
  7188. \begin{lstlisting}
  7189. (define (compiler-tests name passes test-family test-nums) ...)
  7190. \end{lstlisting}
  7191. The compile-file function takes a description of the compiler passes
  7192. (see the comment for \key{interp-tests}) and returns a function that,
  7193. given a program file name (a string ending in \key{.scm}), applies all
  7194. of the passes and writes the output to a file whose name is the same
  7195. as the program file name but with \key{.scm} replaced with \key{.s}.
  7196. \begin{lstlisting}
  7197. (define (compile-file passes)
  7198. (lambda (prog-file-name) ...))
  7199. \end{lstlisting}
  7200. \section{x86 Instruction Set Quick-Reference}
  7201. \label{sec:x86-quick-reference}
  7202. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7203. do. We write $A \to B$ to mean that the value of $A$ is written into
  7204. location $B$. Address offsets are given in bytes. The instruction
  7205. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7206. registers (such as $\%rax$), or memory references (such as
  7207. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7208. reference per instruction. Other operands must be immediates or
  7209. registers.
  7210. \begin{table}[tbp]
  7211. \centering
  7212. \begin{tabular}{l|l}
  7213. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7214. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7215. \texttt{negq} $A$ & $- A \to A$ \\
  7216. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7217. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7218. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7219. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7220. \texttt{retq} & Pops the return address and jumps to it \\
  7221. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7222. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7223. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7224. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7225. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7226. matches the condition code of the instruction, otherwise go to the
  7227. next instructions. The condition codes are \key{e} for ``equal'',
  7228. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7229. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7230. \texttt{jl} $L$ & \\
  7231. \texttt{jle} $L$ & \\
  7232. \texttt{jg} $L$ & \\
  7233. \texttt{jge} $L$ & \\
  7234. \texttt{jmp} $L$ & Jump to label $L$ \\
  7235. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7236. \texttt{movzbq} $A$, $B$ &
  7237. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7238. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7239. and the extra bytes of $B$ are set to zero.} \\
  7240. & \\
  7241. & \\
  7242. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7243. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7244. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7245. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7246. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7247. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7248. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7249. description of the condition codes. $A$ must be a single byte register
  7250. (e.g., \texttt{al} or \texttt{cl}).} \\
  7251. \texttt{setl} $A$ & \\
  7252. \texttt{setle} $A$ & \\
  7253. \texttt{setg} $A$ & \\
  7254. \texttt{setge} $A$ &
  7255. \end{tabular}
  7256. \vspace{5pt}
  7257. \caption{Quick-reference for the x86 instructions used in this book.}
  7258. \label{tab:x86-instr}
  7259. \end{table}
  7260. \bibliographystyle{plainnat}
  7261. \bibliography{all}
  7262. \end{document}
  7263. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7264. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7265. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7266. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7267. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7268. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7269. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7270. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7271. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7272. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7273. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7274. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7275. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7276. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7277. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7278. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7279. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7280. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7281. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7282. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7283. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7284. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7285. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7286. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7287. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7288. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7289. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7290. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7291. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7292. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7293. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7294. % LocalWords: struct symtab