book.tex 538 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852
  1. %\documentclass[]{TimesAPriori_MIT}%%6x9
  2. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  3. %\documentclass[8x10]{TimesAPriori_MIT}%%8x10
  4. \usepackage[T1]{fontenc}
  5. \usepackage[utf8]{inputenc}
  6. \usepackage{listings}
  7. \usepackage{verbatim}
  8. \usepackage{amsmath}
  9. \usepackage{amsthm}
  10. \usepackage{amssymb}
  11. \usepackage{lmodern} % better typewriter font for code
  12. %\usepackage{wrapfig}
  13. \usepackage{multirow}
  14. \usepackage{tcolorbox}
  15. \usepackage{color}
  16. \definecolor{lightgray}{gray}{1}
  17. \newcommand{\black}[1]{{\color{black} #1}}
  18. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  19. \newcommand{\gray}[1]{{\color{gray} #1}}
  20. %% For multiple indices:
  21. \usepackage{multind}
  22. \makeindex{subject}
  23. \makeindex{authors}
  24. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  25. \lstset{%
  26. language=Lisp,
  27. basicstyle=\ttfamily\small,
  28. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  29. deletekeywords={read,mapping,vector},
  30. escapechar=|,
  31. columns=flexible,
  32. moredelim=[is][\color{red}]{~}{~},
  33. showstringspaces=false
  34. }
  35. %%% Any shortcut own defined macros place here
  36. %% sample of author macro:
  37. \input{defs}
  38. \newtheorem{exercise}[theorem]{Exercise}
  39. % Adjusted settings
  40. \setlength{\columnsep}{4pt}
  41. %% \begingroup
  42. %% \setlength{\intextsep}{0pt}%
  43. %% \setlength{\columnsep}{0pt}%
  44. %% \begin{wrapfigure}{r}{0.5\textwidth}
  45. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  46. %% \caption{Basic layout}
  47. %% \end{wrapfigure}
  48. %% \lipsum[1]
  49. %% \endgroup
  50. \newbox\oiintbox
  51. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  52. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  53. \def\oiint{\copy\oiintbox}
  54. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  55. %\usepackage{showframe}
  56. \def\ShowFrameLinethickness{0.125pt}
  57. \addbibresource{book.bib}
  58. \begin{document}
  59. \frontmatter
  60. \HalfTitle{Essentials of Compilation}
  61. \halftitlepage
  62. %% \begin{seriespage}
  63. %% \seriestitle{Industrial Economics}
  64. %% \serieseditor{Miriam Smith and Simon Rattle, editors}
  65. %% \title{Engineering and Economics}
  66. %% \author{Samuel Endgrove}
  67. %% \title{Structural Economics: From Beginning to End}
  68. %% \author{Guang Xi}
  69. %% \end{seriespage}
  70. \Title{Essentials of Compilation}
  71. \Booksubtitle{The Incremental, Nano-Pass Approach}
  72. \edition{First Edition}
  73. \BookAuthor{Jeremy G. Siek}
  74. \imprint{The MIT Press\\
  75. Cambridge, Massachusetts\\
  76. London, England}
  77. \begin{copyrightpage}
  78. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  79. or personal downloading under the
  80. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  81. license.
  82. Copyright in this monograph has been licensed exclusively to The MIT
  83. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  84. version to the public in 2022. All inquiries regarding rights should
  85. be addressed to The MIT Press, Rights and Permissions Department.
  86. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  87. %% All rights reserved. No part of this book may be reproduced in any
  88. %% form by any electronic or mechanical means (including photocopying,
  89. %% recording, or information storage and retrieval) without permission in
  90. %% writing from the publisher.
  91. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  92. %% United States of America.
  93. %% Library of Congress Cataloging-in-Publication Data is available.
  94. %% ISBN:
  95. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  96. \end{copyrightpage}
  97. \dedication{This book is dedicated to the programming language wonks
  98. at Indiana University.}
  99. %% \begin{epigraphpage}
  100. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  101. %% \textit{Book Name if any}}
  102. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  103. %% \end{epigraphpage}
  104. \tableofcontents
  105. \listoffigures
  106. \listoftables
  107. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  108. \chapter*{Preface}
  109. \addcontentsline{toc}{fmbm}{Preface}
  110. There is a magical moment when a programmer presses the ``run'' button
  111. and the software begins to execute. Somehow a program written in a
  112. high-level language is running on a computer that is only capable of
  113. shuffling bits. Here we reveal the wizardry that makes that moment
  114. possible. Beginning with the groundbreaking work of Backus and
  115. colleagues in the 1950s, computer scientists discovered techniques for
  116. constructing programs, called \emph{compilers}, that automatically
  117. translate high-level programs into machine code.
  118. We take you on a journey by constructing your own compiler for a small
  119. but powerful language. Along the way we explain the essential
  120. concepts, algorithms, and data structures that underlie compilers. We
  121. develop your understanding of how programs are mapped onto computer
  122. hardware, which is helpful when reasoning about properties at the
  123. junction between hardware and software such as execution time,
  124. software errors, and security vulnerabilities. For those interested
  125. in pursuing compiler construction, our goal is to provide a
  126. stepping-stone to advanced topics such as just-in-time compilation,
  127. program analysis, and program optimization. For those interested in
  128. designing and implementing programming languages, we connect
  129. language design choices to their impact on the compiler and the generated
  130. code.
  131. A compiler is typically organized as a sequence of stages that
  132. progressively translates a program to code that runs on hardware. We
  133. take this approach to the extreme by partitioning our compiler into a
  134. large number of \emph{nanopasses}, each of which performs a single
  135. task. This allows us to test the output of each pass in isolation, and
  136. furthermore, allows us to focus our attention making the compiler far
  137. easier to understand.
  138. %% [TODO: easier to understand/debug for those maintaining the compiler,
  139. %% proving correctness]
  140. The most familiar approach to describing compilers is with one pass
  141. per chapter. The problem with that is it obfuscates how language
  142. features motivate design choices in a compiler. We take an
  143. \emph{incremental} approach in which we build a complete compiler in
  144. each chapter, starting with arithmetic and variables and add new
  145. features in subsequent chapters.
  146. Our choice of language features is designed to elicit the fundamental
  147. concepts and algorithms used in compilers.
  148. \begin{itemize}
  149. \item We begin with integer arithmetic and local variables in
  150. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  151. the fundamental tools of compiler construction: \emph{abstract
  152. syntax trees} and \emph{recursive functions}.
  153. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  154. \emph{graph coloring} to assign variables to machine registers.
  155. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  156. an elegant recursive algorithm for mapping expressions to
  157. \emph{control-flow graphs}.
  158. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  159. \emph{garbage collection}.
  160. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  161. but lack lexical scoping, similar to the C programming
  162. language~\citep{Kernighan:1988nx} except that we generate efficient
  163. tail calls. The reader learns about the procedure call stack,
  164. \emph{calling conventions}, and their interaction with register
  165. allocation and garbage collection.
  166. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  167. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  168. \emph{closure conversion}, in which lambdas are translated into a
  169. combination of functions and tuples.
  170. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  171. point the input languages are statically typed. The reader extends
  172. the statically typed language with an \code{Any} type which serves
  173. as a target for compiling the dynamically typed language.
  174. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  175. programming languages with the addition of loops and mutable
  176. variables. These additions elicit the need for \emph{dataflow
  177. analysis} in the register allocator.
  178. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  179. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  180. in which different regions of a program may be static or dynamically
  181. typed. The reader implements runtime support for \emph{proxies} that
  182. allow values to safely move between regions.
  183. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  184. leveraging the \code{Any} type and type casts developed in Chapters
  185. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  186. \end{itemize}
  187. There are many language features that we do not include. Our choices
  188. weigh the incidental complexity of a feature against the fundamental
  189. concepts that it exposes. For example, we include tuples and not
  190. records because they both elicit the study of heap allocation and
  191. garbage collection but records come with more incidental complexity.
  192. Since 2016 this book has served as the textbook for the compiler
  193. course at Indiana University, a 16-week course for upper-level
  194. undergraduates and first-year graduate students.
  195. %
  196. Prior to this course, students learn to program in both imperative and
  197. functional languages, study data structures and algorithms, and take
  198. discrete mathematics.
  199. %
  200. At the beginning of the course, students form groups of 2-4 people.
  201. The groups complete one chapter every two weeks, starting with
  202. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  203. chapters include a challenge problem that we assign to the graduate
  204. students. The last two weeks of the course involve a final project in
  205. which students design and implement a compiler extension of their
  206. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  207. \ref{ch:Rpoly} can be used in support of these projects or they can
  208. replace some of the earlier chapters. For example, a course with an
  209. emphasis on statically-typed imperative languages would skip
  210. Chapter~\ref{ch:Rdyn} in favor of
  211. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  212. the dependencies between chapters.
  213. This book has also been used in compiler courses at California
  214. Polytechnic State University, Rose–Hulman Institute of Technology, and
  215. University of Massachusetts Lowell.
  216. \begin{figure}[tp]
  217. \begin{tikzpicture}[baseline=(current bounding box.center)]
  218. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  219. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  220. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  221. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  222. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  223. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  224. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  225. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  226. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  227. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  228. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  229. \path[->] (C1) edge [above] node {} (C2);
  230. \path[->] (C2) edge [above] node {} (C3);
  231. \path[->] (C3) edge [above] node {} (C4);
  232. \path[->] (C4) edge [above] node {} (C5);
  233. \path[->] (C5) edge [above] node {} (C6);
  234. \path[->] (C6) edge [above] node {} (C7);
  235. \path[->] (C4) edge [above] node {} (C8);
  236. \path[->] (C4) edge [above] node {} (C9);
  237. \path[->] (C8) edge [above] node {} (C10);
  238. \path[->] (C10) edge [above] node {} (C11);
  239. \end{tikzpicture}
  240. \caption{Diagram of chapter dependencies.}
  241. \label{fig:chapter-dependences}
  242. \end{figure}
  243. We use the \href{https://racket-lang.org/}{Racket} language both for
  244. the implementation of the compiler and for the input language, so the
  245. reader should be proficient with Racket or Scheme. There are many
  246. excellent resources for learning Scheme and
  247. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  248. support code for this book is in the \code{github} repository at the
  249. following URL:
  250. \begin{center}\small
  251. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  252. \end{center}
  253. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  254. is helpful but not necessary for the reader to have taken a computer
  255. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  256. of x86-64 assembly language that are needed.
  257. %
  258. We follow the System V calling
  259. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  260. that we generate works with the runtime system (written in C) when it
  261. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  262. operating systems.
  263. %
  264. On the Windows operating system, \code{gcc} uses the Microsoft x64
  265. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  266. assembly code that we generate does \emph{not} work with the runtime
  267. system on Windows. One workaround is to use a virtual machine with
  268. Linux as the guest operating system.
  269. \section*{Acknowledgments}
  270. The tradition of compiler construction at Indiana University goes back
  271. to research and courses on programming languages by Daniel Friedman in
  272. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  273. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  274. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  275. the compiler course and continued the development of Chez Scheme.
  276. %
  277. The compiler course evolved to incorporate novel pedagogical ideas
  278. while also including elements of efficient real-world compilers. One
  279. of Friedman's ideas was to split the compiler into many small
  280. passes. Another idea, called ``the game'', was to test the code
  281. generated by each pass using interpreters.
  282. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  283. developed infrastructure to support this approach and evolved the
  284. course to use even smaller
  285. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  286. design decisions in this book are inspired by the assignment
  287. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  288. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  289. organization of the course made it difficult for students to
  290. understand the rationale for the compiler design. Ghuloum proposed the
  291. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  292. on.
  293. We thank the many students who served as teaching assistants for the
  294. compiler course at IU and made suggestions for improving the book
  295. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  296. thank Andre Kuhlenschmidt for his work on the garbage collector,
  297. Michael Vollmer for his work on efficient tail calls, and Michael
  298. Vitousek for his help running the first offering of the incremental
  299. compiler course at IU.
  300. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  301. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  302. for teaching courses based on early drafts of this book and for their
  303. invaluable feedback.
  304. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  305. course in the early 2000's and especially for finding the bug that
  306. sent the garbage collector on a wild goose chase!
  307. \mbox{}\\
  308. \noindent Jeremy G. Siek \\
  309. Bloomington, Indiana
  310. \mainmatter
  311. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  312. \chapter{Preliminaries}
  313. \label{ch:trees-recur}
  314. In this chapter we review the basic tools that are needed to implement
  315. a compiler. Programs are typically input by a programmer as text,
  316. i.e., a sequence of characters. The program-as-text representation is
  317. called \emph{concrete syntax}. We use concrete syntax to concisely
  318. write down and talk about programs. Inside the compiler, we use
  319. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  320. that efficiently supports the operations that the compiler needs to
  321. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  322. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  323. from concrete syntax to abstract syntax is a process called
  324. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  325. implementation of parsing in this book. A parser is provided in the
  326. support code for translating from concrete to abstract syntax.
  327. ASTs can be represented in many different ways inside the compiler,
  328. depending on the programming language used to write the compiler.
  329. %
  330. We use Racket's
  331. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  332. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  333. define the abstract syntax of programming languages
  334. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  335. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  336. recursive functions to construct and deconstruct ASTs
  337. (Section~\ref{sec:recursion}). This chapter provides an brief
  338. introduction to these ideas. \index{subject}{struct}
  339. \section{Abstract Syntax Trees and Racket Structures}
  340. \label{sec:ast}
  341. Compilers use abstract syntax trees to represent programs because they
  342. often need to ask questions like: for a given part of a program, what
  343. kind of language feature is it? What are its sub-parts? Consider the
  344. program on the left and its AST on the right. This program is an
  345. addition operation and it has two sub-parts, a read operation and a
  346. negation. The negation has another sub-part, the integer constant
  347. \code{8}. By using a tree to represent the program, we can easily
  348. follow the links to go from one part of a program to its sub-parts.
  349. \begin{center}
  350. \begin{minipage}{0.4\textwidth}
  351. \begin{lstlisting}
  352. (+ (read) (- 8))
  353. \end{lstlisting}
  354. \end{minipage}
  355. \begin{minipage}{0.4\textwidth}
  356. \begin{equation}
  357. \begin{tikzpicture}
  358. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  359. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  360. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  361. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  362. \draw[->] (plus) to (read);
  363. \draw[->] (plus) to (minus);
  364. \draw[->] (minus) to (8);
  365. \end{tikzpicture}
  366. \label{eq:arith-prog}
  367. \end{equation}
  368. \end{minipage}
  369. \end{center}
  370. We use the standard terminology for trees to describe ASTs: each
  371. circle above is called a \emph{node}. The arrows connect a node to its
  372. \emph{children} (which are also nodes). The top-most node is the
  373. \emph{root}. Every node except for the root has a \emph{parent} (the
  374. node it is the child of). If a node has no children, it is a
  375. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  376. \index{subject}{node}
  377. \index{subject}{children}
  378. \index{subject}{root}
  379. \index{subject}{parent}
  380. \index{subject}{leaf}
  381. \index{subject}{internal node}
  382. %% Recall that an \emph{symbolic expression} (S-expression) is either
  383. %% \begin{enumerate}
  384. %% \item an atom, or
  385. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  386. %% where $e_1$ and $e_2$ are each an S-expression.
  387. %% \end{enumerate}
  388. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  389. %% null value \code{'()}, etc. We can create an S-expression in Racket
  390. %% simply by writing a backquote (called a quasi-quote in Racket)
  391. %% followed by the textual representation of the S-expression. It is
  392. %% quite common to use S-expressions to represent a list, such as $a, b
  393. %% ,c$ in the following way:
  394. %% \begin{lstlisting}
  395. %% `(a . (b . (c . ())))
  396. %% \end{lstlisting}
  397. %% Each element of the list is in the first slot of a pair, and the
  398. %% second slot is either the rest of the list or the null value, to mark
  399. %% the end of the list. Such lists are so common that Racket provides
  400. %% special notation for them that removes the need for the periods
  401. %% and so many parenthesis:
  402. %% \begin{lstlisting}
  403. %% `(a b c)
  404. %% \end{lstlisting}
  405. %% The following expression creates an S-expression that represents AST
  406. %% \eqref{eq:arith-prog}.
  407. %% \begin{lstlisting}
  408. %% `(+ (read) (- 8))
  409. %% \end{lstlisting}
  410. %% When using S-expressions to represent ASTs, the convention is to
  411. %% represent each AST node as a list and to put the operation symbol at
  412. %% the front of the list. The rest of the list contains the children. So
  413. %% in the above case, the root AST node has operation \code{`+} and its
  414. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  415. %% diagram \eqref{eq:arith-prog}.
  416. %% To build larger S-expressions one often needs to splice together
  417. %% several smaller S-expressions. Racket provides the comma operator to
  418. %% splice an S-expression into a larger one. For example, instead of
  419. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  420. %% we could have first created an S-expression for AST
  421. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  422. %% S-expression.
  423. %% \begin{lstlisting}
  424. %% (define ast1.4 `(- 8))
  425. %% (define ast1.1 `(+ (read) ,ast1.4))
  426. %% \end{lstlisting}
  427. %% In general, the Racket expression that follows the comma (splice)
  428. %% can be any expression that produces an S-expression.
  429. We define a Racket \code{struct} for each kind of node. For this
  430. chapter we require just two kinds of nodes: one for integer constants
  431. and one for primitive operations. The following is the \code{struct}
  432. definition for integer constants.
  433. \begin{lstlisting}
  434. (struct Int (value))
  435. \end{lstlisting}
  436. An integer node includes just one thing: the integer value.
  437. To create an AST node for the integer $8$, we write \code{(Int 8)}.
  438. \begin{lstlisting}
  439. (define eight (Int 8))
  440. \end{lstlisting}
  441. We say that the value created by \code{(Int 8)} is an
  442. \emph{instance} of the \code{Int} structure.
  443. The following is the \code{struct} definition for primitive operations.
  444. \begin{lstlisting}
  445. (struct Prim (op args))
  446. \end{lstlisting}
  447. A primitive operation node includes an operator symbol \code{op}
  448. and a list of child \code{args}. For example, to create
  449. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  450. \begin{lstlisting}
  451. (define neg-eight (Prim '- (list eight)))
  452. \end{lstlisting}
  453. Primitive operations may have zero or more children. The \code{read}
  454. operator has zero children:
  455. \begin{lstlisting}
  456. (define rd (Prim 'read '()))
  457. \end{lstlisting}
  458. whereas the addition operator has two children:
  459. \begin{lstlisting}
  460. (define ast1.1 (Prim '+ (list rd neg-eight)))
  461. \end{lstlisting}
  462. We have made a design choice regarding the \code{Prim} structure.
  463. Instead of using one structure for many different operations
  464. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  465. structure for each operation, as follows.
  466. \begin{lstlisting}
  467. (struct Read ())
  468. (struct Add (left right))
  469. (struct Neg (value))
  470. \end{lstlisting}
  471. The reason we choose to use just one structure is that in many parts
  472. of the compiler the code for the different primitive operators is the
  473. same, so we might as well just write that code once, which is enabled
  474. by using a single structure.
  475. When compiling a program such as \eqref{eq:arith-prog}, we need to
  476. know that the operation associated with the root node is addition and
  477. we need to be able to access its two children. Racket provides pattern
  478. matching to support these kinds of queries, as we see in
  479. Section~\ref{sec:pattern-matching}.
  480. In this book, we often write down the concrete syntax of a program
  481. even when we really have in mind the AST because the concrete syntax
  482. is more concise. We recommend that, in your mind, you always think of
  483. programs as abstract syntax trees.
  484. \section{Grammars}
  485. \label{sec:grammar}
  486. \index{subject}{integer}
  487. \index{subject}{literal}
  488. \index{subject}{constant}
  489. A programming language can be thought of as a \emph{set} of programs.
  490. The set is typically infinite (one can always create larger and larger
  491. programs), so one cannot simply describe a language by listing all of
  492. the programs in the language. Instead we write down a set of rules, a
  493. \emph{grammar}, for building programs. Grammars are often used to
  494. define the concrete syntax of a language, but they can also be used to
  495. describe the abstract syntax. We write our rules in a variant of
  496. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  497. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  498. As an example, we describe a small language, named \LangInt{}, that consists of
  499. integers and arithmetic operations.
  500. \index{subject}{grammar}
  501. The first grammar rule for the abstract syntax of \LangInt{} says that an
  502. instance of the \code{Int} structure is an expression:
  503. \begin{equation}
  504. \Exp ::= \INT{\Int} \label{eq:arith-int}
  505. \end{equation}
  506. %
  507. Each rule has a left-hand-side and a right-hand-side. The way to read
  508. a rule is that if you have an AST node that matches the
  509. right-hand-side, then you can categorize it according to the
  510. left-hand-side.
  511. %
  512. A name such as $\Exp$ that is defined by the grammar rules is a
  513. \emph{non-terminal}. \index{subject}{non-terminal}
  514. %
  515. The name $\Int$ is also a non-terminal, but instead of defining it
  516. with a grammar rule, we define it with the following explanation. We
  517. make the simplifying design decision that all of the languages in this
  518. book only handle machine-representable integers. On most modern
  519. machines this corresponds to integers represented with 64-bits, i.e.,
  520. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  521. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  522. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  523. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  524. that the sequence of decimals represent an integer in range $-2^{62}$
  525. to $2^{62}-1$.
  526. The second grammar rule is the \texttt{read} operation that receives
  527. an input integer from the user of the program.
  528. \begin{equation}
  529. \Exp ::= \READ{} \label{eq:arith-read}
  530. \end{equation}
  531. The third rule says that, given an $\Exp$ node, the negation of that
  532. node is also an $\Exp$.
  533. \begin{equation}
  534. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  535. \end{equation}
  536. Symbols in typewriter font such as \key{-} and \key{read} are
  537. \emph{terminal} symbols and must literally appear in the program for
  538. the rule to be applicable.
  539. \index{subject}{terminal}
  540. We can apply these rules to categorize the ASTs that are in the
  541. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  542. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  543. following AST is an $\Exp$.
  544. \begin{center}
  545. \begin{minipage}{0.4\textwidth}
  546. \begin{lstlisting}
  547. (Prim '- (list (Int 8)))
  548. \end{lstlisting}
  549. \end{minipage}
  550. \begin{minipage}{0.25\textwidth}
  551. \begin{equation}
  552. \begin{tikzpicture}
  553. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  554. \node[draw, circle] (8) at (0, -1.2) {$8$};
  555. \draw[->] (minus) to (8);
  556. \end{tikzpicture}
  557. \label{eq:arith-neg8}
  558. \end{equation}
  559. \end{minipage}
  560. \end{center}
  561. The next grammar rule is for addition expressions:
  562. \begin{equation}
  563. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  564. \end{equation}
  565. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  566. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  567. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  568. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  569. to show that
  570. \begin{lstlisting}
  571. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  572. \end{lstlisting}
  573. is an $\Exp$ in the \LangInt{} language.
  574. If you have an AST for which the above rules do not apply, then the
  575. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  576. is not in \LangInt{} because there are no rules for \code{+} with only one
  577. argument, nor for \key{-} with two arguments. Whenever we define a
  578. language with a grammar, the language only includes those programs
  579. that are justified by the rules.
  580. The last grammar rule for \LangInt{} states that there is a \code{Program}
  581. node to mark the top of the whole program:
  582. \[
  583. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  584. \]
  585. The \code{Program} structure is defined as follows
  586. \begin{lstlisting}
  587. (struct Program (info body))
  588. \end{lstlisting}
  589. where \code{body} is an expression. In later chapters, the \code{info}
  590. part will be used to store auxiliary information but for now it is
  591. just the empty list.
  592. It is common to have many grammar rules with the same left-hand side
  593. but different right-hand sides, such as the rules for $\Exp$ in the
  594. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  595. combine several right-hand-sides into a single rule.
  596. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  597. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  598. defined in Figure~\ref{fig:r0-concrete-syntax}.
  599. The \code{read-program} function provided in \code{utilities.rkt} of
  600. the support code reads a program in from a file (the sequence of
  601. characters in the concrete syntax of Racket) and parses it into an
  602. abstract syntax tree. See the description of \code{read-program} in
  603. Appendix~\ref{appendix:utilities} for more details.
  604. \begin{figure}[tp]
  605. \fbox{
  606. \begin{minipage}{0.96\textwidth}
  607. \[
  608. \begin{array}{rcl}
  609. \begin{array}{rcl}
  610. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  611. \LangInt{} &::=& \Exp
  612. \end{array}
  613. \end{array}
  614. \]
  615. \end{minipage}
  616. }
  617. \caption{The concrete syntax of \LangInt{}.}
  618. \label{fig:r0-concrete-syntax}
  619. \end{figure}
  620. \begin{figure}[tp]
  621. \fbox{
  622. \begin{minipage}{0.96\textwidth}
  623. \[
  624. \begin{array}{rcl}
  625. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  626. &\mid& \ADD{\Exp}{\Exp} \\
  627. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  628. \end{array}
  629. \]
  630. \end{minipage}
  631. }
  632. \caption{The abstract syntax of \LangInt{}.}
  633. \label{fig:r0-syntax}
  634. \end{figure}
  635. \section{Pattern Matching}
  636. \label{sec:pattern-matching}
  637. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  638. the parts of an AST node. Racket provides the \texttt{match} form to
  639. access the parts of a structure. Consider the following example and
  640. the output on the right. \index{subject}{match} \index{subject}{pattern matching}
  641. \begin{center}
  642. \begin{minipage}{0.5\textwidth}
  643. \begin{lstlisting}
  644. (match ast1.1
  645. [(Prim op (list child1 child2))
  646. (print op)])
  647. \end{lstlisting}
  648. \end{minipage}
  649. \vrule
  650. \begin{minipage}{0.25\textwidth}
  651. \begin{lstlisting}
  652. '+
  653. \end{lstlisting}
  654. \end{minipage}
  655. \end{center}
  656. In the above example, the \texttt{match} form takes an AST
  657. \eqref{eq:arith-prog} and binds its parts to the three pattern
  658. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  659. prints out the operator. In general, a match clause consists of a
  660. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  661. recursively defined to be either a pattern variable, a structure name
  662. followed by a pattern for each of the structure's arguments, or an
  663. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  664. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  665. and Chapter 9 of The Racket
  666. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  667. for a complete description of \code{match}.)
  668. %
  669. The body of a match clause may contain arbitrary Racket code. The
  670. pattern variables can be used in the scope of the body, such as
  671. \code{op} in \code{(print op)}.
  672. A \code{match} form may contain several clauses, as in the following
  673. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  674. the AST. The \code{match} proceeds through the clauses in order,
  675. checking whether the pattern can match the input AST. The body of the
  676. first clause that matches is executed. The output of \code{leaf?} for
  677. several ASTs is shown on the right.
  678. \begin{center}
  679. \begin{minipage}{0.6\textwidth}
  680. \begin{lstlisting}
  681. (define (leaf? arith)
  682. (match arith
  683. [(Int n) #t]
  684. [(Prim 'read '()) #t]
  685. [(Prim '- (list e1)) #f]
  686. [(Prim '+ (list e1 e2)) #f]))
  687. (leaf? (Prim 'read '()))
  688. (leaf? (Prim '- (list (Int 8))))
  689. (leaf? (Int 8))
  690. \end{lstlisting}
  691. \end{minipage}
  692. \vrule
  693. \begin{minipage}{0.25\textwidth}
  694. \begin{lstlisting}
  695. #t
  696. #f
  697. #t
  698. \end{lstlisting}
  699. \end{minipage}
  700. \end{center}
  701. When writing a \code{match}, we refer to the grammar definition to
  702. identify which non-terminal we are expecting to match against, then we
  703. make sure that 1) we have one clause for each alternative of that
  704. non-terminal and 2) that the pattern in each clause corresponds to the
  705. corresponding right-hand side of a grammar rule. For the \code{match}
  706. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  707. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  708. alternatives, so the \code{match} has 4 clauses. The pattern in each
  709. clause corresponds to the right-hand side of a grammar rule. For
  710. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  711. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  712. patterns, replace non-terminals such as $\Exp$ with pattern variables
  713. of your choice (e.g. \code{e1} and \code{e2}).
  714. \section{Recursive Functions}
  715. \label{sec:recursion}
  716. \index{subject}{recursive function}
  717. Programs are inherently recursive. For example, an \LangInt{} expression is
  718. often made of smaller expressions. Thus, the natural way to process an
  719. entire program is with a recursive function. As a first example of
  720. such a recursive function, we define \texttt{exp?} below, which takes
  721. an arbitrary value and determines whether or not it is an \LangInt{}
  722. expression.
  723. %
  724. We say that a function is defined by \emph{structural recursion} when
  725. it is defined using a sequence of match clauses that correspond to a
  726. grammar, and the body of each clause makes a recursive call on each
  727. child node.\footnote{This principle of structuring code according to
  728. the data definition is advocated in the book \emph{How to Design
  729. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  730. Below we also define a second function, named \code{Rint?}, that
  731. determines whether an AST is an \LangInt{} program. In general we can
  732. expect to write one recursive function to handle each non-terminal in
  733. a grammar.\index{subject}{structural recursion}
  734. %
  735. \begin{center}
  736. \begin{minipage}{0.7\textwidth}
  737. \begin{lstlisting}
  738. (define (exp? ast)
  739. (match ast
  740. [(Int n) #t]
  741. [(Prim 'read '()) #t]
  742. [(Prim '- (list e)) (exp? e)]
  743. [(Prim '+ (list e1 e2))
  744. (and (exp? e1) (exp? e2))]
  745. [else #f]))
  746. (define (Rint? ast)
  747. (match ast
  748. [(Program '() e) (exp? e)]
  749. [else #f]))
  750. (Rint? (Program '() ast1.1)
  751. (Rint? (Program '()
  752. (Prim '- (list (Prim 'read '())
  753. (Prim '+ (list (Num 8)))))))
  754. \end{lstlisting}
  755. \end{minipage}
  756. \vrule
  757. \begin{minipage}{0.25\textwidth}
  758. \begin{lstlisting}
  759. #t
  760. #f
  761. \end{lstlisting}
  762. \end{minipage}
  763. \end{center}
  764. You may be tempted to merge the two functions into one, like this:
  765. \begin{center}
  766. \begin{minipage}{0.5\textwidth}
  767. \begin{lstlisting}
  768. (define (Rint? ast)
  769. (match ast
  770. [(Int n) #t]
  771. [(Prim 'read '()) #t]
  772. [(Prim '- (list e)) (Rint? e)]
  773. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  774. [(Program '() e) (Rint? e)]
  775. [else #f]))
  776. \end{lstlisting}
  777. \end{minipage}
  778. \end{center}
  779. %
  780. Sometimes such a trick will save a few lines of code, especially when
  781. it comes to the \code{Program} wrapper. Yet this style is generally
  782. \emph{not} recommended because it can get you into trouble.
  783. %
  784. For example, the above function is subtly wrong:
  785. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  786. returns true when it should return false.
  787. \section{Interpreters}
  788. \label{sec:interp-Rint}
  789. \index{subject}{interpreter}
  790. In general, the intended behavior of a program is defined by the
  791. specification of the language. For example, the Scheme language is
  792. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  793. defined in its reference manual~\citep{plt-tr}. In this book we use
  794. interpreters to specify each language that we consider. An interpreter
  795. that is designated as the definition of a language is called a
  796. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  797. \index{subject}{definitional interpreter} We warm up by creating a definitional
  798. interpreter for the \LangInt{} language, which serves as a second example
  799. of structural recursion. The \texttt{interp-Rint} function is defined in
  800. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  801. input program followed by a call to the \lstinline{interp-exp} helper
  802. function, which in turn has one match clause per grammar rule for
  803. \LangInt{} expressions.
  804. \begin{figure}[tp]
  805. \begin{lstlisting}
  806. (define (interp-exp e)
  807. (match e
  808. [(Int n) n]
  809. [(Prim 'read '())
  810. (define r (read))
  811. (cond [(fixnum? r) r]
  812. [else (error 'interp-exp "read expected an integer" r)])]
  813. [(Prim '- (list e))
  814. (define v (interp-exp e))
  815. (fx- 0 v)]
  816. [(Prim '+ (list e1 e2))
  817. (define v1 (interp-exp e1))
  818. (define v2 (interp-exp e2))
  819. (fx+ v1 v2)]))
  820. (define (interp-Rint p)
  821. (match p
  822. [(Program '() e) (interp-exp e)]))
  823. \end{lstlisting}
  824. \caption{Interpreter for the \LangInt{} language.}
  825. \label{fig:interp-Rint}
  826. \end{figure}
  827. Let us consider the result of interpreting a few \LangInt{} programs. The
  828. following program adds two integers.
  829. \begin{lstlisting}
  830. (+ 10 32)
  831. \end{lstlisting}
  832. The result is \key{42}, the answer to life, the universe, and
  833. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  834. Galaxy} by Douglas Adams.}.
  835. %
  836. We wrote the above program in concrete syntax whereas the parsed
  837. abstract syntax is:
  838. \begin{lstlisting}
  839. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  840. \end{lstlisting}
  841. The next example demonstrates that expressions may be nested within
  842. each other, in this case nesting several additions and negations.
  843. \begin{lstlisting}
  844. (+ 10 (- (+ 12 20)))
  845. \end{lstlisting}
  846. What is the result of the above program?
  847. As mentioned previously, the \LangInt{} language does not support
  848. arbitrarily-large integers, but only $63$-bit integers, so we
  849. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  850. in Racket.
  851. Suppose
  852. \[
  853. n = 999999999999999999
  854. \]
  855. which indeed fits in $63$-bits. What happens when we run the
  856. following program in our interpreter?
  857. \begin{lstlisting}
  858. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  859. \end{lstlisting}
  860. It produces an error:
  861. \begin{lstlisting}
  862. fx+: result is not a fixnum
  863. \end{lstlisting}
  864. We establish the convention that if running the definitional
  865. interpreter on a program produces an error then the meaning of that
  866. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  867. error is a \code{trapped-error}. A compiler for the language is under
  868. no obligations regarding programs with unspecified behavior; it does
  869. not have to produce an executable, and if it does, that executable can
  870. do anything. On the other hand, if the error is a
  871. \code{trapped-error}, then the compiler must produce an executable and
  872. it is required to report that an error occurred. To signal an error,
  873. exit with a return code of \code{255}. The interpreters in chapters
  874. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  875. \code{trapped-error}.
  876. %% This convention applies to the languages defined in this
  877. %% book, as a way to simplify the student's task of implementing them,
  878. %% but this convention is not applicable to all programming languages.
  879. %%
  880. Moving on to the last feature of the \LangInt{} language, the \key{read}
  881. operation prompts the user of the program for an integer. Recall that
  882. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  883. \code{8}. So if we run
  884. \begin{lstlisting}
  885. (interp-Rint (Program '() ast1.1))
  886. \end{lstlisting}
  887. and if the input is \code{50}, the result is \code{42}.
  888. We include the \key{read} operation in \LangInt{} so a clever student
  889. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  890. during compilation to obtain the output and then generates the trivial
  891. code to produce the output. (Yes, a clever student did this in the
  892. first instance of this course.)
  893. The job of a compiler is to translate a program in one language into a
  894. program in another language so that the output program behaves the
  895. same way as the input program does. This idea is depicted in the
  896. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  897. $\mathcal{L}_2$, and a definitional interpreter for each language.
  898. Given a compiler that translates from language $\mathcal{L}_1$ to
  899. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  900. compiler must translate it into some program $P_2$ such that
  901. interpreting $P_1$ and $P_2$ on their respective interpreters with
  902. same input $i$ yields the same output $o$.
  903. \begin{equation} \label{eq:compile-correct}
  904. \begin{tikzpicture}[baseline=(current bounding box.center)]
  905. \node (p1) at (0, 0) {$P_1$};
  906. \node (p2) at (3, 0) {$P_2$};
  907. \node (o) at (3, -2.5) {$o$};
  908. \path[->] (p1) edge [above] node {compile} (p2);
  909. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  910. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  911. \end{tikzpicture}
  912. \end{equation}
  913. In the next section we see our first example of a compiler.
  914. \section{Example Compiler: a Partial Evaluator}
  915. \label{sec:partial-evaluation}
  916. In this section we consider a compiler that translates \LangInt{} programs
  917. into \LangInt{} programs that may be more efficient, that is, this compiler
  918. is an optimizer. This optimizer eagerly computes the parts of the
  919. program that do not depend on any inputs, a process known as
  920. \emph{partial evaluation}~\citep{Jones:1993uq}.
  921. \index{subject}{partial evaluation}
  922. For example, given the following program
  923. \begin{lstlisting}
  924. (+ (read) (- (+ 5 3)))
  925. \end{lstlisting}
  926. our compiler will translate it into the program
  927. \begin{lstlisting}
  928. (+ (read) -8)
  929. \end{lstlisting}
  930. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  931. evaluator for the \LangInt{} language. The output of the partial evaluator
  932. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  933. recursion over $\Exp$ is captured in the \code{pe-exp} function
  934. whereas the code for partially evaluating the negation and addition
  935. operations is factored into two separate helper functions:
  936. \code{pe-neg} and \code{pe-add}. The input to these helper
  937. functions is the output of partially evaluating the children.
  938. \begin{figure}[tp]
  939. \begin{lstlisting}
  940. (define (pe-neg r)
  941. (match r
  942. [(Int n) (Int (fx- 0 n))]
  943. [else (Prim '- (list r))]))
  944. (define (pe-add r1 r2)
  945. (match* (r1 r2)
  946. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  947. [(_ _) (Prim '+ (list r1 r2))]))
  948. (define (pe-exp e)
  949. (match e
  950. [(Int n) (Int n)]
  951. [(Prim 'read '()) (Prim 'read '())]
  952. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  953. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  954. (define (pe-Rint p)
  955. (match p
  956. [(Program '() e) (Program '() (pe-exp e))]))
  957. \end{lstlisting}
  958. \caption{A partial evaluator for \LangInt{}.}
  959. \label{fig:pe-arith}
  960. \end{figure}
  961. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  962. arguments are integers and if they are, perform the appropriate
  963. arithmetic. Otherwise, they create an AST node for the arithmetic
  964. operation.
  965. To gain some confidence that the partial evaluator is correct, we can
  966. test whether it produces programs that get the same result as the
  967. input programs. That is, we can test whether it satisfies Diagram
  968. \ref{eq:compile-correct}. The following code runs the partial
  969. evaluator on several examples and tests the output program. The
  970. \texttt{parse-program} and \texttt{assert} functions are defined in
  971. Appendix~\ref{appendix:utilities}.\\
  972. \begin{minipage}{1.0\textwidth}
  973. \begin{lstlisting}
  974. (define (test-pe p)
  975. (assert "testing pe-Rint"
  976. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  977. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  978. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  979. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  980. \end{lstlisting}
  981. \end{minipage}
  982. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  983. \chapter{Integers and Variables}
  984. \label{ch:Rvar}
  985. This chapter is about compiling a subset of Racket to x86-64 assembly
  986. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  987. integer arithmetic and local variable binding. We often refer to
  988. x86-64 simply as x86. The chapter begins with a description of the
  989. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  990. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  991. is large so we discuss only the instructions needed for compiling
  992. \LangVar{}. We introduce more x86 instructions in later chapters.
  993. After introducing \LangVar{} and x86, we reflect on their differences
  994. and come up with a plan to break down the translation from \LangVar{}
  995. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  996. rest of the sections in this chapter give detailed hints regarding
  997. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  998. We hope to give enough hints that the well-prepared reader, together
  999. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1000. a couple weeks. To give the reader a feeling for the scale of this
  1001. first compiler, the instructor solution for the \LangVar{} compiler is
  1002. approximately 500 lines of code.
  1003. \section{The \LangVar{} Language}
  1004. \label{sec:s0}
  1005. \index{subject}{variable}
  1006. The \LangVar{} language extends the \LangInt{} language with variable
  1007. definitions. The concrete syntax of the \LangVar{} language is defined by
  1008. the grammar in Figure~\ref{fig:Rvar-concrete-syntax} and the abstract
  1009. syntax is defined in Figure~\ref{fig:Rvar-syntax}. The non-terminal
  1010. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  1011. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1012. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1013. \key{Program} struct to mark the top of the program.
  1014. %% The $\itm{info}$
  1015. %% field of the \key{Program} structure contains an \emph{association
  1016. %% list} (a list of key-value pairs) that is used to communicate
  1017. %% auxiliary data from one compiler pass the next.
  1018. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1019. exhibit several compilation techniques.
  1020. \begin{figure}[tp]
  1021. \centering
  1022. \fbox{
  1023. \begin{minipage}{0.96\textwidth}
  1024. \[
  1025. \begin{array}{rcl}
  1026. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1027. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1028. \LangVarM{} &::=& \Exp
  1029. \end{array}
  1030. \]
  1031. \end{minipage}
  1032. }
  1033. \caption{The concrete syntax of \LangVar{}.}
  1034. \label{fig:Rvar-concrete-syntax}
  1035. \end{figure}
  1036. \begin{figure}[tp]
  1037. \centering
  1038. \fbox{
  1039. \begin{minipage}{0.96\textwidth}
  1040. \[
  1041. \begin{array}{rcl}
  1042. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1043. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1044. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1045. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1046. \end{array}
  1047. \]
  1048. \end{minipage}
  1049. }
  1050. \caption{The abstract syntax of \LangVar{}.}
  1051. \label{fig:Rvar-syntax}
  1052. \end{figure}
  1053. Let us dive further into the syntax and semantics of the \LangVar{}
  1054. language. The \key{let} feature defines a variable for use within its
  1055. body and initializes the variable with the value of an expression.
  1056. The abstract syntax for \key{let} is defined in
  1057. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for \key{let} is
  1058. \begin{lstlisting}
  1059. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1060. \end{lstlisting}
  1061. For example, the following program initializes \code{x} to $32$ and then
  1062. evaluates the body \code{(+ 10 x)}, producing $42$.
  1063. \begin{lstlisting}
  1064. (let ([x (+ 12 20)]) (+ 10 x))
  1065. \end{lstlisting}
  1066. When there are multiple \key{let}'s for the same variable, the closest
  1067. enclosing \key{let} is used. That is, variable definitions overshadow
  1068. prior definitions. Consider the following program with two \key{let}'s
  1069. that define variables named \code{x}. Can you figure out the result?
  1070. \begin{lstlisting}
  1071. (let ([x 32]) (+ (let ([x 10]) x) x))
  1072. \end{lstlisting}
  1073. For the purposes of depicting which variable uses correspond to which
  1074. definitions, the following shows the \code{x}'s annotated with
  1075. subscripts to distinguish them. Double check that your answer for the
  1076. above is the same as your answer for this annotated version of the
  1077. program.
  1078. \begin{lstlisting}
  1079. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1080. \end{lstlisting}
  1081. The initializing expression is always evaluated before the body of the
  1082. \key{let}, so in the following, the \key{read} for \code{x} is
  1083. performed before the \key{read} for \code{y}. Given the input
  1084. $52$ then $10$, the following produces $42$ (not $-42$).
  1085. \begin{lstlisting}
  1086. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1087. \end{lstlisting}
  1088. \subsection{Extensible Interpreters via Method Overriding}
  1089. \label{sec:extensible-interp}
  1090. To prepare for discussing the interpreter for \LangVar{}, we
  1091. explain why we to implement the interpreter using
  1092. object-oriented programming, that is, as a collection of methods
  1093. inside of a class. Throughout this book we define many interpreters,
  1094. one for each of the languages that we study. Because each language
  1095. builds on the prior one, there is a lot of commonality between these
  1096. interpreters. We want to write down those common parts just once
  1097. instead of many times. A naive approach would be to have, for example,
  1098. the interpreter for \LangIf{} handle all of the new features in that
  1099. language and then have a default case that dispatches to the
  1100. interpreter for \LangVar{}. The following code sketches this idea.
  1101. \begin{center}
  1102. \begin{minipage}{0.45\textwidth}
  1103. \begin{lstlisting}
  1104. (define (interp-Rvar e)
  1105. (match e
  1106. [(Prim '- (list e))
  1107. (fx- 0 (interp-Rvar e))]
  1108. ...))
  1109. \end{lstlisting}
  1110. \end{minipage}
  1111. \begin{minipage}{0.45\textwidth}
  1112. \begin{lstlisting}
  1113. (define (interp-Rif e)
  1114. (match e
  1115. [(If cnd thn els)
  1116. (match (interp-Rif cnd)
  1117. [#t (interp-Rif thn)]
  1118. [#f (interp-Rif els)])]
  1119. ...
  1120. [else (interp-Rvar e)]))
  1121. \end{lstlisting}
  1122. \end{minipage}
  1123. \end{center}
  1124. The problem with this approach is that it does not handle situations
  1125. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1126. feature, like the \code{-} operator, as in the following program.
  1127. \begin{lstlisting}
  1128. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1129. \end{lstlisting}
  1130. If we invoke \code{interp-Rif} on this program, it dispatches to
  1131. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1132. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1133. which is an \code{If}. But there is no case for \code{If} in
  1134. \code{interp-Rvar}, so we get an error!
  1135. To make our interpreters extensible we need something called
  1136. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1137. recursive knot is delayed to when the functions are
  1138. composed. Object-oriented languages provide open recursion with the
  1139. late-binding of overridden methods\index{subject}{method overriding}. The
  1140. following code sketches this idea for interpreting \LangVar{} and
  1141. \LangIf{} using the
  1142. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1143. \index{subject}{class} feature of Racket. We define one class for each
  1144. language and define a method for interpreting expressions inside each
  1145. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1146. and the method \code{interp-exp} in \LangIf{} overrides the
  1147. \code{interp-exp} in \LangVar{}. Note that the default case of
  1148. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1149. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1150. that dispatches to the \code{interp-exp} in \LangVar{}.
  1151. \begin{center}
  1152. \begin{minipage}{0.45\textwidth}
  1153. \begin{lstlisting}
  1154. (define interp-Rvar-class
  1155. (class object%
  1156. (define/public (interp-exp e)
  1157. (match e
  1158. [(Prim '- (list e))
  1159. (fx- 0 (interp-exp e))]
  1160. ...))
  1161. ...))
  1162. \end{lstlisting}
  1163. \end{minipage}
  1164. \begin{minipage}{0.45\textwidth}
  1165. \begin{lstlisting}
  1166. (define interp-Rif-class
  1167. (class interp-Rvar-class
  1168. (define/override (interp-exp e)
  1169. (match e
  1170. [(If cnd thn els)
  1171. (match (interp-exp cnd)
  1172. [#t (interp-exp thn)]
  1173. [#f (interp-exp els)])]
  1174. ...
  1175. [else (super interp-exp e)]))
  1176. ...
  1177. ))
  1178. \end{lstlisting}
  1179. \end{minipage}
  1180. \end{center}
  1181. Getting back to the troublesome example, repeated here:
  1182. \begin{lstlisting}
  1183. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1184. \end{lstlisting}
  1185. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1186. expression by creating an object of the \LangIf{} class and sending it the
  1187. \code{interp-exp} method with the argument \code{e0}.
  1188. \begin{lstlisting}
  1189. (send (new interp-Rif-class) interp-exp e0)
  1190. \end{lstlisting}
  1191. The default case of \code{interp-exp} in \LangIf{} handles it by
  1192. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1193. handles the \code{-} operator. But then for the recursive method call,
  1194. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1195. \code{If} is handled correctly. Thus, method overriding gives us the
  1196. open recursion that we need to implement our interpreters in an
  1197. extensible way.
  1198. \subsection{Definitional Interpreter for \LangVar{}}
  1199. \begin{figure}[tp]
  1200. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1201. \small
  1202. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1203. An \emph{association list} (alist) is a list of key-value pairs.
  1204. For example, we can map people to their ages with an alist.
  1205. \index{subject}{alist}\index{subject}{association list}
  1206. \begin{lstlisting}[basicstyle=\ttfamily]
  1207. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1208. \end{lstlisting}
  1209. The \emph{dictionary} interface is for mapping keys to values.
  1210. Every alist implements this interface. \index{subject}{dictionary} The package
  1211. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1212. provides many functions for working with dictionaries. Here
  1213. are a few of them:
  1214. \begin{description}
  1215. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1216. returns the value associated with the given $\itm{key}$.
  1217. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1218. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1219. but otherwise is the same as $\itm{dict}$.
  1220. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1221. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1222. of keys and values in $\itm{dict}$. For example, the following
  1223. creates a new alist in which the ages are incremented.
  1224. \end{description}
  1225. \vspace{-10pt}
  1226. \begin{lstlisting}[basicstyle=\ttfamily]
  1227. (for/list ([(k v) (in-dict ages)])
  1228. (cons k (add1 v)))
  1229. \end{lstlisting}
  1230. \end{tcolorbox}
  1231. %\end{wrapfigure}
  1232. \caption{Association lists implement the dictionary interface.}
  1233. \label{fig:alist}
  1234. \end{figure}
  1235. Having justified the use of classes and methods to implement
  1236. interpreters, we turn to the definitional interpreter for \LangVar{}
  1237. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1238. \LangInt{} but adds two new \key{match} cases for variables and
  1239. \key{let}. For \key{let} we need a way to communicate the value bound
  1240. to a variable to all the uses of the variable. To accomplish this, we
  1241. maintain a mapping from variables to values. Throughout the compiler
  1242. we often need to map variables to information about them. We refer to
  1243. these mappings as
  1244. \emph{environments}\index{subject}{environment}.\footnote{Another common term
  1245. for environment in the compiler literature is \emph{symbol
  1246. table}\index{subject}{symbol table}.}
  1247. %
  1248. For simplicity, we use an association list (alist) to represent the
  1249. environment. Figure~\ref{fig:alist} gives a brief introduction to
  1250. alists and the \code{racket/dict} package. The \code{interp-exp}
  1251. function takes the current environment, \code{env}, as an extra
  1252. parameter. When the interpreter encounters a variable, it finds the
  1253. corresponding value using the \code{dict-ref} function. When the
  1254. interpreter encounters a \key{Let}, it evaluates the initializing
  1255. expression, extends the environment with the result value bound to the
  1256. variable, using \code{dict-set}, then evaluates the body of the
  1257. \key{Let}.
  1258. \begin{figure}[tp]
  1259. \begin{lstlisting}
  1260. (define interp-Rvar-class
  1261. (class object%
  1262. (super-new)
  1263. (define/public ((interp-exp env) e)
  1264. (match e
  1265. [(Int n) n]
  1266. [(Prim 'read '())
  1267. (define r (read))
  1268. (cond [(fixnum? r) r]
  1269. [else (error 'interp-exp "expected an integer" r)])]
  1270. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1271. [(Prim '+ (list e1 e2))
  1272. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1273. [(Var x) (dict-ref env x)]
  1274. [(Let x e body)
  1275. (define new-env (dict-set env x ((interp-exp env) e)))
  1276. ((interp-exp new-env) body)]))
  1277. (define/public (interp-program p)
  1278. (match p
  1279. [(Program '() e) ((interp-exp '()) e)]))
  1280. ))
  1281. (define (interp-Rvar p)
  1282. (send (new interp-Rvar-class) interp-program p))
  1283. \end{lstlisting}
  1284. \caption{Interpreter for the \LangVar{} language.}
  1285. \label{fig:interp-Rvar}
  1286. \end{figure}
  1287. The goal for this chapter is to implement a compiler that translates
  1288. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1289. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1290. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1291. is, they output the same integer $n$. We depict this correctness
  1292. criteria in the following diagram.
  1293. \[
  1294. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1295. \node (p1) at (0, 0) {$P_1$};
  1296. \node (p2) at (4, 0) {$P_2$};
  1297. \node (o) at (4, -2) {$n$};
  1298. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1299. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1300. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1301. \end{tikzpicture}
  1302. \]
  1303. In the next section we introduce the \LangXInt{} subset of x86 that
  1304. suffices for compiling \LangVar{}.
  1305. \section{The \LangXInt{} Assembly Language}
  1306. \label{sec:x86}
  1307. \index{subject}{x86}
  1308. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1309. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1310. assembler.
  1311. %
  1312. A program begins with a \code{main} label followed by a sequence of
  1313. instructions. The \key{globl} directive says that the \key{main}
  1314. procedure is externally visible, which is necessary so that the
  1315. operating system can call it. In the grammar, ellipses such as
  1316. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1317. \ldots$ is a sequence of instructions.\index{subject}{instruction}
  1318. %
  1319. An x86 program is stored in the computer's memory. For our purposes,
  1320. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1321. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1322. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1323. the address of the next instruction to be executed. For most
  1324. instructions, the program counter is incremented after the instruction
  1325. is executed, so it points to the next instruction in memory. Most x86
  1326. instructions take two operands, where each operand is either an
  1327. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1328. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1329. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1330. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1331. && \key{r8} \mid \key{r9} \mid \key{r10}
  1332. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1333. \mid \key{r14} \mid \key{r15}}
  1334. \begin{figure}[tp]
  1335. \fbox{
  1336. \begin{minipage}{0.96\textwidth}
  1337. \[
  1338. \begin{array}{lcl}
  1339. \Reg &::=& \allregisters{} \\
  1340. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1341. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1342. \key{subq} \; \Arg\key{,} \Arg \mid
  1343. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1344. && \key{callq} \; \mathit{label} \mid
  1345. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1346. && \itm{label}\key{:}\; \Instr \\
  1347. \LangXIntM{} &::= & \key{.globl main}\\
  1348. & & \key{main:} \; \Instr\ldots
  1349. \end{array}
  1350. \]
  1351. \end{minipage}
  1352. }
  1353. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1354. \label{fig:x86-int-concrete}
  1355. \end{figure}
  1356. A register is a special kind of variable. Each one holds a 64-bit
  1357. value; there are 16 general-purpose registers in the computer and
  1358. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1359. is written with a \key{\%} followed by the register name, such as
  1360. \key{\%rax}.
  1361. An immediate value is written using the notation \key{\$}$n$ where $n$
  1362. is an integer.
  1363. %
  1364. %
  1365. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1366. which obtains the address stored in register $r$ and then adds $n$
  1367. bytes to the address. The resulting address is used to load or store
  1368. to memory depending on whether it occurs as a source or destination
  1369. argument of an instruction.
  1370. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1371. source $s$ and destination $d$, applies the arithmetic operation, then
  1372. writes the result back to the destination $d$.
  1373. %
  1374. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1375. stores the result in $d$.
  1376. %
  1377. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1378. specified by the label and $\key{retq}$ returns from a procedure to
  1379. its caller.
  1380. %
  1381. We discuss procedure calls in more detail later in this chapter and in
  1382. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1383. updates the program counter to the address of the instruction after
  1384. the specified label.
  1385. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1386. all of the x86 instructions used in this book.
  1387. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1388. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1389. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1390. adds $32$ to the $10$ in \key{rax} and
  1391. puts the result, $42$, back into \key{rax}.
  1392. %
  1393. The last instruction, \key{retq}, finishes the \key{main} function by
  1394. returning the integer in \key{rax} to the operating system. The
  1395. operating system interprets this integer as the program's exit
  1396. code. By convention, an exit code of 0 indicates that a program
  1397. completed successfully, and all other exit codes indicate various
  1398. errors. Nevertheless, in this book we return the result of the program
  1399. as the exit code.
  1400. \begin{figure}[tbp]
  1401. \begin{lstlisting}
  1402. .globl main
  1403. main:
  1404. movq $10, %rax
  1405. addq $32, %rax
  1406. retq
  1407. \end{lstlisting}
  1408. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1409. \label{fig:p0-x86}
  1410. \end{figure}
  1411. The x86 assembly language varies in a couple of ways depending on what
  1412. operating system it is assembled in. The code examples shown here are
  1413. correct on Linux and most Unix-like platforms, but when assembled on
  1414. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1415. as in \key{\_main}.
  1416. We exhibit the use of memory for storing intermediate results in the
  1417. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1418. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1419. memory called the \emph{procedure call stack} (or \emph{stack} for
  1420. short). \index{subject}{stack}\index{subject}{procedure call stack} The stack consists
  1421. of a separate \emph{frame}\index{subject}{frame} for each procedure call. The
  1422. memory layout for an individual frame is shown in
  1423. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1424. \emph{stack pointer}\index{subject}{stack pointer} and points to the item at
  1425. the top of the stack. The stack grows downward in memory, so we
  1426. increase the size of the stack by subtracting from the stack pointer.
  1427. In the context of a procedure call, the \emph{return
  1428. address}\index{subject}{return address} is the instruction after the call
  1429. instruction on the caller side. The function call instruction,
  1430. \code{callq}, pushes the return address onto the stack prior to
  1431. jumping to the procedure. The register \key{rbp} is the \emph{base
  1432. pointer}\index{subject}{base pointer} and is used to access variables that
  1433. are stored in the frame of the current procedure call. The base
  1434. pointer of the caller is pushed onto the stack after the return
  1435. address and then the base pointer is set to the location of the old
  1436. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1437. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1438. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1439. \begin{figure}[tbp]
  1440. \begin{lstlisting}
  1441. start:
  1442. movq $10, -8(%rbp)
  1443. negq -8(%rbp)
  1444. movq -8(%rbp), %rax
  1445. addq $52, %rax
  1446. jmp conclusion
  1447. .globl main
  1448. main:
  1449. pushq %rbp
  1450. movq %rsp, %rbp
  1451. subq $16, %rsp
  1452. jmp start
  1453. conclusion:
  1454. addq $16, %rsp
  1455. popq %rbp
  1456. retq
  1457. \end{lstlisting}
  1458. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1459. \label{fig:p1-x86}
  1460. \end{figure}
  1461. \begin{figure}[tbp]
  1462. \centering
  1463. \begin{tabular}{|r|l|} \hline
  1464. Position & Contents \\ \hline
  1465. 8(\key{\%rbp}) & return address \\
  1466. 0(\key{\%rbp}) & old \key{rbp} \\
  1467. -8(\key{\%rbp}) & variable $1$ \\
  1468. -16(\key{\%rbp}) & variable $2$ \\
  1469. \ldots & \ldots \\
  1470. 0(\key{\%rsp}) & variable $n$\\ \hline
  1471. \end{tabular}
  1472. \caption{Memory layout of a frame.}
  1473. \label{fig:frame}
  1474. \end{figure}
  1475. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1476. control is transferred from the operating system to the \code{main}
  1477. function. The operating system issues a \code{callq main} instruction
  1478. which pushes its return address on the stack and then jumps to
  1479. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1480. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1481. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1482. alignment (because the \code{callq} pushed the return address). The
  1483. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  1484. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1485. pointer for the caller onto the stack and subtracts $8$ from the stack
  1486. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1487. base pointer so that it points the location of the old base
  1488. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1489. pointer down to make enough room for storing variables. This program
  1490. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1491. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1492. functions. The last instruction of the prelude is \code{jmp start},
  1493. which transfers control to the instructions that were generated from
  1494. the Racket expression \code{(+ 52 (- 10))}.
  1495. The first instruction under the \code{start} label is
  1496. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1497. %
  1498. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1499. %
  1500. The next instruction moves the $-10$ from variable $1$ into the
  1501. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1502. the value in \code{rax}, updating its contents to $42$.
  1503. The three instructions under the label \code{conclusion} are the
  1504. typical \emph{conclusion}\index{subject}{conclusion} of a procedure. The first
  1505. two instructions restore the \code{rsp} and \code{rbp} registers to
  1506. the state they were in at the beginning of the procedure. The
  1507. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1508. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1509. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1510. instruction, \key{retq}, jumps back to the procedure that called this
  1511. one and adds $8$ to the stack pointer.
  1512. The compiler needs a convenient representation for manipulating x86
  1513. programs, so we define an abstract syntax for x86 in
  1514. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1515. \LangXInt{}. The main difference compared to the concrete syntax of
  1516. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1517. allowed in front of every instruction. Instead instructions are
  1518. grouped into \emph{blocks}\index{subject}{block}\index{subject}{basic block} with a
  1519. label associated with every block, which is why the \key{X86Program}
  1520. struct includes an alist mapping labels to blocks. The reason for this
  1521. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  1522. introduce conditional branching. The \code{Block} structure includes
  1523. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1524. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1525. $\itm{info}$ field should contain an empty list. Also, regarding the
  1526. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1527. integer for representing the arity of the function, i.e., the number
  1528. of arguments, which is helpful to know during register allocation
  1529. (Chapter~\ref{ch:register-allocation-Rvar}).
  1530. \begin{figure}[tp]
  1531. \fbox{
  1532. \begin{minipage}{0.98\textwidth}
  1533. \small
  1534. \[
  1535. \begin{array}{lcl}
  1536. \Reg &::=& \allregisters{} \\
  1537. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1538. \mid \DEREF{\Reg}{\Int} \\
  1539. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1540. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1541. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1542. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1543. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1544. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1545. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1546. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1547. \end{array}
  1548. \]
  1549. \end{minipage}
  1550. }
  1551. \caption{The abstract syntax of \LangXInt{} assembly.}
  1552. \label{fig:x86-int-ast}
  1553. \end{figure}
  1554. \section{Planning the trip to x86 via the \LangCVar{} language}
  1555. \label{sec:plan-s0-x86}
  1556. To compile one language to another it helps to focus on the
  1557. differences between the two languages because the compiler will need
  1558. to bridge those differences. What are the differences between \LangVar{}
  1559. and x86 assembly? Here are some of the most important ones:
  1560. \begin{enumerate}
  1561. \item[(a)] x86 arithmetic instructions typically have two arguments
  1562. and update the second argument in place. In contrast, \LangVar{}
  1563. arithmetic operations take two arguments and produce a new value.
  1564. An x86 instruction may have at most one memory-accessing argument.
  1565. Furthermore, some instructions place special restrictions on their
  1566. arguments.
  1567. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1568. expression, whereas x86 instructions restrict their arguments to be
  1569. integer constants, registers, and memory locations.
  1570. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1571. sequence of instructions and jumps to labeled positions, whereas in
  1572. \LangVar{} the order of evaluation is a left-to-right depth-first
  1573. traversal of the abstract syntax tree.
  1574. \item[(d)] A program in \LangVar{} can have any number of variables
  1575. whereas x86 has 16 registers and the procedure calls stack.
  1576. \item[(e)] Variables in \LangVar{} can shadow other variables with the
  1577. same name. In x86, registers have unique names and memory locations
  1578. have unique addresses.
  1579. \end{enumerate}
  1580. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1581. the problem into several steps, dealing with the above differences one
  1582. at a time. Each of these steps is called a \emph{pass} of the
  1583. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  1584. %
  1585. This terminology comes from the way each step passes over the AST of
  1586. the program.
  1587. %
  1588. We begin by sketching how we might implement each pass, and give them
  1589. names. We then figure out an ordering of the passes and the
  1590. input/output language for each pass. The very first pass has
  1591. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1592. its output language. In between we can choose whichever language is
  1593. most convenient for expressing the output of each pass, whether that
  1594. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1595. our own design. Finally, to implement each pass we write one
  1596. recursive function per non-terminal in the grammar of the input
  1597. language of the pass. \index{subject}{intermediate language}
  1598. \begin{description}
  1599. \item[\key{select-instructions}] handles the difference between
  1600. \LangVar{} operations and x86 instructions. This pass converts each
  1601. \LangVar{} operation to a short sequence of instructions that
  1602. accomplishes the same task.
  1603. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1604. a primitive operation is a variable or integer, that is, an
  1605. \emph{atomic} expression. We refer to non-atomic expressions as
  1606. \emph{complex}. This pass introduces temporary variables to hold
  1607. the results of complex subexpressions.\index{subject}{atomic
  1608. expression}\index{subject}{complex expression}%
  1609. \footnote{The subexpressions of an operation are often called
  1610. operators and operands which explains the presence of
  1611. \code{opera*} in the name of this pass.}
  1612. \item[\key{explicate-control}] makes the execution order of the
  1613. program explicit. It convert the abstract syntax tree representation
  1614. into a control-flow graph in which each node contains a sequence of
  1615. statements and the edges between nodes say which nodes contain jumps
  1616. to other nodes.
  1617. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1618. registers or stack locations in x86.
  1619. \item[\key{uniquify}] deals with the shadowing of variables by
  1620. renaming every variable to a unique name.
  1621. \end{description}
  1622. The next question is: in what order should we apply these passes? This
  1623. question can be challenging because it is difficult to know ahead of
  1624. time which orderings will be better (easier to implement, produce more
  1625. efficient code, etc.) so oftentimes trial-and-error is
  1626. involved. Nevertheless, we can try to plan ahead and make educated
  1627. choices regarding the ordering.
  1628. What should be the ordering of \key{explicate-control} with respect to
  1629. \key{uniquify}? The \key{uniquify} pass should come first because
  1630. \key{explicate-control} changes all the \key{let}-bound variables to
  1631. become local variables whose scope is the entire program, which would
  1632. confuse variables with the same name.
  1633. %
  1634. We place \key{remove-complex-opera*} before \key{explicate-control}
  1635. because the later removes the \key{let} form, but it is convenient to
  1636. use \key{let} in the output of \key{remove-complex-opera*}.
  1637. %
  1638. The ordering of \key{uniquify} with respect to
  1639. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1640. \key{uniquify} to come first.
  1641. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1642. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  1643. learn that, in x86, registers are used for passing arguments to
  1644. functions and it is preferable to assign parameters to their
  1645. corresponding registers. On the other hand, by selecting instructions
  1646. first we may run into a dead end in \key{assign-homes}. Recall that
  1647. only one argument of an x86 instruction may be a memory access but
  1648. \key{assign-homes} might fail to assign even one of them to a
  1649. register.
  1650. %
  1651. A sophisticated approach is to iteratively repeat the two passes until
  1652. a solution is found. However, to reduce implementation complexity we
  1653. recommend a simpler approach in which \key{select-instructions} comes
  1654. first, followed by the \key{assign-homes}, then a third pass named
  1655. \key{patch-instructions} that uses a reserved register to fix
  1656. outstanding problems.
  1657. \begin{figure}[tbp]
  1658. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1659. \node (Rvar) at (0,2) {\large \LangVar{}};
  1660. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1661. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1662. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1663. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1664. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1665. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1666. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1667. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1668. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1669. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1670. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1671. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1672. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1673. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1674. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1675. \end{tikzpicture}
  1676. \caption{Diagram of the passes for compiling \LangVar{}. }
  1677. \label{fig:Rvar-passes}
  1678. \end{figure}
  1679. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1680. passes and identifies the input and output language of each pass. The
  1681. last pass, \key{print-x86}, converts from the abstract syntax of
  1682. \LangXInt{} to the concrete syntax. In the following two sections
  1683. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1684. dialect of x86. The remainder of this chapter gives hints regarding
  1685. the implementation of each of the compiler passes in
  1686. Figure~\ref{fig:Rvar-passes}.
  1687. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1688. %% are programs that are still in the \LangVar{} language, though the
  1689. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1690. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1691. %% %
  1692. %% The output of \key{explicate-control} is in an intermediate language
  1693. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1694. %% syntax, which we introduce in the next section. The
  1695. %% \key{select-instruction} pass translates from \LangCVar{} to
  1696. %% \LangXVar{}. The \key{assign-homes} and
  1697. %% \key{patch-instructions}
  1698. %% passes input and output variants of x86 assembly.
  1699. \subsection{The \LangCVar{} Intermediate Language}
  1700. The output of \key{explicate-control} is similar to the $C$
  1701. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1702. categories for expressions and statements, so we name it \LangCVar{}. The
  1703. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1704. (The concrete syntax for \LangCVar{} is in the Appendix,
  1705. Figure~\ref{fig:c0-concrete-syntax}.)
  1706. %
  1707. The \LangCVar{} language supports the same operators as \LangVar{} but
  1708. the arguments of operators are restricted to atomic
  1709. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1710. assignment statements which can be executed in sequence using the
  1711. \key{Seq} form. A sequence of statements always ends with
  1712. \key{Return}, a guarantee that is baked into the grammar rules for
  1713. \itm{tail}. The naming of this non-terminal comes from the term
  1714. \emph{tail position}\index{subject}{tail position}, which refers to an
  1715. expression that is the last one to execute within a function.
  1716. A \LangCVar{} program consists of a control-flow graph represented as
  1717. an alist mapping labels to tails. This is more general than necessary
  1718. for the present chapter, as we do not yet introduce \key{goto} for
  1719. jumping to labels, but it saves us from having to change the syntax in
  1720. Chapter~\ref{ch:Rif}. For now there will be just one label,
  1721. \key{start}, and the whole program is its tail.
  1722. %
  1723. The $\itm{info}$ field of the \key{CProgram} form, after the
  1724. \key{explicate-control} pass, contains a mapping from the symbol
  1725. \key{locals} to a list of variables, that is, a list of all the
  1726. variables used in the program. At the start of the program, these
  1727. variables are uninitialized; they become initialized on their first
  1728. assignment.
  1729. \begin{figure}[tbp]
  1730. \fbox{
  1731. \begin{minipage}{0.96\textwidth}
  1732. \[
  1733. \begin{array}{lcl}
  1734. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1735. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1736. &\mid& \ADD{\Atm}{\Atm}\\
  1737. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1738. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1739. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1740. \end{array}
  1741. \]
  1742. \end{minipage}
  1743. }
  1744. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1745. \label{fig:c0-syntax}
  1746. \end{figure}
  1747. The definitional interpreter for \LangCVar{} is in the support code,
  1748. in the file \code{interp-Cvar.rkt}.
  1749. \subsection{The \LangXVar{} dialect}
  1750. The \LangXVar{} language is the output of the pass
  1751. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  1752. number of program-scope variables and removes the restrictions
  1753. regarding instruction arguments.
  1754. \section{Uniquify Variables}
  1755. \label{sec:uniquify-Rvar}
  1756. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1757. programs in which every \key{let} binds a unique variable name. For
  1758. example, the \code{uniquify} pass should translate the program on the
  1759. left into the program on the right.
  1760. \begin{transformation}
  1761. \begin{lstlisting}
  1762. (let ([x 32])
  1763. (+ (let ([x 10]) x) x))
  1764. \end{lstlisting}
  1765. \compilesto
  1766. \begin{lstlisting}
  1767. (let ([x.1 32])
  1768. (+ (let ([x.2 10]) x.2) x.1))
  1769. \end{lstlisting}
  1770. \end{transformation}
  1771. The following is another example translation, this time of a program
  1772. with a \key{let} nested inside the initializing expression of another
  1773. \key{let}.
  1774. \begin{transformation}
  1775. \begin{lstlisting}
  1776. (let ([x (let ([x 4])
  1777. (+ x 1))])
  1778. (+ x 2))
  1779. \end{lstlisting}
  1780. \compilesto
  1781. \begin{lstlisting}
  1782. (let ([x.2 (let ([x.1 4])
  1783. (+ x.1 1))])
  1784. (+ x.2 2))
  1785. \end{lstlisting}
  1786. \end{transformation}
  1787. We recommend implementing \code{uniquify} by creating a structurally
  1788. recursive function named \code{uniquify-exp} that mostly just copies
  1789. an expression. However, when encountering a \key{let}, it should
  1790. generate a unique name for the variable and associate the old name
  1791. with the new name in an alist.\footnote{The Racket function
  1792. \code{gensym} is handy for generating unique variable names.} The
  1793. \code{uniquify-exp} function needs to access this alist when it gets
  1794. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1795. for the alist.
  1796. The skeleton of the \code{uniquify-exp} function is shown in
  1797. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1798. convenient to partially apply it to an alist and then apply it to
  1799. different expressions, as in the last case for primitive operations in
  1800. Figure~\ref{fig:uniquify-Rvar}. The
  1801. %
  1802. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1803. %
  1804. form of Racket is useful for transforming each element of a list to
  1805. produce a new list.\index{subject}{for/list}
  1806. \begin{figure}[tbp]
  1807. \begin{lstlisting}
  1808. (define (uniquify-exp env)
  1809. (lambda (e)
  1810. (match e
  1811. [(Var x) ___]
  1812. [(Int n) (Int n)]
  1813. [(Let x e body) ___]
  1814. [(Prim op es)
  1815. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1816. (define (uniquify p)
  1817. (match p
  1818. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1819. \end{lstlisting}
  1820. \caption{Skeleton for the \key{uniquify} pass.}
  1821. \label{fig:uniquify-Rvar}
  1822. \end{figure}
  1823. \begin{exercise}
  1824. \normalfont % I don't like the italics for exercises. -Jeremy
  1825. Complete the \code{uniquify} pass by filling in the blanks in
  1826. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  1827. variables and for the \key{let} form in the file \code{compiler.rkt}
  1828. in the support code.
  1829. \end{exercise}
  1830. \begin{exercise}
  1831. \normalfont % I don't like the italics for exercises. -Jeremy
  1832. \label{ex:Rvar}
  1833. Create five \LangVar{} programs that exercise the most interesting
  1834. parts of the \key{uniquify} pass, that is, the programs should include
  1835. \key{let} forms, variables, and variables that shadow each other.
  1836. The five programs should be placed in the subdirectory named
  1837. \key{tests} and the file names should start with \code{var\_test\_}
  1838. followed by a unique integer and end with the file extension
  1839. \key{.rkt}.
  1840. %
  1841. The \key{run-tests.rkt} script in the support code checks whether the
  1842. output programs produce the same result as the input programs. The
  1843. script uses the \key{interp-tests} function
  1844. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1845. your \key{uniquify} pass on the example programs. The \code{passes}
  1846. parameter of \key{interp-tests} is a list that should have one entry
  1847. for each pass in your compiler. For now, define \code{passes} to
  1848. contain just one entry for \code{uniquify} as shown below.
  1849. \begin{lstlisting}
  1850. (define passes
  1851. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  1852. \end{lstlisting}
  1853. Run the \key{run-tests.rkt} script in the support code to check
  1854. whether the output programs produce the same result as the input
  1855. programs.
  1856. \end{exercise}
  1857. \section{Remove Complex Operands}
  1858. \label{sec:remove-complex-opera-Rvar}
  1859. The \code{remove-complex-opera*} pass compiles \LangVar{} programs
  1860. into a restricted form in which the arguments of operations are atomic
  1861. expressions. Put another way, this pass removes complex
  1862. operands\index{subject}{complex operand}, such as the expression \code{(- 10)}
  1863. in the program below. This is accomplished by introducing a new
  1864. \key{let}-bound variable, binding the complex operand to the new
  1865. variable, and then using the new variable in place of the complex
  1866. operand, as shown in the output of \code{remove-complex-opera*} on the
  1867. right.
  1868. \begin{transformation}
  1869. % var_test_19.rkt
  1870. \begin{lstlisting}
  1871. (let ([x (+ 42 (- 10))])
  1872. (+ x 10))
  1873. \end{lstlisting}
  1874. \compilesto
  1875. \begin{lstlisting}
  1876. (let ([x (let ([tmp.1 (- 10)])
  1877. (+ 42 tmp.1))])
  1878. (+ x 10))
  1879. \end{lstlisting}
  1880. \end{transformation}
  1881. \begin{figure}[tp]
  1882. \centering
  1883. \fbox{
  1884. \begin{minipage}{0.96\textwidth}
  1885. \[
  1886. \begin{array}{rcl}
  1887. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1888. \Exp &::=& \Atm \mid \READ{} \\
  1889. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1890. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1891. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1892. \end{array}
  1893. \]
  1894. \end{minipage}
  1895. }
  1896. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  1897. atomic expressions, like administrative normal form (ANF).}
  1898. \label{fig:Rvar-anf-syntax}
  1899. \end{figure}
  1900. Figure~\ref{fig:Rvar-anf-syntax} presents the grammar for the output of
  1901. this pass, the language \LangVarANF{}. The only difference is that
  1902. operator arguments are restricted to be atomic expressions that are
  1903. defined by the \Atm{} non-terminal. In particular, integer constants
  1904. and variables are atomic. In the literature, restricting arguments to
  1905. be atomic expressions is one of the ideas in \emph{administrative
  1906. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1907. \index{subject}{administrative normal form} \index{subject}{ANF}
  1908. We recommend implementing this pass with two mutually recursive
  1909. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1910. \code{rco-atom} to subexpressions that need to become atomic and to
  1911. apply \code{rco-exp} to subexpressions that do not. Both functions
  1912. take an \LangVar{} expression as input. The \code{rco-exp} function
  1913. returns an expression. The \code{rco-atom} function returns two
  1914. things: an atomic expression and an alist mapping temporary variables to
  1915. complex subexpressions. You can return multiple things from a function
  1916. using Racket's \key{values} form and you can receive multiple things
  1917. from a function call using the \key{define-values} form.
  1918. Also, the
  1919. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1920. form is useful for applying a function to each element of a list, in
  1921. the case where the function returns multiple values.
  1922. \index{subject}{for/lists}
  1923. Returning to the example program with the expression \code{(+ 42 (-
  1924. 10))}, the subexpression \code{(- 10)} should be processed using the
  1925. \code{rco-atom} function because it is an argument of the \code{+} and
  1926. therefore needs to become atomic. The output of \code{rco-atom}
  1927. applied to \code{(- 10)} is as follows.
  1928. \begin{transformation}
  1929. \begin{lstlisting}
  1930. (- 10)
  1931. \end{lstlisting}
  1932. \compilesto
  1933. \begin{lstlisting}
  1934. tmp.1
  1935. ((tmp.1 . (- 10)))
  1936. \end{lstlisting}
  1937. \end{transformation}
  1938. Take special care of programs such as the following that bind a
  1939. variable to an atomic expression. You should leave such variable
  1940. bindings unchanged, as shown in the program on the right \\
  1941. \begin{transformation}
  1942. % var_test_20.rkt
  1943. \begin{lstlisting}
  1944. (let ([a 42])
  1945. (let ([b a])
  1946. b))
  1947. \end{lstlisting}
  1948. \compilesto
  1949. \begin{lstlisting}
  1950. (let ([a 42])
  1951. (let ([b a])
  1952. b))
  1953. \end{lstlisting}
  1954. \end{transformation}
  1955. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1956. produce the following output with unnecessary temporary variables.
  1957. \begin{center}
  1958. \begin{minipage}{0.4\textwidth}
  1959. \begin{lstlisting}
  1960. (let ([tmp.1 42])
  1961. (let ([a tmp.1])
  1962. (let ([tmp.2 a])
  1963. (let ([b tmp.2])
  1964. b))))
  1965. \end{lstlisting}
  1966. \end{minipage}
  1967. \end{center}
  1968. \begin{exercise}
  1969. \normalfont
  1970. Implement the \code{remove-complex-opera*} function in
  1971. \code{compiler.rkt}.
  1972. %
  1973. Create three new \LangVar{} programs that exercise the interesting
  1974. code in the \code{remove-complex-opera*} pass. Follow the guidelines
  1975. regarding file names described in Exercise~\ref{ex:Rvar}.
  1976. %
  1977. In the \code{run-tests.rkt} script, add the following entry to the
  1978. list of \code{passes} and then run the script to test your compiler.
  1979. \begin{lstlisting}
  1980. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  1981. \end{lstlisting}
  1982. While debugging your compiler, it is often useful to see the
  1983. intermediate programs that are output from each pass. To print the
  1984. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  1985. \code{interp-tests} in \code{run-tests.rkt}.
  1986. \end{exercise}
  1987. \section{Explicate Control}
  1988. \label{sec:explicate-control-Rvar}
  1989. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  1990. programs that make the order of execution explicit in their
  1991. syntax. For now this amounts to flattening \key{let} constructs into a
  1992. sequence of assignment statements. For example, consider the following
  1993. \LangVar{} program.\\
  1994. % var_test_11.rkt
  1995. \begin{minipage}{0.96\textwidth}
  1996. \begin{lstlisting}
  1997. (let ([y (let ([x 20])
  1998. (+ x (let ([x 22]) x)))])
  1999. y)
  2000. \end{lstlisting}
  2001. \end{minipage}\\
  2002. %
  2003. The output of the previous pass and of \code{explicate-control} is
  2004. shown below. Recall that the right-hand-side of a \key{let} executes
  2005. before its body, so the order of evaluation for this program is to
  2006. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2007. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2008. output of \code{explicate-control} makes this ordering explicit.
  2009. \begin{transformation}
  2010. \begin{lstlisting}
  2011. (let ([y (let ([x.1 20])
  2012. (let ([x.2 22])
  2013. (+ x.1 x.2)))])
  2014. y)
  2015. \end{lstlisting}
  2016. \compilesto
  2017. \begin{lstlisting}[language=C]
  2018. start:
  2019. x.1 = 20;
  2020. x.2 = 22;
  2021. y = (+ x.1 x.2);
  2022. return y;
  2023. \end{lstlisting}
  2024. \end{transformation}
  2025. \begin{figure}[tbp]
  2026. \begin{lstlisting}
  2027. (define (explicate-tail e)
  2028. (match e
  2029. [(Var x) ___]
  2030. [(Int n) (Return (Int n))]
  2031. [(Let x rhs body) ___]
  2032. [(Prim op es) ___]
  2033. [else (error "explicate-tail unhandled case" e)]))
  2034. (define (explicate-assign e x cont)
  2035. (match e
  2036. [(Var x) ___]
  2037. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2038. [(Let y rhs body) ___]
  2039. [(Prim op es) ___]
  2040. [else (error "explicate-assign unhandled case" e)]))
  2041. (define (explicate-control p)
  2042. (match p
  2043. [(Program info body) ___]))
  2044. \end{lstlisting}
  2045. \caption{Skeleton for the \key{explicate-control} pass.}
  2046. \label{fig:explicate-control-Rvar}
  2047. \end{figure}
  2048. The organization of this pass depends on the notion of tail position
  2049. that we have alluded to earlier.
  2050. \begin{definition}
  2051. The following rules define when an expression is in \textbf{\emph{tail
  2052. position}}\index{subject}{tail position} for the language \LangVar{}.
  2053. \begin{enumerate}
  2054. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2055. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2056. \end{enumerate}
  2057. \end{definition}
  2058. We recommend implementing \code{explicate-control} using two mutually
  2059. recursive functions, \code{explicate-tail} and
  2060. \code{explicate-assign}, as suggested in the skeleton code in
  2061. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2062. function should be applied to expressions in tail position whereas the
  2063. \code{explicate-assign} should be applied to expressions that occur on
  2064. the right-hand-side of a \key{let}.
  2065. %
  2066. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2067. input and produces a \Tail{} in \LangCVar{} (see
  2068. Figure~\ref{fig:c0-syntax}).
  2069. %
  2070. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2071. the variable that it is to be assigned to, and a \Tail{} in
  2072. \LangCVar{} for the code that comes after the assignment. The
  2073. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2074. The \code{explicate-assign} function is in accumulator-passing style:
  2075. the \code{cont} parameter is used for accumulating the output. This
  2076. accumulator-passing style plays an important role in how we generate
  2077. high-quality code for conditional expressions in Chapter~\ref{ch:Rif}.
  2078. \begin{exercise}\normalfont
  2079. %
  2080. Implement the \code{explicate-control} function in
  2081. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2082. exercise the code in \code{explicate-control}.
  2083. %
  2084. In the \code{run-tests.rkt} script, add the following entry to the
  2085. list of \code{passes} and then run the script to test your compiler.
  2086. \begin{lstlisting}
  2087. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2088. \end{lstlisting}
  2089. \end{exercise}
  2090. \section{Select Instructions}
  2091. \label{sec:select-Rvar}
  2092. \index{subject}{instruction selection}
  2093. In the \code{select-instructions} pass we begin the work of
  2094. translating from \LangCVar{} to \LangXVar{}. The target language of
  2095. this pass is a variant of x86 that still uses variables, so we add an
  2096. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2097. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2098. recommend implementing the \code{select-instructions} with
  2099. three auxiliary functions, one for each of the non-terminals of
  2100. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2101. The cases for $\Atm$ are straightforward; variables stay
  2102. the same and integer constants are changed to immediates:
  2103. $\INT{n}$ changes to $\IMM{n}$.
  2104. Next we consider the cases for $\Stmt$, starting with arithmetic
  2105. operations. For example, consider the addition operation. We can use
  2106. the \key{addq} instruction, but it performs an in-place update. So we
  2107. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2108. add $\itm{arg}_2$ to \itm{var}.
  2109. \begin{transformation}
  2110. \begin{lstlisting}
  2111. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2112. \end{lstlisting}
  2113. \compilesto
  2114. \begin{lstlisting}
  2115. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2116. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2117. \end{lstlisting}
  2118. \end{transformation}
  2119. There are also cases that require special care to avoid generating
  2120. needlessly complicated code. For example, if one of the arguments of
  2121. the addition is the same variable as the left-hand side of the
  2122. assignment, then there is no need for the extra move instruction. The
  2123. assignment statement can be translated into a single \key{addq}
  2124. instruction as follows.
  2125. \begin{transformation}
  2126. \begin{lstlisting}
  2127. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2128. \end{lstlisting}
  2129. \compilesto
  2130. \begin{lstlisting}
  2131. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2132. \end{lstlisting}
  2133. \end{transformation}
  2134. The \key{read} operation does not have a direct counterpart in x86
  2135. assembly, so we provide this functionality with the function
  2136. \code{read\_int} in the file \code{runtime.c}, written in
  2137. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2138. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  2139. system}, or simply the \emph{runtime} for short. When compiling your
  2140. generated x86 assembly code, you need to compile \code{runtime.c} to
  2141. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2142. \code{-c}) and link it into the executable. For our purposes of code
  2143. generation, all you need to do is translate an assignment of
  2144. \key{read} into a call to the \code{read\_int} function followed by a
  2145. move from \code{rax} to the left-hand-side variable. (Recall that the
  2146. return value of a function goes into \code{rax}.)
  2147. \begin{transformation}
  2148. \begin{lstlisting}
  2149. |$\itm{var}$| = (read);
  2150. \end{lstlisting}
  2151. \compilesto
  2152. \begin{lstlisting}
  2153. callq read_int
  2154. movq %rax, |$\itm{var}$|
  2155. \end{lstlisting}
  2156. \end{transformation}
  2157. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2158. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2159. assignment to the \key{rax} register followed by a jump to the
  2160. conclusion of the program (so the conclusion needs to be labeled).
  2161. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2162. recursively and then append the resulting instructions.
  2163. \begin{exercise}
  2164. \normalfont Implement the \key{select-instructions} pass in
  2165. \code{compiler.rkt}. Create three new example programs that are
  2166. designed to exercise all of the interesting cases in this pass.
  2167. %
  2168. In the \code{run-tests.rkt} script, add the following entry to the
  2169. list of \code{passes} and then run the script to test your compiler.
  2170. \begin{lstlisting}
  2171. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2172. \end{lstlisting}
  2173. \end{exercise}
  2174. \section{Assign Homes}
  2175. \label{sec:assign-Rvar}
  2176. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2177. \LangXVar{} programs that no longer use program variables.
  2178. Thus, the \key{assign-homes} pass is responsible for placing all of
  2179. the program variables in registers or on the stack. For runtime
  2180. efficiency, it is better to place variables in registers, but as there
  2181. are only 16 registers, some programs must necessarily resort to
  2182. placing some variables on the stack. In this chapter we focus on the
  2183. mechanics of placing variables on the stack. We study an algorithm for
  2184. placing variables in registers in
  2185. Chapter~\ref{ch:register-allocation-Rvar}.
  2186. Consider again the following \LangVar{} program from
  2187. Section~\ref{sec:remove-complex-opera-Rvar}.
  2188. % var_test_20.rkt
  2189. \begin{lstlisting}
  2190. (let ([a 42])
  2191. (let ([b a])
  2192. b))
  2193. \end{lstlisting}
  2194. The output of \code{select-instructions} is shown on the left and the
  2195. output of \code{assign-homes} on the right. In this example, we
  2196. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2197. variable \code{b} to location \code{-16(\%rbp)}.
  2198. \begin{transformation}
  2199. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2200. locals-types:
  2201. a : Integer, b : Integer
  2202. start:
  2203. movq $42, a
  2204. movq a, b
  2205. movq b, %rax
  2206. jmp conclusion
  2207. \end{lstlisting}
  2208. \compilesto
  2209. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2210. stack-space: 16
  2211. start:
  2212. movq $42, -8(%rbp)
  2213. movq -8(%rbp), -16(%rbp)
  2214. movq -16(%rbp), %rax
  2215. jmp conclusion
  2216. \end{lstlisting}
  2217. \end{transformation}
  2218. The \code{locals-types} entry in the $\itm{info}$ of the
  2219. \code{X86Program} node is an alist mapping all the variables in the
  2220. program to their types (for now just \code{Integer}). The
  2221. \code{assign-homes} pass should replace all uses of those variables
  2222. with stack locations. As an aside, the \code{locals-types} entry is
  2223. computed by \code{type-check-Cvar} in the support code, which installs
  2224. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2225. be propagated to the \code{X86Program} node.
  2226. In the process of assigning variables to stack locations, it is
  2227. convenient for you to compute and store the size of the frame (in
  2228. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2229. the key \code{stack-space}, which is needed later to generate the
  2230. conclusion of the \code{main} procedure. The x86-64 standard requires
  2231. the frame size to be a multiple of 16 bytes.\index{subject}{frame}
  2232. \begin{exercise}\normalfont
  2233. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2234. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2235. \Block{}. We recommend that the auxiliary functions take an extra
  2236. parameter that is an alist mapping variable names to homes (stack
  2237. locations for now).
  2238. %
  2239. In the \code{run-tests.rkt} script, add the following entry to the
  2240. list of \code{passes} and then run the script to test your compiler.
  2241. \begin{lstlisting}
  2242. (list "assign homes" assign-homes interp-x86-0)
  2243. \end{lstlisting}
  2244. \end{exercise}
  2245. \section{Patch Instructions}
  2246. \label{sec:patch-s0}
  2247. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2248. \LangXInt{} by making sure that each instruction adheres to the
  2249. restriction that at most one argument of an instruction may be a
  2250. memory reference.
  2251. We return to the following example.\\
  2252. \begin{minipage}{0.5\textwidth}
  2253. % var_test_20.rkt
  2254. \begin{lstlisting}
  2255. (let ([a 42])
  2256. (let ([b a])
  2257. b))
  2258. \end{lstlisting}
  2259. \end{minipage}\\
  2260. The \key{assign-homes} pass produces the following output
  2261. for this program. \\
  2262. \begin{minipage}{0.5\textwidth}
  2263. \begin{lstlisting}
  2264. stack-space: 16
  2265. start:
  2266. movq $42, -8(%rbp)
  2267. movq -8(%rbp), -16(%rbp)
  2268. movq -16(%rbp), %rax
  2269. jmp conclusion
  2270. \end{lstlisting}
  2271. \end{minipage}\\
  2272. The second \key{movq} instruction is problematic because both
  2273. arguments are stack locations. We suggest fixing this problem by
  2274. moving from the source location to the register \key{rax} and then
  2275. from \key{rax} to the destination location, as follows.
  2276. \begin{lstlisting}
  2277. movq -8(%rbp), %rax
  2278. movq %rax, -16(%rbp)
  2279. \end{lstlisting}
  2280. \begin{exercise}
  2281. \normalfont Implement the \key{patch-instructions} pass in
  2282. \code{compiler.rkt}. Create three new example programs that are
  2283. designed to exercise all of the interesting cases in this pass.
  2284. %
  2285. In the \code{run-tests.rkt} script, add the following entry to the
  2286. list of \code{passes} and then run the script to test your compiler.
  2287. \begin{lstlisting}
  2288. (list "patch instructions" patch-instructions interp-x86-0)
  2289. \end{lstlisting}
  2290. \end{exercise}
  2291. \section{Print x86}
  2292. \label{sec:print-x86}
  2293. The last step of the compiler from \LangVar{} to x86 is to convert the
  2294. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2295. string representation (defined in
  2296. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2297. \key{string-append} functions are useful in this regard. The main work
  2298. that this step needs to perform is to create the \key{main} function
  2299. and the standard instructions for its prelude and conclusion, as shown
  2300. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2301. know the amount of space needed for the stack frame, which you can
  2302. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2303. the \key{X86Program} node.
  2304. When running on Mac OS X, you compiler should prefix an underscore to
  2305. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2306. useful for determining which operating system the compiler is running
  2307. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2308. \begin{exercise}\normalfont
  2309. %
  2310. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2311. %
  2312. In the \code{run-tests.rkt} script, add the following entry to the
  2313. list of \code{passes} and then run the script to test your compiler.
  2314. \begin{lstlisting}
  2315. (list "print x86" print-x86 #f)
  2316. \end{lstlisting}
  2317. %
  2318. Uncomment the call to the \key{compiler-tests} function
  2319. (Appendix~\ref{appendix:utilities}), which tests your complete
  2320. compiler by executing the generated x86 code. Compile the provided
  2321. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2322. script to test your compiler.
  2323. \end{exercise}
  2324. \section{Challenge: Partial Evaluator for \LangVar{}}
  2325. \label{sec:pe-Rvar}
  2326. \index{subject}{partial evaluation}
  2327. This section describes optional challenge exercises that involve
  2328. adapting and improving the partial evaluator for \LangInt{} that was
  2329. introduced in Section~\ref{sec:partial-evaluation}.
  2330. \begin{exercise}\label{ex:pe-Rvar}
  2331. \normalfont
  2332. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2333. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2334. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2335. and variables to the \LangInt{} language, so you will need to add cases for
  2336. them in the \code{pe-exp} function. Once complete, add the partial
  2337. evaluation pass to the front of your compiler and make sure that your
  2338. compiler still passes all of the tests.
  2339. \end{exercise}
  2340. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2341. \begin{exercise}
  2342. \normalfont
  2343. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2344. \code{pe-add} auxiliary functions with functions that know more about
  2345. arithmetic. For example, your partial evaluator should translate
  2346. \[
  2347. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2348. \code{(+ 2 (read))}
  2349. \]
  2350. To accomplish this, the \code{pe-exp} function should produce output
  2351. in the form of the $\itm{residual}$ non-terminal of the following
  2352. grammar. The idea is that when processing an addition expression, we
  2353. can always produce either 1) an integer constant, 2) an addition
  2354. expression with an integer constant on the left-hand side but not the
  2355. right-hand side, or 3) or an addition expression in which neither
  2356. subexpression is a constant.
  2357. \[
  2358. \begin{array}{lcl}
  2359. \itm{inert} &::=& \Var
  2360. \mid \LP\key{read}\RP
  2361. \mid \LP\key{-} ~\Var\RP
  2362. \mid \LP\key{-} ~\LP\key{read}\RP\RP
  2363. \mid \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  2364. &\mid& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  2365. \itm{residual} &::=& \Int
  2366. \mid \LP\key{+}~ \Int~ \itm{inert}\RP
  2367. \mid \itm{inert}
  2368. \end{array}
  2369. \]
  2370. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2371. inputs are $\itm{residual}$ expressions and they should return
  2372. $\itm{residual}$ expressions. Once the improvements are complete,
  2373. make sure that your compiler still passes all of the tests. After
  2374. all, fast code is useless if it produces incorrect results!
  2375. \end{exercise}
  2376. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2377. \chapter{Register Allocation}
  2378. \label{ch:register-allocation-Rvar}
  2379. \index{subject}{register allocation}
  2380. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  2381. stack. In this Chapter we learn how to improve the performance of the
  2382. generated code by placing some variables into registers. The CPU can
  2383. access a register in a single cycle, whereas accessing the stack can
  2384. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2385. serves as a running example. The source program is on the left and the
  2386. output of instruction selection is on the right. The program is almost
  2387. in the x86 assembly language but it still uses variables.
  2388. \begin{figure}
  2389. \begin{minipage}{0.45\textwidth}
  2390. Example \LangVar{} program:
  2391. % var_test_28.rkt
  2392. \begin{lstlisting}
  2393. (let ([v 1])
  2394. (let ([w 42])
  2395. (let ([x (+ v 7)])
  2396. (let ([y x])
  2397. (let ([z (+ x w)])
  2398. (+ z (- y)))))))
  2399. \end{lstlisting}
  2400. \end{minipage}
  2401. \begin{minipage}{0.45\textwidth}
  2402. After instruction selection:
  2403. \begin{lstlisting}
  2404. locals-types:
  2405. x : Integer, y : Integer,
  2406. z : Integer, t : Integer,
  2407. v : Integer, w : Integer
  2408. start:
  2409. movq $1, v
  2410. movq $42, w
  2411. movq v, x
  2412. addq $7, x
  2413. movq x, y
  2414. movq x, z
  2415. addq w, z
  2416. movq y, t
  2417. negq t
  2418. movq z, %rax
  2419. addq t, %rax
  2420. jmp conclusion
  2421. \end{lstlisting}
  2422. \end{minipage}
  2423. \caption{A running example for register allocation.}
  2424. \label{fig:reg-eg}
  2425. \end{figure}
  2426. The goal of register allocation is to fit as many variables into
  2427. registers as possible. Some programs have more variables than
  2428. registers so we cannot always map each variable to a different
  2429. register. Fortunately, it is common for different variables to be
  2430. needed during different periods of time during program execution, and
  2431. in such cases several variables can be mapped to the same register.
  2432. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2433. After the variable \code{x} is moved to \code{z} it is no longer
  2434. needed. Variable \code{z}, on the other hand, is used only after this
  2435. point, so \code{x} and \code{z} could share the same register. The
  2436. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2437. where a variable is needed. Once we have that information, we compute
  2438. which variables are needed at the same time, i.e., which ones
  2439. \emph{interfere} with each other, and represent this relation as an
  2440. undirected graph whose vertices are variables and edges indicate when
  2441. two variables interfere (Section~\ref{sec:build-interference}). We
  2442. then model register allocation as a graph coloring problem
  2443. (Section~\ref{sec:graph-coloring}).
  2444. If we run out of registers despite these efforts, we place the
  2445. remaining variables on the stack, similar to what we did in
  2446. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  2447. for assigning a variable to a stack location. The decision to spill a
  2448. variable is handled as part of the graph coloring process
  2449. (Section~\ref{sec:graph-coloring}).
  2450. We make the simplifying assumption that each variable is assigned to
  2451. one location (a register or stack address). A more sophisticated
  2452. approach is to assign a variable to one or more locations in different
  2453. regions of the program. For example, if a variable is used many times
  2454. in short sequence and then only used again after many other
  2455. instructions, it could be more efficient to assign the variable to a
  2456. register during the initial sequence and then move it to the stack for
  2457. the rest of its lifetime. We refer the interested reader to
  2458. \citet{Cooper:2011aa} for more information about that approach.
  2459. % discuss prioritizing variables based on how much they are used.
  2460. \section{Registers and Calling Conventions}
  2461. \label{sec:calling-conventions}
  2462. \index{subject}{calling conventions}
  2463. As we perform register allocation, we need to be aware of the
  2464. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  2465. functions calls are performed in x86.
  2466. %
  2467. Even though \LangVar{} does not include programmer-defined functions,
  2468. our generated code includes a \code{main} function that is called by
  2469. the operating system and our generated code contains calls to the
  2470. \code{read\_int} function.
  2471. Function calls require coordination between two pieces of code that
  2472. may be written by different programmers or generated by different
  2473. compilers. Here we follow the System V calling conventions that are
  2474. used by the GNU C compiler on Linux and
  2475. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2476. %
  2477. The calling conventions include rules about how functions share the
  2478. use of registers. In particular, the caller is responsible for freeing
  2479. up some registers prior to the function call for use by the callee.
  2480. These are called the \emph{caller-saved registers}
  2481. \index{subject}{caller-saved registers}
  2482. and they are
  2483. \begin{lstlisting}
  2484. rax rcx rdx rsi rdi r8 r9 r10 r11
  2485. \end{lstlisting}
  2486. On the other hand, the callee is responsible for preserving the values
  2487. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  2488. which are
  2489. \begin{lstlisting}
  2490. rsp rbp rbx r12 r13 r14 r15
  2491. \end{lstlisting}
  2492. We can think about this caller/callee convention from two points of
  2493. view, the caller view and the callee view:
  2494. \begin{itemize}
  2495. \item The caller should assume that all the caller-saved registers get
  2496. overwritten with arbitrary values by the callee. On the other hand,
  2497. the caller can safely assume that all the callee-saved registers
  2498. contain the same values after the call that they did before the
  2499. call.
  2500. \item The callee can freely use any of the caller-saved registers.
  2501. However, if the callee wants to use a callee-saved register, the
  2502. callee must arrange to put the original value back in the register
  2503. prior to returning to the caller. This can be accomplished by saving
  2504. the value to the stack in the prelude of the function and restoring
  2505. the value in the conclusion of the function.
  2506. \end{itemize}
  2507. In x86, registers are also used for passing arguments to a function
  2508. and for the return value. In particular, the first six arguments to a
  2509. function are passed in the following six registers, in this order.
  2510. \begin{lstlisting}
  2511. rdi rsi rdx rcx r8 r9
  2512. \end{lstlisting}
  2513. If there are more than six arguments, then the convention is to use
  2514. space on the frame of the caller for the rest of the
  2515. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  2516. need more than six arguments. For now, the only function we care about
  2517. is \code{read\_int} and it takes zero arguments.
  2518. %
  2519. The register \code{rax} is used for the return value of a function.
  2520. The next question is how these calling conventions impact register
  2521. allocation. Consider the \LangVar{} program in
  2522. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2523. example from the caller point of view and then from the callee point
  2524. of view.
  2525. The program makes two calls to the \code{read} function. Also, the
  2526. variable \code{x} is in use during the second call to \code{read}, so
  2527. we need to make sure that the value in \code{x} does not get
  2528. accidentally wiped out by the call to \code{read}. One obvious
  2529. approach is to save all the values in caller-saved registers to the
  2530. stack prior to each function call, and restore them after each
  2531. call. That way, if the register allocator chooses to assign \code{x}
  2532. to a caller-saved register, its value will be preserved across the
  2533. call to \code{read}. However, saving and restoring to the stack is
  2534. relatively slow. If \code{x} is not used many times, it may be better
  2535. to assign \code{x} to a stack location in the first place. Or better
  2536. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2537. register, then it won't need to be saved and restored during function
  2538. calls.
  2539. The approach that we recommend for variables that are in use during a
  2540. function call is to either assign them to callee-saved registers or to
  2541. spill them to the stack. On the other hand, for variables that are not
  2542. in use during a function call, we try the following alternatives in
  2543. order 1) look for an available caller-saved register (to leave room
  2544. for other variables in the callee-saved register), 2) look for a
  2545. callee-saved register, and 3) spill the variable to the stack.
  2546. It is straightforward to implement this approach in a graph coloring
  2547. register allocator. First, we know which variables are in use during
  2548. every function call because we compute that information for every
  2549. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  2550. build the interference graph (Section~\ref{sec:build-interference}),
  2551. we can place an edge between each of these variables and the
  2552. caller-saved registers in the interference graph. This will prevent
  2553. the graph coloring algorithm from assigning those variables to
  2554. caller-saved registers.
  2555. Returning to the example in
  2556. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2557. generated x86 code on the right-hand side, focusing on the
  2558. \code{start} block. Notice that variable \code{x} is assigned to
  2559. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2560. place during the second call to \code{read\_int}. Next, notice that
  2561. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2562. because there are no function calls in the remainder of the block.
  2563. Next we analyze the example from the callee point of view, focusing on
  2564. the prelude and conclusion of the \code{main} function. As usual the
  2565. prelude begins with saving the \code{rbp} register to the stack and
  2566. setting the \code{rbp} to the current stack pointer. We now know why
  2567. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2568. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2569. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2570. (\code{x}). The other callee-saved registers are not saved in the
  2571. prelude because they are not used. The prelude subtracts 8 bytes from
  2572. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2573. \code{start} block. Shifting attention to the \code{conclusion}, we
  2574. see that \code{rbx} is restored from the stack with a \code{popq}
  2575. instruction. \index{subject}{prelude}\index{subject}{conclusion}
  2576. \begin{figure}[tp]
  2577. \begin{minipage}{0.45\textwidth}
  2578. Example \LangVar{} program:
  2579. %var_test_14.rkt
  2580. \begin{lstlisting}
  2581. (let ([x (read)])
  2582. (let ([y (read)])
  2583. (+ (+ x y) 42)))
  2584. \end{lstlisting}
  2585. \end{minipage}
  2586. \begin{minipage}{0.45\textwidth}
  2587. Generated x86 assembly:
  2588. \begin{lstlisting}
  2589. start:
  2590. callq read_int
  2591. movq %rax, %rbx
  2592. callq read_int
  2593. movq %rax, %rcx
  2594. addq %rcx, %rbx
  2595. movq %rbx, %rax
  2596. addq $42, %rax
  2597. jmp _conclusion
  2598. .globl main
  2599. main:
  2600. pushq %rbp
  2601. movq %rsp, %rbp
  2602. pushq %rbx
  2603. subq $8, %rsp
  2604. jmp start
  2605. conclusion:
  2606. addq $8, %rsp
  2607. popq %rbx
  2608. popq %rbp
  2609. retq
  2610. \end{lstlisting}
  2611. \end{minipage}
  2612. \caption{An example with function calls.}
  2613. \label{fig:example-calling-conventions}
  2614. \end{figure}
  2615. %\clearpage
  2616. \section{Liveness Analysis}
  2617. \label{sec:liveness-analysis-Rvar}
  2618. \index{subject}{liveness analysis}
  2619. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2620. is, it discovers which variables are in-use in different regions of a
  2621. program.
  2622. %
  2623. A variable or register is \emph{live} at a program point if its
  2624. current value is used at some later point in the program. We
  2625. refer to variables and registers collectively as \emph{locations}.
  2626. %
  2627. Consider the following code fragment in which there are two writes to
  2628. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2629. \begin{center}
  2630. \begin{minipage}{0.96\textwidth}
  2631. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2632. movq $5, a
  2633. movq $30, b
  2634. movq a, c
  2635. movq $10, b
  2636. addq b, c
  2637. \end{lstlisting}
  2638. \end{minipage}
  2639. \end{center}
  2640. The answer is no because \code{a} is live from line 1 to 3 and
  2641. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2642. line 2 is never used because it is overwritten (line 4) before the
  2643. next read (line 5).
  2644. The live locations can be computed by traversing the instruction
  2645. sequence back to front (i.e., backwards in execution order). Let
  2646. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2647. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2648. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2649. locations before instruction $I_k$. We recommend represeting these
  2650. sets with the Racket \code{set} data structure described in
  2651. Figure~\ref{fig:set}.
  2652. \begin{figure}[tp]
  2653. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  2654. \small
  2655. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2656. A \emph{set} is an unordered collection of elements without duplicates.
  2657. Here are some of the operations defined on sets.
  2658. \index{subject}{set}
  2659. \begin{description}
  2660. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  2661. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  2662. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  2663. difference of the two sets.
  2664. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  2665. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  2666. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  2667. \end{description}
  2668. \end{tcolorbox}
  2669. %\end{wrapfigure}
  2670. \caption{The \code{set} data structure.}
  2671. \label{fig:set}
  2672. \end{figure}
  2673. The live locations after an instruction are always the same as the
  2674. live locations before the next instruction.
  2675. \index{subject}{live-after} \index{subject}{live-before}
  2676. \begin{equation} \label{eq:live-after-before-next}
  2677. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2678. \end{equation}
  2679. To start things off, there are no live locations after the last
  2680. instruction, so
  2681. \begin{equation}\label{eq:live-last-empty}
  2682. L_{\mathsf{after}}(n) = \emptyset
  2683. \end{equation}
  2684. We then apply the following rule repeatedly, traversing the
  2685. instruction sequence back to front.
  2686. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2687. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2688. \end{equation}
  2689. where $W(k)$ are the locations written to by instruction $I_k$ and
  2690. $R(k)$ are the locations read by instruction $I_k$.
  2691. There is a special case for \code{jmp} instructions. The locations
  2692. that are live before a \code{jmp} should be the locations in
  2693. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2694. maintaining an alist named \code{label->live} that maps each label to
  2695. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2696. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2697. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2698. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2699. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2700. Let us walk through the above example, applying these formulas
  2701. starting with the instruction on line 5. We collect the answers in
  2702. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2703. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2704. instruction (formula~\ref{eq:live-last-empty}). The
  2705. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2706. because it reads from variables \code{b} and \code{c}
  2707. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2708. \[
  2709. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2710. \]
  2711. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2712. the live-before set from line 5 to be the live-after set for this
  2713. instruction (formula~\ref{eq:live-after-before-next}).
  2714. \[
  2715. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2716. \]
  2717. This move instruction writes to \code{b} and does not read from any
  2718. variables, so we have the following live-before set
  2719. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2720. \[
  2721. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2722. \]
  2723. The live-before for instruction \code{movq a, c}
  2724. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2725. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2726. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2727. variable that is not live and does not read from a variable.
  2728. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2729. because it writes to variable \code{a}.
  2730. \begin{figure}[tbp]
  2731. \begin{minipage}{0.45\textwidth}
  2732. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2733. movq $5, a
  2734. movq $30, b
  2735. movq a, c
  2736. movq $10, b
  2737. addq b, c
  2738. \end{lstlisting}
  2739. \end{minipage}
  2740. \vrule\hspace{10pt}
  2741. \begin{minipage}{0.45\textwidth}
  2742. \begin{align*}
  2743. L_{\mathsf{before}}(1)= \emptyset,
  2744. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2745. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2746. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2747. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2748. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2749. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2750. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2751. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2752. L_{\mathsf{after}}(5)= \emptyset
  2753. \end{align*}
  2754. \end{minipage}
  2755. \caption{Example output of liveness analysis on a short example.}
  2756. \label{fig:liveness-example-0}
  2757. \end{figure}
  2758. \begin{exercise}\normalfont
  2759. Perform liveness analysis on the running example in
  2760. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2761. sets for each instruction. Compare your answers to the solution
  2762. shown in Figure~\ref{fig:live-eg}.
  2763. \end{exercise}
  2764. \begin{figure}[tp]
  2765. \hspace{20pt}
  2766. \begin{minipage}{0.45\textwidth}
  2767. \begin{lstlisting}
  2768. |$\{\ttm{rsp}\}$|
  2769. movq $1, v
  2770. |$\{\ttm{v},\ttm{rsp}\}$|
  2771. movq $42, w
  2772. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2773. movq v, x
  2774. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2775. addq $7, x
  2776. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2777. movq x, y
  2778. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2779. movq x, z
  2780. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2781. addq w, z
  2782. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2783. movq y, t
  2784. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2785. negq t
  2786. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2787. movq z, %rax
  2788. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2789. addq t, %rax
  2790. |$\{\ttm{rax},\ttm{rsp}\}$|
  2791. jmp conclusion
  2792. \end{lstlisting}
  2793. \end{minipage}
  2794. \caption{The running example annotated with live-after sets.}
  2795. \label{fig:live-eg}
  2796. \end{figure}
  2797. \begin{exercise}\normalfont
  2798. Implement the \code{uncover-live} pass. Store the sequence of
  2799. live-after sets in the $\itm{info}$ field of the \code{Block}
  2800. structure.
  2801. %
  2802. We recommend creating an auxiliary function that takes a list of
  2803. instructions and an initial live-after set (typically empty) and
  2804. returns the list of live-after sets.
  2805. %
  2806. We also recommend creating auxiliary functions to 1) compute the set
  2807. of locations that appear in an \Arg{}, 2) compute the locations read
  2808. by an instruction (the $R$ function), and 3) the locations written by
  2809. an instruction (the $W$ function). The \code{callq} instruction should
  2810. include all of the caller-saved registers in its write-set $W$ because
  2811. the calling convention says that those registers may be written to
  2812. during the function call. Likewise, the \code{callq} instruction
  2813. should include the appropriate argument-passing registers in its
  2814. read-set $R$, depending on the arity of the function being
  2815. called. (This is why the abstract syntax for \code{callq} includes the
  2816. arity.)
  2817. \end{exercise}
  2818. %\clearpage
  2819. \section{Build the Interference Graph}
  2820. \label{sec:build-interference}
  2821. \begin{figure}[tp]
  2822. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  2823. \small
  2824. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2825. A \emph{graph} is a collection of vertices and edges where each
  2826. edge connects two vertices. A graph is \emph{directed} if each
  2827. edge points from a source to a target. Otherwise the graph is
  2828. \emph{undirected}.
  2829. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  2830. \begin{description}
  2831. %% We currently don't use directed graphs. We instead use
  2832. %% directed multi-graphs. -Jeremy
  2833. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2834. directed graph from a list of edges. Each edge is a list
  2835. containing the source and target vertex.
  2836. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2837. undirected graph from a list of edges. Each edge is represented by
  2838. a list containing two vertices.
  2839. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2840. inserts a vertex into the graph.
  2841. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2842. inserts an edge between the two vertices.
  2843. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2844. returns a sequence of vertices adjacent to the vertex.
  2845. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2846. returns a sequence of all vertices in the graph.
  2847. \end{description}
  2848. \end{tcolorbox}
  2849. %\end{wrapfigure}
  2850. \caption{The Racket \code{graph} package.}
  2851. \label{fig:graph}
  2852. \end{figure}
  2853. Based on the liveness analysis, we know where each location is live.
  2854. However, during register allocation, we need to answer questions of
  2855. the specific form: are locations $u$ and $v$ live at the same time?
  2856. (And therefore cannot be assigned to the same register.) To make this
  2857. question more efficient to answer, we create an explicit data
  2858. structure, an \emph{interference graph}\index{subject}{interference
  2859. graph}. An interference graph is an undirected graph that has an
  2860. edge between two locations if they are live at the same time, that is,
  2861. if they interfere with each other. We recommend using the Racket
  2862. \code{graph} package (Figure~\ref{fig:graph}) to represent
  2863. the interference graph.
  2864. An obvious way to compute the interference graph is to look at the set
  2865. of live locations between each instruction and the next and add an edge to the graph
  2866. for every pair of variables in the same set. This approach is less
  2867. than ideal for two reasons. First, it can be expensive because it
  2868. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2869. locations. Second, in the special case where two locations hold the
  2870. same value (because one was assigned to the other), they can be live
  2871. at the same time without interfering with each other.
  2872. A better way to compute the interference graph is to focus on
  2873. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2874. must not overwrite something in a live location. So for each
  2875. instruction, we create an edge between the locations being written to
  2876. and the live locations. (Except that one should not create self
  2877. edges.) Note that for the \key{callq} instruction, we consider all of
  2878. the caller-saved registers as being written to, so an edge is added
  2879. between every live variable and every caller-saved register. For
  2880. \key{movq}, we deal with the above-mentioned special case by not
  2881. adding an edge between a live variable $v$ and the destination if $v$
  2882. matches the source. So we have the following two rules.
  2883. \begin{enumerate}
  2884. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2885. $d$, then add the edge $(d,v)$ for every $v \in
  2886. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2887. \item For any other instruction $I_k$, for every $d \in W(k)$
  2888. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2889. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2890. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2891. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2892. %% \item If instruction $I_k$ is of the form \key{callq}
  2893. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2894. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2895. \end{enumerate}
  2896. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2897. the above rules to each instruction. We highlight a few of the
  2898. instructions. The first instruction is \lstinline{movq $1, v} and the
  2899. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2900. interferes with \code{rsp}.
  2901. %
  2902. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2903. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2904. interferes with \ttm{w} and \ttm{rsp}.
  2905. %
  2906. The next instruction is \lstinline{movq x, y} and the live-after set
  2907. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2908. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2909. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2910. same value. Figure~\ref{fig:interference-results} lists the
  2911. interference results for all of the instructions and the resulting
  2912. interference graph is shown in Figure~\ref{fig:interfere}.
  2913. \begin{figure}[tbp]
  2914. \begin{quote}
  2915. \begin{tabular}{ll}
  2916. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2917. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2918. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2919. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2920. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2921. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2922. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2923. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2924. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2925. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2926. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2927. \lstinline!jmp conclusion!& no interference.
  2928. \end{tabular}
  2929. \end{quote}
  2930. \caption{Interference results for the running example.}
  2931. \label{fig:interference-results}
  2932. \end{figure}
  2933. \begin{figure}[tbp]
  2934. \large
  2935. \[
  2936. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2937. \node (rax) at (0,0) {$\ttm{rax}$};
  2938. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2939. \node (t1) at (0,2) {$\ttm{t}$};
  2940. \node (z) at (3,2) {$\ttm{z}$};
  2941. \node (x) at (6,2) {$\ttm{x}$};
  2942. \node (y) at (3,0) {$\ttm{y}$};
  2943. \node (w) at (6,0) {$\ttm{w}$};
  2944. \node (v) at (9,0) {$\ttm{v}$};
  2945. \draw (t1) to (rax);
  2946. \draw (t1) to (z);
  2947. \draw (z) to (y);
  2948. \draw (z) to (w);
  2949. \draw (x) to (w);
  2950. \draw (y) to (w);
  2951. \draw (v) to (w);
  2952. \draw (v) to (rsp);
  2953. \draw (w) to (rsp);
  2954. \draw (x) to (rsp);
  2955. \draw (y) to (rsp);
  2956. \path[-.,bend left=15] (z) edge node {} (rsp);
  2957. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2958. \draw (rax) to (rsp);
  2959. \end{tikzpicture}
  2960. \]
  2961. \caption{The interference graph of the example program.}
  2962. \label{fig:interfere}
  2963. \end{figure}
  2964. %% Our next concern is to choose a data structure for representing the
  2965. %% interference graph. There are many choices for how to represent a
  2966. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2967. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2968. %% data structure is to study the algorithm that uses the data structure,
  2969. %% determine what operations need to be performed, and then choose the
  2970. %% data structure that provide the most efficient implementations of
  2971. %% those operations. Often times the choice of data structure can have an
  2972. %% effect on the time complexity of the algorithm, as it does here. If
  2973. %% you skim the next section, you will see that the register allocation
  2974. %% algorithm needs to ask the graph for all of its vertices and, given a
  2975. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2976. %% correct choice of graph representation is that of an adjacency
  2977. %% list. There are helper functions in \code{utilities.rkt} for
  2978. %% representing graphs using the adjacency list representation:
  2979. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2980. %% (Appendix~\ref{appendix:utilities}).
  2981. %% %
  2982. %% \margincomment{\footnotesize To do: change to use the
  2983. %% Racket graph library. \\ --Jeremy}
  2984. %% %
  2985. %% In particular, those functions use a hash table to map each vertex to
  2986. %% the set of adjacent vertices, and the sets are represented using
  2987. %% Racket's \key{set}, which is also a hash table.
  2988. \begin{exercise}\normalfont
  2989. Implement the compiler pass named \code{build-interference} according
  2990. to the algorithm suggested above. We recommend using the \code{graph}
  2991. package to create and inspect the interference graph. The output
  2992. graph of this pass should be stored in the $\itm{info}$ field of the
  2993. program, under the key \code{conflicts}.
  2994. \end{exercise}
  2995. \section{Graph Coloring via Sudoku}
  2996. \label{sec:graph-coloring}
  2997. \index{subject}{graph coloring}
  2998. \index{subject}{Sudoku}
  2999. \index{subject}{color}
  3000. We come to the main event, mapping variables to registers and stack
  3001. locations. Variables that interfere with each other must be mapped to
  3002. different locations. In terms of the interference graph, this means
  3003. that adjacent vertices must be mapped to different locations. If we
  3004. think of locations as colors, the register allocation problem becomes
  3005. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3006. The reader may be more familiar with the graph coloring problem than he
  3007. or she realizes; the popular game of Sudoku is an instance of the
  3008. graph coloring problem. The following describes how to build a graph
  3009. out of an initial Sudoku board.
  3010. \begin{itemize}
  3011. \item There is one vertex in the graph for each Sudoku square.
  3012. \item There is an edge between two vertices if the corresponding squares
  3013. are in the same row, in the same column, or if the squares are in
  3014. the same $3\times 3$ region.
  3015. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3016. \item Based on the initial assignment of numbers to squares in the
  3017. Sudoku board, assign the corresponding colors to the corresponding
  3018. vertices in the graph.
  3019. \end{itemize}
  3020. If you can color the remaining vertices in the graph with the nine
  3021. colors, then you have also solved the corresponding game of Sudoku.
  3022. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3023. the corresponding graph with colored vertices. We map the Sudoku
  3024. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  3025. sampling of the vertices (the colored ones) because showing edges for
  3026. all of the vertices would make the graph unreadable.
  3027. \begin{figure}[tbp]
  3028. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3029. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  3030. \caption{A Sudoku game board and the corresponding colored graph.}
  3031. \label{fig:sudoku-graph}
  3032. \end{figure}
  3033. Some techniques for playing Sudoku correspond to heuristics used in
  3034. graph coloring algorithms. For example, one of the basic techniques
  3035. for Sudoku is called Pencil Marks. The idea is to use a process of
  3036. elimination to determine what numbers are no longer available for a
  3037. square and write down those numbers in the square (writing very
  3038. small). For example, if the number $1$ is assigned to a square, then
  3039. write the pencil mark $1$ in all the squares in the same row, column,
  3040. and region to indicate that $1$ is no longer an option for those other
  3041. squares.
  3042. %
  3043. The Pencil Marks technique corresponds to the notion of
  3044. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  3045. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3046. are no longer available. In graph terminology, we have the following
  3047. definition:
  3048. \begin{equation*}
  3049. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3050. \text{ and } \mathrm{color}(v) = c \}
  3051. \end{equation*}
  3052. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3053. edge with $u$.
  3054. Using the Pencil Marks technique leads to a simple strategy for
  3055. filling in numbers: if there is a square with only one possible number
  3056. left, then choose that number! But what if there are no squares with
  3057. only one possibility left? One brute-force approach is to try them
  3058. all: choose the first one and if that ultimately leads to a solution,
  3059. great. If not, backtrack and choose the next possibility. One good
  3060. thing about Pencil Marks is that it reduces the degree of branching in
  3061. the search tree. Nevertheless, backtracking can be terribly time
  3062. consuming. One way to reduce the amount of backtracking is to use the
  3063. most-constrained-first heuristic. That is, when choosing a square,
  3064. always choose one with the fewest possibilities left (the vertex with
  3065. the highest saturation). The idea is that choosing highly constrained
  3066. squares earlier rather than later is better because later on there may
  3067. not be any possibilities left in the highly saturated squares.
  3068. However, register allocation is easier than Sudoku because the
  3069. register allocator can map variables to stack locations when the
  3070. registers run out. Thus, it makes sense to replace backtracking with
  3071. greedy search: make the best choice at the time and keep going. We
  3072. still wish to minimize the number of colors needed, so we use the
  3073. most-constrained-first heuristic in the greedy search.
  3074. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3075. algorithm for register allocation based on saturation and the
  3076. most-constrained-first heuristic. It is roughly equivalent to the
  3077. DSATUR
  3078. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3079. as in Sudoku, the algorithm represents colors with integers. The
  3080. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3081. for register allocation. The integers $k$ and larger correspond to
  3082. stack locations. The registers that are not used for register
  3083. allocation, such as \code{rax}, are assigned to negative integers. In
  3084. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3085. %% One might wonder why we include registers at all in the liveness
  3086. %% analysis and interference graph. For example, we never allocate a
  3087. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3088. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3089. %% to use register for passing arguments to functions, it will be
  3090. %% necessary for those registers to appear in the interference graph
  3091. %% because those registers will also be assigned to variables, and we
  3092. %% don't want those two uses to encroach on each other. Regarding
  3093. %% registers such as \code{rax} and \code{rsp} that are not used for
  3094. %% variables, we could omit them from the interference graph but that
  3095. %% would require adding special cases to our algorithm, which would
  3096. %% complicate the logic for little gain.
  3097. \begin{figure}[btp]
  3098. \centering
  3099. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3100. Algorithm: DSATUR
  3101. Input: a graph |$G$|
  3102. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3103. |$W \gets \mathrm{vertices}(G)$|
  3104. while |$W \neq \emptyset$| do
  3105. pick a vertex |$u$| from |$W$| with the highest saturation,
  3106. breaking ties randomly
  3107. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3108. |$\mathrm{color}[u] \gets c$|
  3109. |$W \gets W - \{u\}$|
  3110. \end{lstlisting}
  3111. \caption{The saturation-based greedy graph coloring algorithm.}
  3112. \label{fig:satur-algo}
  3113. \end{figure}
  3114. With the DSATUR algorithm in hand, let us return to the running
  3115. example and consider how to color the interference graph in
  3116. Figure~\ref{fig:interfere}.
  3117. %
  3118. We start by assigning the register nodes to their own color. For
  3119. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3120. assigned $-2$. The variables are not yet colored, so they are
  3121. annotated with a dash. We then update the saturation for vertices that
  3122. are adjacent to a register, obtaining the following annotated
  3123. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3124. it interferes with both \code{rax} and \code{rsp}.
  3125. \[
  3126. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3127. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3128. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3129. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3130. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3131. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3132. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3133. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3134. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3135. \draw (t1) to (rax);
  3136. \draw (t1) to (z);
  3137. \draw (z) to (y);
  3138. \draw (z) to (w);
  3139. \draw (x) to (w);
  3140. \draw (y) to (w);
  3141. \draw (v) to (w);
  3142. \draw (v) to (rsp);
  3143. \draw (w) to (rsp);
  3144. \draw (x) to (rsp);
  3145. \draw (y) to (rsp);
  3146. \path[-.,bend left=15] (z) edge node {} (rsp);
  3147. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3148. \draw (rax) to (rsp);
  3149. \end{tikzpicture}
  3150. \]
  3151. The algorithm says to select a maximally saturated vertex. So we pick
  3152. $\ttm{t}$ and color it with the first available integer, which is
  3153. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3154. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3155. \[
  3156. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3157. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3158. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3159. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3160. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3161. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3162. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3163. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3164. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3165. \draw (t1) to (rax);
  3166. \draw (t1) to (z);
  3167. \draw (z) to (y);
  3168. \draw (z) to (w);
  3169. \draw (x) to (w);
  3170. \draw (y) to (w);
  3171. \draw (v) to (w);
  3172. \draw (v) to (rsp);
  3173. \draw (w) to (rsp);
  3174. \draw (x) to (rsp);
  3175. \draw (y) to (rsp);
  3176. \path[-.,bend left=15] (z) edge node {} (rsp);
  3177. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3178. \draw (rax) to (rsp);
  3179. \end{tikzpicture}
  3180. \]
  3181. We repeat the process, selecting the next maximally saturated vertex,
  3182. which is \code{z}, and color it with the first available number, which
  3183. is $1$. We add $1$ to the saturation for the neighboring vertices
  3184. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3185. \[
  3186. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3187. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3188. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3189. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3190. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3191. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3192. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3193. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3194. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3195. \draw (t1) to (rax);
  3196. \draw (t1) to (z);
  3197. \draw (z) to (y);
  3198. \draw (z) to (w);
  3199. \draw (x) to (w);
  3200. \draw (y) to (w);
  3201. \draw (v) to (w);
  3202. \draw (v) to (rsp);
  3203. \draw (w) to (rsp);
  3204. \draw (x) to (rsp);
  3205. \draw (y) to (rsp);
  3206. \path[-.,bend left=15] (z) edge node {} (rsp);
  3207. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3208. \draw (rax) to (rsp);
  3209. \end{tikzpicture}
  3210. \]
  3211. The most saturated vertices are now \code{w} and \code{y}. We color
  3212. \code{w} with the first available color, which is $0$.
  3213. \[
  3214. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3215. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3216. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3217. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3218. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3219. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3220. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3221. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3222. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3223. \draw (t1) to (rax);
  3224. \draw (t1) to (z);
  3225. \draw (z) to (y);
  3226. \draw (z) to (w);
  3227. \draw (x) to (w);
  3228. \draw (y) to (w);
  3229. \draw (v) to (w);
  3230. \draw (v) to (rsp);
  3231. \draw (w) to (rsp);
  3232. \draw (x) to (rsp);
  3233. \draw (y) to (rsp);
  3234. \path[-.,bend left=15] (z) edge node {} (rsp);
  3235. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3236. \draw (rax) to (rsp);
  3237. \end{tikzpicture}
  3238. \]
  3239. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3240. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3241. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3242. and \code{z}, whose colors are $0$ and $1$ respectively.
  3243. \[
  3244. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3245. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3246. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3247. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3248. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3249. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3250. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3251. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3252. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3253. \draw (t1) to (rax);
  3254. \draw (t1) to (z);
  3255. \draw (z) to (y);
  3256. \draw (z) to (w);
  3257. \draw (x) to (w);
  3258. \draw (y) to (w);
  3259. \draw (v) to (w);
  3260. \draw (v) to (rsp);
  3261. \draw (w) to (rsp);
  3262. \draw (x) to (rsp);
  3263. \draw (y) to (rsp);
  3264. \path[-.,bend left=15] (z) edge node {} (rsp);
  3265. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3266. \draw (rax) to (rsp);
  3267. \end{tikzpicture}
  3268. \]
  3269. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3270. \[
  3271. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3272. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3273. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3274. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3275. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3276. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3277. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3278. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3279. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3280. \draw (t1) to (rax);
  3281. \draw (t1) to (z);
  3282. \draw (z) to (y);
  3283. \draw (z) to (w);
  3284. \draw (x) to (w);
  3285. \draw (y) to (w);
  3286. \draw (v) to (w);
  3287. \draw (v) to (rsp);
  3288. \draw (w) to (rsp);
  3289. \draw (x) to (rsp);
  3290. \draw (y) to (rsp);
  3291. \path[-.,bend left=15] (z) edge node {} (rsp);
  3292. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3293. \draw (rax) to (rsp);
  3294. \end{tikzpicture}
  3295. \]
  3296. In the last step of the algorithm, we color \code{x} with $1$.
  3297. \[
  3298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3299. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3300. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3301. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3302. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3303. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3304. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3305. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3306. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3307. \draw (t1) to (rax);
  3308. \draw (t1) to (z);
  3309. \draw (z) to (y);
  3310. \draw (z) to (w);
  3311. \draw (x) to (w);
  3312. \draw (y) to (w);
  3313. \draw (v) to (w);
  3314. \draw (v) to (rsp);
  3315. \draw (w) to (rsp);
  3316. \draw (x) to (rsp);
  3317. \draw (y) to (rsp);
  3318. \path[-.,bend left=15] (z) edge node {} (rsp);
  3319. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3320. \draw (rax) to (rsp);
  3321. \end{tikzpicture}
  3322. \]
  3323. We recommend creating an auxiliary function named \code{color-graph}
  3324. that takes an interference graph and a list of all the variables in
  3325. the program. This function should return a mapping of variables to
  3326. their colors (represented as natural numbers). By creating this helper
  3327. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3328. when we add support for functions.
  3329. To prioritize the processing of highly saturated nodes inside the
  3330. \code{color-graph} function, we recommend using the priority queue
  3331. data structure described in Figure~\ref{fig:priority-queue}. In
  3332. addition, you will need to maintain a mapping from variables to their
  3333. ``handles'' in the priority queue so that you can notify the priority
  3334. queue when their saturation changes.
  3335. \begin{figure}[tp]
  3336. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  3337. \small
  3338. \begin{tcolorbox}[title=Priority Queue]
  3339. A \emph{priority queue} is a collection of items in which the
  3340. removal of items is governed by priority. In a ``min'' queue,
  3341. lower priority items are removed first. An implementation is in
  3342. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  3343. queue} \index{subject}{minimum priority queue}
  3344. \begin{description}
  3345. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3346. priority queue that uses the $\itm{cmp}$ predicate to determine
  3347. whether its first argument has lower or equal priority to its
  3348. second argument.
  3349. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3350. items in the queue.
  3351. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3352. the item into the queue and returns a handle for the item in the
  3353. queue.
  3354. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3355. the lowest priority.
  3356. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3357. notifies the queue that the priority has decreased for the item
  3358. associated with the given handle.
  3359. \end{description}
  3360. \end{tcolorbox}
  3361. %\end{wrapfigure}
  3362. \caption{The priority queue data structure.}
  3363. \label{fig:priority-queue}
  3364. \end{figure}
  3365. With the coloring complete, we finalize the assignment of variables to
  3366. registers and stack locations. We map the first $k$ colors to the $k$
  3367. registers and the rest of the colors to stack locations. Suppose for
  3368. the moment that we have just one register to use for register
  3369. allocation, \key{rcx}. Then we have the following map from colors to
  3370. locations.
  3371. \[
  3372. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3373. \]
  3374. Composing this mapping with the coloring, we arrive at the following
  3375. assignment of variables to locations.
  3376. \begin{gather*}
  3377. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3378. \ttm{w} \mapsto \key{\%rcx}, \,
  3379. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3380. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3381. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3382. \ttm{t} \mapsto \key{\%rcx} \}
  3383. \end{gather*}
  3384. Adapt the code from the \code{assign-homes} pass
  3385. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3386. assigned location. Applying the above assignment to our running
  3387. example, on the left, yields the program on the right.
  3388. % why frame size of 32? -JGS
  3389. \begin{center}
  3390. \begin{minipage}{0.3\textwidth}
  3391. \begin{lstlisting}
  3392. movq $1, v
  3393. movq $42, w
  3394. movq v, x
  3395. addq $7, x
  3396. movq x, y
  3397. movq x, z
  3398. addq w, z
  3399. movq y, t
  3400. negq t
  3401. movq z, %rax
  3402. addq t, %rax
  3403. jmp conclusion
  3404. \end{lstlisting}
  3405. \end{minipage}
  3406. $\Rightarrow\qquad$
  3407. \begin{minipage}{0.45\textwidth}
  3408. \begin{lstlisting}
  3409. movq $1, -8(%rbp)
  3410. movq $42, %rcx
  3411. movq -8(%rbp), -8(%rbp)
  3412. addq $7, -8(%rbp)
  3413. movq -8(%rbp), -16(%rbp)
  3414. movq -8(%rbp), -8(%rbp)
  3415. addq %rcx, -8(%rbp)
  3416. movq -16(%rbp), %rcx
  3417. negq %rcx
  3418. movq -8(%rbp), %rax
  3419. addq %rcx, %rax
  3420. jmp conclusion
  3421. \end{lstlisting}
  3422. \end{minipage}
  3423. \end{center}
  3424. \begin{exercise}\normalfont
  3425. %
  3426. Implement the compiler pass \code{allocate-registers}.
  3427. %
  3428. Create five programs that exercise all of the register allocation
  3429. algorithm, including spilling variables to the stack.
  3430. %
  3431. Replace \code{assign-homes} in the list of \code{passes} in the
  3432. \code{run-tests.rkt} script with the three new passes:
  3433. \code{uncover-live}, \code{build-interference}, and
  3434. \code{allocate-registers}.
  3435. %
  3436. Temporarily remove the \code{print-x86} pass from the list of passes
  3437. and the call to \code{compiler-tests}.
  3438. %
  3439. Run the script to test the register allocator.
  3440. \end{exercise}
  3441. \section{Patch Instructions}
  3442. \label{sec:patch-instructions}
  3443. The remaining step in the compilation to x86 is to ensure that the
  3444. instructions have at most one argument that is a memory access.
  3445. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3446. is problematic. The fix is to first move \code{-8(\%rbp)}
  3447. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3448. %
  3449. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3450. problematic, but they can be fixed by simply deleting them. In
  3451. general, we recommend deleting all the trivial moves whose source and
  3452. destination are the same location.
  3453. %
  3454. The following is the output of \code{patch-instructions} on the
  3455. running example.
  3456. \begin{center}
  3457. \begin{minipage}{0.4\textwidth}
  3458. \begin{lstlisting}
  3459. movq $1, -8(%rbp)
  3460. movq $42, %rcx
  3461. movq -8(%rbp), -8(%rbp)
  3462. addq $7, -8(%rbp)
  3463. movq -8(%rbp), -16(%rbp)
  3464. movq -8(%rbp), -8(%rbp)
  3465. addq %rcx, -8(%rbp)
  3466. movq -16(%rbp), %rcx
  3467. negq %rcx
  3468. movq -8(%rbp), %rax
  3469. addq %rcx, %rax
  3470. jmp conclusion
  3471. \end{lstlisting}
  3472. \end{minipage}
  3473. $\Rightarrow\qquad$
  3474. \begin{minipage}{0.45\textwidth}
  3475. \begin{lstlisting}
  3476. movq $1, -8(%rbp)
  3477. movq $42, %rcx
  3478. addq $7, -8(%rbp)
  3479. movq -8(%rbp), %rax
  3480. movq %rax, -16(%rbp)
  3481. addq %rcx, -8(%rbp)
  3482. movq -16(%rbp), %rcx
  3483. negq %rcx
  3484. movq -8(%rbp), %rax
  3485. addq %rcx, %rax
  3486. jmp conclusion
  3487. \end{lstlisting}
  3488. \end{minipage}
  3489. \end{center}
  3490. \begin{exercise}\normalfont
  3491. %
  3492. Implement the \code{patch-instructions} compiler pass.
  3493. %
  3494. Insert it after \code{allocate-registers} in the list of \code{passes}
  3495. in the \code{run-tests.rkt} script.
  3496. %
  3497. Run the script to test the \code{patch-instructions} pass.
  3498. \end{exercise}
  3499. \section{Print x86}
  3500. \label{sec:print-x86-reg-alloc}
  3501. \index{subject}{calling conventions}
  3502. \index{subject}{prelude}\index{subject}{conclusion}
  3503. Recall that the \code{print-x86} pass generates the prelude and
  3504. conclusion instructions to satisfy the x86 calling conventions
  3505. (Section~\ref{sec:calling-conventions}). With the addition of the
  3506. register allocator, the callee-saved registers used by the register
  3507. allocator must be saved in the prelude and restored in the conclusion.
  3508. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3509. of \code{X86Program} named \code{used-callee} that stores the set of
  3510. callee-saved registers that were assigned to variables. The
  3511. \code{print-x86} pass can then access this information to decide which
  3512. callee-saved registers need to be saved and restored.
  3513. %
  3514. When calculating the size of the frame to adjust the \code{rsp} in the
  3515. prelude, make sure to take into account the space used for saving the
  3516. callee-saved registers. Also, don't forget that the frame needs to be
  3517. a multiple of 16 bytes!
  3518. An overview of all of the passes involved in register allocation is
  3519. shown in Figure~\ref{fig:reg-alloc-passes}.
  3520. \begin{figure}[tbp]
  3521. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3522. \node (Rvar) at (0,2) {\large \LangVar{}};
  3523. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3524. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3525. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3526. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3527. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3528. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3529. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3530. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3531. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3532. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3533. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3534. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3535. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3536. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3537. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3538. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3539. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3540. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3541. \end{tikzpicture}
  3542. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3543. \label{fig:reg-alloc-passes}
  3544. \end{figure}
  3545. \begin{exercise}\normalfont
  3546. Update the \code{print-x86} pass as described in this section.
  3547. %
  3548. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3549. list of passes and the call to \code{compiler-tests}.
  3550. %
  3551. Run the script to test the complete compiler for \LangVar{} that
  3552. performs register allocation.
  3553. \end{exercise}
  3554. \section{Challenge: Move Biasing}
  3555. \label{sec:move-biasing}
  3556. \index{subject}{move biasing}
  3557. This section describes an enhancement to the register allocator for
  3558. students looking for an extra challenge or who have a deeper interest
  3559. in register allocation.
  3560. To motivate the need for move biasing we return to the running example
  3561. but this time use all of the general purpose registers. So we have
  3562. the following mapping of color numbers to registers.
  3563. \[
  3564. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3565. \]
  3566. Using the same assignment of variables to color numbers that was
  3567. produced by the register allocator described in the last section, we
  3568. get the following program.
  3569. \begin{center}
  3570. \begin{minipage}{0.3\textwidth}
  3571. \begin{lstlisting}
  3572. movq $1, v
  3573. movq $42, w
  3574. movq v, x
  3575. addq $7, x
  3576. movq x, y
  3577. movq x, z
  3578. addq w, z
  3579. movq y, t
  3580. negq t
  3581. movq z, %rax
  3582. addq t, %rax
  3583. jmp conclusion
  3584. \end{lstlisting}
  3585. \end{minipage}
  3586. $\Rightarrow\qquad$
  3587. \begin{minipage}{0.45\textwidth}
  3588. \begin{lstlisting}
  3589. movq $1, %rdx
  3590. movq $42, %rcx
  3591. movq %rdx, %rdx
  3592. addq $7, %rdx
  3593. movq %rdx, %rsi
  3594. movq %rdx, %rdx
  3595. addq %rcx, %rdx
  3596. movq %rsi, %rcx
  3597. negq %rcx
  3598. movq %rdx, %rax
  3599. addq %rcx, %rax
  3600. jmp conclusion
  3601. \end{lstlisting}
  3602. \end{minipage}
  3603. \end{center}
  3604. In the above output code there are two \key{movq} instructions that
  3605. can be removed because their source and target are the same. However,
  3606. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3607. register, we could instead remove three \key{movq} instructions. We
  3608. can accomplish this by taking into account which variables appear in
  3609. \key{movq} instructions with which other variables.
  3610. We say that two variables $p$ and $q$ are \emph{move
  3611. related}\index{subject}{move related} if they participate together in a
  3612. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3613. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3614. for a variable, it should prefer a color that has already been used
  3615. for a move-related variable (assuming that they do not interfere). Of
  3616. course, this preference should not override the preference for
  3617. registers over stack locations. This preference should be used as a
  3618. tie breaker when choosing between registers or when choosing between
  3619. stack locations.
  3620. We recommend representing the move relationships in a graph, similar
  3621. to how we represented interference. The following is the \emph{move
  3622. graph} for our running example.
  3623. \[
  3624. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3625. \node (rax) at (0,0) {$\ttm{rax}$};
  3626. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3627. \node (t) at (0,2) {$\ttm{t}$};
  3628. \node (z) at (3,2) {$\ttm{z}$};
  3629. \node (x) at (6,2) {$\ttm{x}$};
  3630. \node (y) at (3,0) {$\ttm{y}$};
  3631. \node (w) at (6,0) {$\ttm{w}$};
  3632. \node (v) at (9,0) {$\ttm{v}$};
  3633. \draw (v) to (x);
  3634. \draw (x) to (y);
  3635. \draw (x) to (z);
  3636. \draw (y) to (t);
  3637. \end{tikzpicture}
  3638. \]
  3639. Now we replay the graph coloring, pausing to see the coloring of
  3640. \code{y}. Recall the following configuration. The most saturated vertices
  3641. were \code{w} and \code{y}.
  3642. \[
  3643. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3644. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3645. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3646. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3647. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3648. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3649. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3650. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3651. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3652. \draw (t1) to (rax);
  3653. \draw (t1) to (z);
  3654. \draw (z) to (y);
  3655. \draw (z) to (w);
  3656. \draw (x) to (w);
  3657. \draw (y) to (w);
  3658. \draw (v) to (w);
  3659. \draw (v) to (rsp);
  3660. \draw (w) to (rsp);
  3661. \draw (x) to (rsp);
  3662. \draw (y) to (rsp);
  3663. \path[-.,bend left=15] (z) edge node {} (rsp);
  3664. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3665. \draw (rax) to (rsp);
  3666. \end{tikzpicture}
  3667. \]
  3668. %
  3669. Last time we chose to color \code{w} with $0$. But this time we see
  3670. that \code{w} is not move related to any vertex, but \code{y} is move
  3671. related to \code{t}. So we choose to color \code{y} the same color as
  3672. \code{t}, $0$.
  3673. \[
  3674. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3675. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3676. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3677. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3678. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3679. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3680. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3681. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3682. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3683. \draw (t1) to (rax);
  3684. \draw (t1) to (z);
  3685. \draw (z) to (y);
  3686. \draw (z) to (w);
  3687. \draw (x) to (w);
  3688. \draw (y) to (w);
  3689. \draw (v) to (w);
  3690. \draw (v) to (rsp);
  3691. \draw (w) to (rsp);
  3692. \draw (x) to (rsp);
  3693. \draw (y) to (rsp);
  3694. \path[-.,bend left=15] (z) edge node {} (rsp);
  3695. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3696. \draw (rax) to (rsp);
  3697. \end{tikzpicture}
  3698. \]
  3699. Now \code{w} is the most saturated, so we color it $2$.
  3700. \[
  3701. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3702. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3703. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3704. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3705. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3706. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3707. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3708. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3709. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3710. \draw (t1) to (rax);
  3711. \draw (t1) to (z);
  3712. \draw (z) to (y);
  3713. \draw (z) to (w);
  3714. \draw (x) to (w);
  3715. \draw (y) to (w);
  3716. \draw (v) to (w);
  3717. \draw (v) to (rsp);
  3718. \draw (w) to (rsp);
  3719. \draw (x) to (rsp);
  3720. \draw (y) to (rsp);
  3721. \path[-.,bend left=15] (z) edge node {} (rsp);
  3722. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3723. \draw (rax) to (rsp);
  3724. \end{tikzpicture}
  3725. \]
  3726. At this point, vertices \code{x} and \code{v} are most saturated, but
  3727. \code{x} is move related to \code{y} and \code{z}, so we color
  3728. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3729. \[
  3730. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3731. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3732. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3733. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3734. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3735. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3736. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3737. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3738. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3739. \draw (t1) to (rax);
  3740. \draw (t) to (z);
  3741. \draw (z) to (y);
  3742. \draw (z) to (w);
  3743. \draw (x) to (w);
  3744. \draw (y) to (w);
  3745. \draw (v) to (w);
  3746. \draw (v) to (rsp);
  3747. \draw (w) to (rsp);
  3748. \draw (x) to (rsp);
  3749. \draw (y) to (rsp);
  3750. \path[-.,bend left=15] (z) edge node {} (rsp);
  3751. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3752. \draw (rax) to (rsp);
  3753. \end{tikzpicture}
  3754. \]
  3755. So we have the following assignment of variables to registers.
  3756. \begin{gather*}
  3757. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3758. \ttm{w} \mapsto \key{\%rsi}, \,
  3759. \ttm{x} \mapsto \key{\%rcx}, \,
  3760. \ttm{y} \mapsto \key{\%rcx}, \,
  3761. \ttm{z} \mapsto \key{\%rdx}, \,
  3762. \ttm{t} \mapsto \key{\%rcx} \}
  3763. \end{gather*}
  3764. We apply this register assignment to the running example, on the left,
  3765. to obtain the code in the middle. The \code{patch-instructions} then
  3766. removes the three trivial moves to obtain the code on the right.
  3767. \begin{minipage}{0.25\textwidth}
  3768. \begin{lstlisting}
  3769. movq $1, v
  3770. movq $42, w
  3771. movq v, x
  3772. addq $7, x
  3773. movq x, y
  3774. movq x, z
  3775. addq w, z
  3776. movq y, t
  3777. negq t
  3778. movq z, %rax
  3779. addq t, %rax
  3780. jmp conclusion
  3781. \end{lstlisting}
  3782. \end{minipage}
  3783. $\Rightarrow\qquad$
  3784. \begin{minipage}{0.25\textwidth}
  3785. \begin{lstlisting}
  3786. movq $1, %rcx
  3787. movq $42, %rsi
  3788. movq %rcx, %rcx
  3789. addq $7, %rcx
  3790. movq %rcx, %rcx
  3791. movq %rcx, %rdx
  3792. addq %rsi, %rdx
  3793. movq %rcx, %rcx
  3794. negq %rcx
  3795. movq %rdx, %rax
  3796. addq %rcx, %rax
  3797. jmp conclusion
  3798. \end{lstlisting}
  3799. \end{minipage}
  3800. $\Rightarrow\qquad$
  3801. \begin{minipage}{0.25\textwidth}
  3802. \begin{lstlisting}
  3803. movq $1, %rcx
  3804. movq $42, %rsi
  3805. addq $7, %rcx
  3806. movq %rcx, %rdx
  3807. addq %rsi, %rdx
  3808. negq %rcx
  3809. movq %rdx, %rax
  3810. addq %rcx, %rax
  3811. jmp conclusion
  3812. \end{lstlisting}
  3813. \end{minipage}
  3814. \begin{exercise}\normalfont
  3815. Change your implementation of \code{allocate-registers} to take move
  3816. biasing into account. Create two new tests that include at least one
  3817. opportunity for move biasing and visually inspect the output x86
  3818. programs to make sure that your move biasing is working properly. Make
  3819. sure that your compiler still passes all of the tests.
  3820. \end{exercise}
  3821. %To do: another neat challenge would be to do
  3822. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  3823. %% \subsection{Output of the Running Example}
  3824. %% \label{sec:reg-alloc-output}
  3825. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3826. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3827. and move biasing. To demonstrate both the use of registers and the
  3828. stack, we have limited the register allocator to use just two
  3829. registers: \code{rbx} and \code{rcx}. In the prelude\index{subject}{prelude}
  3830. of the \code{main} function, we push \code{rbx} onto the stack because
  3831. it is a callee-saved register and it was assigned to variable by the
  3832. register allocator. We subtract \code{8} from the \code{rsp} at the
  3833. end of the prelude to reserve space for the one spilled variable.
  3834. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3835. Moving on the the \code{start} block, we see how the registers were
  3836. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3837. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3838. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3839. that the prelude saved the callee-save register \code{rbx} onto the
  3840. stack. The spilled variables must be placed lower on the stack than
  3841. the saved callee-save registers, so in this case \code{w} is placed at
  3842. \code{-16(\%rbp)}.
  3843. In the \code{conclusion}\index{subject}{conclusion}, we undo the work that was
  3844. done in the prelude. We move the stack pointer up by \code{8} bytes
  3845. (the room for spilled variables), then we pop the old values of
  3846. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3847. \code{retq} to return control to the operating system.
  3848. \begin{figure}[tbp]
  3849. % var_test_28.rkt
  3850. % (use-minimal-set-of-registers! #t)
  3851. % and only rbx rcx
  3852. % tmp 0 rbx
  3853. % z 1 rcx
  3854. % y 0 rbx
  3855. % w 2 16(%rbp)
  3856. % v 0 rbx
  3857. % x 0 rbx
  3858. \begin{lstlisting}
  3859. start:
  3860. movq $1, %rbx
  3861. movq $42, -16(%rbp)
  3862. addq $7, %rbx
  3863. movq %rbx, %rcx
  3864. addq -16(%rbp), %rcx
  3865. negq %rbx
  3866. movq %rcx, %rax
  3867. addq %rbx, %rax
  3868. jmp conclusion
  3869. .globl main
  3870. main:
  3871. pushq %rbp
  3872. movq %rsp, %rbp
  3873. pushq %rbx
  3874. subq $8, %rsp
  3875. jmp start
  3876. conclusion:
  3877. addq $8, %rsp
  3878. popq %rbx
  3879. popq %rbp
  3880. retq
  3881. \end{lstlisting}
  3882. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3883. \label{fig:running-example-x86}
  3884. \end{figure}
  3885. % challenge: prioritize variables based on execution frequencies
  3886. % and the number of uses of a variable
  3887. % challenge: enhance the coloring algorithm using Chaitin's
  3888. % approach of prioritizing high-degree variables
  3889. % by removing low-degree variables (coloring them later)
  3890. % from the interference graph
  3891. \section{Further Reading}
  3892. \label{sec:register-allocation-further-reading}
  3893. Early register allocation algorithms were developed for Fortran
  3894. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  3895. of graph coloring began in the late 1970s and early 1980s with the
  3896. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  3897. algorithm is based on the following observation of
  3898. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  3899. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  3900. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  3901. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  3902. different colors, but since there are less than $k$ of them, there
  3903. will be one or more colors left over to use for coloring $v$ in $G$.
  3904. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  3905. less than $k$ from the graph and recursively colors the rest of the
  3906. graph. Upon returning from the recursion, it colors $v$ with one of
  3907. the available colors and returns. \citet{Chaitin:1982vn} augments
  3908. this algorithm to handle spilling as follows. If there are no vertices
  3909. of degree lower than $k$ then pick a vertex at random, spill it,
  3910. remove it from the graph, and proceed recursively to color the rest of
  3911. the graph.
  3912. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  3913. move-related and that don't interfere with each other, a process
  3914. called \emph{coalescing}. While coalescing decreases the number of
  3915. moves, it can make the graph more difficult to
  3916. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  3917. which two variables are merged only if they have fewer than $k$
  3918. neighbors of high degree. \citet{George:1996aa} observe that
  3919. conservative coalescing is sometimes too conservative and make it more
  3920. aggressive by iterating the coalescing with the removal of low-degree
  3921. vertices.
  3922. %
  3923. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  3924. also propose \emph{biased coloring} in which a variable is assigned to
  3925. the same color as another move-related variable if possible, as
  3926. discussed in Section~\ref{sec:move-biasing}.
  3927. %
  3928. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  3929. performs coalescing, graph coloring, and spill code insertion until
  3930. all variables have been assigned a location.
  3931. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  3932. spills variables that don't have to be: a high-degree variable can be
  3933. colorable if many of its neighbors are assigned the same color.
  3934. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  3935. high-degree vertex is not immediately spilled. Instead the decision is
  3936. deferred until after the recursive call, at which point it is apparent
  3937. whether there is actually an available color or not. We observe that
  3938. this algorithm is equivalent to the smallest-last ordering
  3939. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  3940. be registers and the rest to be stack locations.
  3941. %% biased coloring
  3942. Earlier editions of the compiler course at Indiana University
  3943. \citep{Dybvig:2010aa} were based on the algorithm of
  3944. \citet{Briggs:1994kx}.
  3945. The smallest-last ordering algorithm is one of many \emph{greedy}
  3946. coloring algorithms. A greedy coloring algorithm visits all the
  3947. vertices in a particular order and assigns each one the first
  3948. available color. An \emph{offline} greedy algorithm chooses the
  3949. ordering up-front, prior to assigning colors. The algorithm of
  3950. \citet{Chaitin:1981vl} should be considered offline because the vertex
  3951. ordering does not depend on the colors assigned, so the algorithm
  3952. could be split into two phases. Other orderings are possible. For
  3953. example, \citet{Chow:1984ys} order variables according an estimate of
  3954. runtime cost.
  3955. An \emph{online} greedy coloring algorithm uses information about the
  3956. current assignment of colors to influence the order in which the
  3957. remaining vertices are colored. The saturation-based algorithm
  3958. described in this chapter is one such algorithm. We choose to use
  3959. saturation-based coloring is because it is fun to introduce graph
  3960. coloring via Sudoku.
  3961. A register allocator may choose to map each variable to just one
  3962. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  3963. variable to one or more locations. The later can be achieved by
  3964. \emph{live range splitting}, where a variable is replaced by several
  3965. variables that each handle part of its live
  3966. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  3967. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  3968. %% replacement algorithm, bottom-up local
  3969. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  3970. %% Cooper: top-down (priority bassed), bottom-up
  3971. %% top-down
  3972. %% order variables by priority (estimated cost)
  3973. %% caveat: split variables into two groups:
  3974. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  3975. %% color the constrained ones first
  3976. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  3977. %% cite J. Cocke for an algorithm that colors variables
  3978. %% in a high-degree first ordering
  3979. %Register Allocation via Usage Counts, Freiburghouse CACM
  3980. \citet{Palsberg:2007si} observe that many of the interference graphs
  3981. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  3982. that is, every cycle with four or more edges has an edge which is not
  3983. part of the cycle but which connects two vertices on the cycle. Such
  3984. graphs can be optimally colored by the greedy algorithm with a vertex
  3985. ordering determined by maximum cardinality search.
  3986. In situations where compile time is of utmost importance, such as in
  3987. just-in-time compilers, graph coloring algorithms can be too expensive
  3988. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  3989. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3990. \chapter{Booleans and Control Flow}
  3991. \label{ch:Rif}
  3992. \index{subject}{Boolean}
  3993. \index{subject}{control flow}
  3994. \index{subject}{conditional expression}
  3995. The \LangInt{} and \LangVar{} languages only have a single kind of
  3996. value, integers. In this chapter we add a second kind of value, the
  3997. Booleans, to create the \LangIf{} language. The Boolean values
  3998. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  3999. respectively in Racket. The \LangIf{} language includes several
  4000. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4001. \key{<}, etc.) and the conditional \key{if} expression. With the
  4002. addition of \key{if}, programs can have non-trivial control flow which
  4003. impacts \code{explicate-control} and liveness analysis. Also, because
  4004. we now have two kinds of values, we need to handle programs that apply
  4005. an operation to the wrong kind of value, such as \code{(not 1)}.
  4006. There are two language design options for such situations. One option
  4007. is to signal an error and the other is to provide a wider
  4008. interpretation of the operation. The Racket language uses a mixture of
  4009. these two options, depending on the operation and the kind of
  4010. value. For example, the result of \code{(not 1)} in Racket is
  4011. \code{\#f} because Racket treats non-zero integers as if they were
  4012. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4013. error in Racket because \code{car} expects a pair.
  4014. Typed Racket makes similar design choices as Racket, except much of
  4015. the error detection happens at compile time instead of run time. Typed
  4016. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4017. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4018. because Typed Racket expects the type of the argument to be of the
  4019. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4020. The \LangIf{} language performs type checking during compilation like
  4021. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4022. alternative choice, that is, a dynamically typed language like Racket.
  4023. The \LangIf{} language is a subset of Typed Racket; for some
  4024. operations we are more restrictive, for example, rejecting
  4025. \code{(not 1)}.
  4026. This chapter is organized as follows. We begin by defining the syntax
  4027. and interpreter for the \LangIf{} language
  4028. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4029. checking and build a type checker for \LangIf{}
  4030. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4031. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4032. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4033. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4034. discuss how our compiler passes change to accommodate Booleans and
  4035. conditional control flow. There is one new pass, named \code{shrink},
  4036. that translates some operators into others, thereby reducing the
  4037. number of operators that need to be handled in later passes. The
  4038. largest changes occur in \code{explicate-control}, to translate
  4039. \code{if} expressions into control-flow graphs
  4040. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4041. allocation, the liveness analysis now has multiple basic blocks to
  4042. process and there is the interesting question of how to handle
  4043. conditional jumps.
  4044. \section{The \LangIf{} Language}
  4045. \label{sec:lang-if}
  4046. The concrete syntax of the \LangIf{} language is defined in
  4047. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4048. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4049. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4050. \code{\#f}, and the conditional \code{if} expression. We expand the
  4051. operators to include
  4052. \begin{enumerate}
  4053. \item subtraction on integers,
  4054. \item the logical operators \key{and}, \key{or} and \key{not},
  4055. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4056. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4057. comparing integers.
  4058. \end{enumerate}
  4059. We reorganize the abstract syntax for the primitive operations in
  4060. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4061. them. This means that the grammar no longer checks whether the arity
  4062. of an operators matches the number of arguments. That responsibility
  4063. is moved to the type checker for \LangIf{}, which we introduce in
  4064. Section~\ref{sec:type-check-Rif}.
  4065. \begin{figure}[tp]
  4066. \centering
  4067. \fbox{
  4068. \begin{minipage}{0.96\textwidth}
  4069. \[
  4070. \begin{array}{lcl}
  4071. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4072. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4073. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4074. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4075. &\mid& \itm{bool}
  4076. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4077. \mid (\key{not}\;\Exp) \\
  4078. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4079. \LangIfM{} &::=& \Exp
  4080. \end{array}
  4081. \]
  4082. \end{minipage}
  4083. }
  4084. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4085. (Figure~\ref{fig:Rvar-concrete-syntax}) with Booleans and conditionals.}
  4086. \label{fig:Rif-concrete-syntax}
  4087. \end{figure}
  4088. \begin{figure}[tp]
  4089. \centering
  4090. \fbox{
  4091. \begin{minipage}{0.96\textwidth}
  4092. \[
  4093. \begin{array}{lcl}
  4094. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4095. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4096. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4097. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4098. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4099. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4100. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4101. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4102. \end{array}
  4103. \]
  4104. \end{minipage}
  4105. }
  4106. \caption{The abstract syntax of \LangIf{}.}
  4107. \label{fig:Rif-syntax}
  4108. \end{figure}
  4109. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4110. which inherits from the interpreter for \LangVar{}
  4111. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4112. evaluate to the corresponding Boolean values. The conditional
  4113. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4114. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4115. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4116. operations \code{not} and \code{and} behave as you might expect, but
  4117. note that the \code{and} operation is short-circuiting. That is, given
  4118. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4119. evaluated if $e_1$ evaluates to \code{\#f}.
  4120. With the increase in the number of primitive operations, the
  4121. interpreter would become repetitive without some care. We refactor
  4122. the case for \code{Prim}, moving the code that differs with each
  4123. operation into the \code{interp-op} method shown in in
  4124. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4125. separately because of its short-circuiting behavior.
  4126. \begin{figure}[tbp]
  4127. \begin{lstlisting}
  4128. (define interp-Rif-class
  4129. (class interp-Rvar-class
  4130. (super-new)
  4131. (define/public (interp-op op) ...)
  4132. (define/override ((interp-exp env) e)
  4133. (define recur (interp-exp env))
  4134. (match e
  4135. [(Bool b) b]
  4136. [(If cnd thn els)
  4137. (match (recur cnd)
  4138. [#t (recur thn)]
  4139. [#f (recur els)])]
  4140. [(Prim 'and (list e1 e2))
  4141. (match (recur e1)
  4142. [#t (match (recur e2) [#t #t] [#f #f])]
  4143. [#f #f])]
  4144. [(Prim op args)
  4145. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4146. [else ((super interp-exp env) e)]))
  4147. ))
  4148. (define (interp-Rif p)
  4149. (send (new interp-Rif-class) interp-program p))
  4150. \end{lstlisting}
  4151. \caption{Interpreter for the \LangIf{} language. (See
  4152. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4153. \label{fig:interp-Rif}
  4154. \end{figure}
  4155. \begin{figure}[tbp]
  4156. \begin{lstlisting}
  4157. (define/public (interp-op op)
  4158. (match op
  4159. ['+ fx+]
  4160. ['- fx-]
  4161. ['read read-fixnum]
  4162. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4163. ['or (lambda (v1 v2)
  4164. (cond [(and (boolean? v1) (boolean? v2))
  4165. (or v1 v2)]))]
  4166. ['eq? (lambda (v1 v2)
  4167. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4168. (and (boolean? v1) (boolean? v2))
  4169. (and (vector? v1) (vector? v2)))
  4170. (eq? v1 v2)]))]
  4171. ['< (lambda (v1 v2)
  4172. (cond [(and (fixnum? v1) (fixnum? v2))
  4173. (< v1 v2)]))]
  4174. ['<= (lambda (v1 v2)
  4175. (cond [(and (fixnum? v1) (fixnum? v2))
  4176. (<= v1 v2)]))]
  4177. ['> (lambda (v1 v2)
  4178. (cond [(and (fixnum? v1) (fixnum? v2))
  4179. (> v1 v2)]))]
  4180. ['>= (lambda (v1 v2)
  4181. (cond [(and (fixnum? v1) (fixnum? v2))
  4182. (>= v1 v2)]))]
  4183. [else (error 'interp-op "unknown operator")]))
  4184. \end{lstlisting}
  4185. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4186. \label{fig:interp-op-Rif}
  4187. \end{figure}
  4188. \section{Type Checking \LangIf{} Programs}
  4189. \label{sec:type-check-Rif}
  4190. \index{subject}{type checking}
  4191. \index{subject}{semantic analysis}
  4192. It is helpful to think about type checking in two complementary
  4193. ways. A type checker predicts the type of value that will be produced
  4194. by each expression in the program. For \LangIf{}, we have just two types,
  4195. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4196. \begin{lstlisting}
  4197. (+ 10 (- (+ 12 20)))
  4198. \end{lstlisting}
  4199. produces an \key{Integer} while
  4200. \begin{lstlisting}
  4201. (and (not #f) #t)
  4202. \end{lstlisting}
  4203. produces a \key{Boolean}.
  4204. Another way to think about type checking is that it enforces a set of
  4205. rules about which operators can be applied to which kinds of
  4206. values. For example, our type checker for \LangIf{} signals an error
  4207. for the below expression
  4208. \begin{lstlisting}
  4209. (not (+ 10 (- (+ 12 20))))
  4210. \end{lstlisting}
  4211. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4212. but the type checker enforces the rule that the argument of \code{not}
  4213. must be a \key{Boolean}.
  4214. We implement type checking using classes and methods because they
  4215. provide the open recursion needed to reuse code as we extend the type
  4216. checker in later chapters, analogous to the use of classes and methods
  4217. for the interpreters (Section~\ref{sec:extensible-interp}).
  4218. We separate the type checker for the \LangVar{} fragment into its own
  4219. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4220. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4221. from the type checker for \LangVar{}. These type checkers are in the
  4222. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4223. support code.
  4224. %
  4225. Each type checker is a structurally recursive function over the AST.
  4226. Given an input expression \code{e}, the type checker either signals an
  4227. error or returns an expression and its type (\key{Integer} or
  4228. \key{Boolean}). It returns an expression because there are situations
  4229. in which we want to change or update the expression.
  4230. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4231. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4232. \code{Integer}. To handle variables, the type checker uses the
  4233. environment \code{env} to map variables to types. Consider the case
  4234. for \key{let}. We type check the initializing expression to obtain
  4235. its type \key{T} and then associate type \code{T} with the variable
  4236. \code{x} in the environment used to type check the body of the
  4237. \key{let}. Thus, when the type checker encounters a use of variable
  4238. \code{x}, it can find its type in the environment. Regarding
  4239. primitive operators, we recursively analyze the arguments and then
  4240. invoke \code{type-check-op} to check whether the argument types are
  4241. allowed.
  4242. Several auxiliary methods are used in the type checker. The method
  4243. \code{operator-types} defines a dictionary that maps the operator
  4244. names to their parameter and return types. The \code{type-equal?}
  4245. method determines whether two types are equal, which for now simply
  4246. dispatches to \code{equal?} (deep equality). The
  4247. \code{check-type-equal?} method triggers an error if the two types are
  4248. not equal. The \code{type-check-op} method looks up the operator in
  4249. the \code{operator-types} dictionary and then checks whether the
  4250. argument types are equal to the parameter types. The result is the
  4251. return type of the operator.
  4252. \begin{figure}[tbp]
  4253. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4254. (define type-check-Rvar-class
  4255. (class object%
  4256. (super-new)
  4257. (define/public (operator-types)
  4258. '((+ . ((Integer Integer) . Integer))
  4259. (- . ((Integer) . Integer))
  4260. (read . (() . Integer))))
  4261. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4262. (define/public (check-type-equal? t1 t2 e)
  4263. (unless (type-equal? t1 t2)
  4264. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4265. (define/public (type-check-op op arg-types e)
  4266. (match (dict-ref (operator-types) op)
  4267. [`(,param-types . ,return-type)
  4268. (for ([at arg-types] [pt param-types])
  4269. (check-type-equal? at pt e))
  4270. return-type]
  4271. [else (error 'type-check-op "unrecognized ~a" op)]))
  4272. (define/public (type-check-exp env)
  4273. (lambda (e)
  4274. (match e
  4275. [(Int n) (values (Int n) 'Integer)]
  4276. [(Var x) (values (Var x) (dict-ref env x))]
  4277. [(Let x e body)
  4278. (define-values (e^ Te) ((type-check-exp env) e))
  4279. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4280. (values (Let x e^ b) Tb)]
  4281. [(Prim op es)
  4282. (define-values (new-es ts)
  4283. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4284. (values (Prim op new-es) (type-check-op op ts e))]
  4285. [else (error 'type-check-exp "couldn't match" e)])))
  4286. (define/public (type-check-program e)
  4287. (match e
  4288. [(Program info body)
  4289. (define-values (body^ Tb) ((type-check-exp '()) body))
  4290. (check-type-equal? Tb 'Integer body)
  4291. (Program info body^)]
  4292. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4293. ))
  4294. (define (type-check-Rvar p)
  4295. (send (new type-check-Rvar-class) type-check-program p))
  4296. \end{lstlisting}
  4297. \caption{Type checker for the \LangVar{} language.}
  4298. \label{fig:type-check-Rvar}
  4299. \end{figure}
  4300. \begin{figure}[tbp]
  4301. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4302. (define type-check-Rif-class
  4303. (class type-check-Rvar-class
  4304. (super-new)
  4305. (inherit check-type-equal?)
  4306. (define/override (operator-types)
  4307. (append '((- . ((Integer Integer) . Integer))
  4308. (and . ((Boolean Boolean) . Boolean))
  4309. (or . ((Boolean Boolean) . Boolean))
  4310. (< . ((Integer Integer) . Boolean))
  4311. (<= . ((Integer Integer) . Boolean))
  4312. (> . ((Integer Integer) . Boolean))
  4313. (>= . ((Integer Integer) . Boolean))
  4314. (not . ((Boolean) . Boolean))
  4315. )
  4316. (super operator-types)))
  4317. (define/override (type-check-exp env)
  4318. (lambda (e)
  4319. (match e
  4320. [(Prim 'eq? (list e1 e2))
  4321. (define-values (e1^ T1) ((type-check-exp env) e1))
  4322. (define-values (e2^ T2) ((type-check-exp env) e2))
  4323. (check-type-equal? T1 T2 e)
  4324. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4325. [(Bool b) (values (Bool b) 'Boolean)]
  4326. [(If cnd thn els)
  4327. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4328. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4329. (define-values (els^ Te) ((type-check-exp env) els))
  4330. (check-type-equal? Tc 'Boolean e)
  4331. (check-type-equal? Tt Te e)
  4332. (values (If cnd^ thn^ els^) Te)]
  4333. [else ((super type-check-exp env) e)])))
  4334. ))
  4335. (define (type-check-Rif p)
  4336. (send (new type-check-Rif-class) type-check-program p))
  4337. \end{lstlisting}
  4338. \caption{Type checker for the \LangIf{} language.}
  4339. \label{fig:type-check-Rif}
  4340. \end{figure}
  4341. Next we discuss the type checker for \LangIf{} in
  4342. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4343. two arguments to have the same type. The type of a Boolean constant is
  4344. \code{Boolean}. The condition of an \code{if} must be of
  4345. \code{Boolean} type and the two branches must have the same type. The
  4346. \code{operator-types} function adds dictionary entries for the other
  4347. new operators.
  4348. \begin{exercise}\normalfont
  4349. Create 10 new test programs in \LangIf{}. Half of the programs should
  4350. have a type error. For those programs, create an empty file with the
  4351. same base name but with file extension \code{.tyerr}. For example, if
  4352. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4353. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4354. \code{interp-tests} and \code{compiler-tests} that a type error is
  4355. expected. The other half of the test programs should not have type
  4356. errors.
  4357. In the \code{run-tests.rkt} script, change the second argument of
  4358. \code{interp-tests} and \code{compiler-tests} to
  4359. \code{type-check-Rif}, which causes the type checker to run prior to
  4360. the compiler passes. Temporarily change the \code{passes} to an empty
  4361. list and run the script, thereby checking that the new test programs
  4362. either type check or not as intended.
  4363. \end{exercise}
  4364. \section{The \LangCIf{} Intermediate Language}
  4365. \label{sec:Cif}
  4366. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4367. \LangCIf{} intermediate language. (The concrete syntax is in the
  4368. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4369. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4370. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4371. \key{\#f} to the \Arg{} non-terminal.
  4372. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4373. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4374. statement is a comparison operation and the branches are \code{goto}
  4375. statements, making it straightforward to compile \code{if} statements
  4376. to x86.
  4377. \begin{figure}[tp]
  4378. \fbox{
  4379. \begin{minipage}{0.96\textwidth}
  4380. \small
  4381. \[
  4382. \begin{array}{lcl}
  4383. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4384. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4385. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4386. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4387. &\mid& \UNIOP{\key{'not}}{\Atm}
  4388. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4389. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4390. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4391. \mid \GOTO{\itm{label}} \\
  4392. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4393. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4394. \end{array}
  4395. \]
  4396. \end{minipage}
  4397. }
  4398. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4399. (Figure~\ref{fig:c0-syntax}).}
  4400. \label{fig:c1-syntax}
  4401. \end{figure}
  4402. \section{The \LangXIf{} Language}
  4403. \label{sec:x86-if}
  4404. \index{subject}{x86} To implement the new logical operations, the comparison
  4405. operations, and the \key{if} expression, we need to delve further into
  4406. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4407. define the concrete and abstract syntax for the \LangXIf{} subset
  4408. of x86, which includes instructions for logical operations,
  4409. comparisons, and conditional jumps.
  4410. One challenge is that x86 does not provide an instruction that
  4411. directly implements logical negation (\code{not} in \LangIf{} and
  4412. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4413. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4414. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4415. bit of its arguments, and writes the results into its second argument.
  4416. Recall the truth table for exclusive-or:
  4417. \begin{center}
  4418. \begin{tabular}{l|cc}
  4419. & 0 & 1 \\ \hline
  4420. 0 & 0 & 1 \\
  4421. 1 & 1 & 0
  4422. \end{tabular}
  4423. \end{center}
  4424. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4425. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4426. for the bit $1$, the result is the opposite of the second bit. Thus,
  4427. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4428. the first argument:
  4429. \[
  4430. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4431. \qquad\Rightarrow\qquad
  4432. \begin{array}{l}
  4433. \key{movq}~ \Arg\key{,} \Var\\
  4434. \key{xorq}~ \key{\$1,} \Var
  4435. \end{array}
  4436. \]
  4437. \begin{figure}[tp]
  4438. \fbox{
  4439. \begin{minipage}{0.96\textwidth}
  4440. \[
  4441. \begin{array}{lcl}
  4442. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4443. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4444. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4445. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4446. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4447. \key{subq} \; \Arg\key{,} \Arg \mid
  4448. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4449. && \gray{ \key{callq} \; \itm{label} \mid
  4450. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4451. && \gray{ \itm{label}\key{:}\; \Instr }
  4452. \mid \key{xorq}~\Arg\key{,}~\Arg
  4453. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4454. && \key{set}cc~\Arg
  4455. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4456. \mid \key{j}cc~\itm{label}
  4457. \\
  4458. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  4459. & & \gray{ \key{main:} \; \Instr\ldots }
  4460. \end{array}
  4461. \]
  4462. \end{minipage}
  4463. }
  4464. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4465. \label{fig:x86-1-concrete}
  4466. \end{figure}
  4467. \begin{figure}[tp]
  4468. \fbox{
  4469. \begin{minipage}{0.98\textwidth}
  4470. \small
  4471. \[
  4472. \begin{array}{lcl}
  4473. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4474. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4475. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4476. \mid \BYTEREG{\itm{bytereg}} \\
  4477. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4478. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4479. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4480. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4481. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4482. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4483. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4484. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4485. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4486. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4487. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4488. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4489. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4490. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4491. \end{array}
  4492. \]
  4493. \end{minipage}
  4494. }
  4495. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4496. \label{fig:x86-1}
  4497. \end{figure}
  4498. Next we consider the x86 instructions that are relevant for compiling
  4499. the comparison operations. The \key{cmpq} instruction compares its two
  4500. arguments to determine whether one argument is less than, equal, or
  4501. greater than the other argument. The \key{cmpq} instruction is unusual
  4502. regarding the order of its arguments and where the result is
  4503. placed. The argument order is backwards: if you want to test whether
  4504. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4505. \key{cmpq} is placed in the special EFLAGS register. This register
  4506. cannot be accessed directly but it can be queried by a number of
  4507. instructions, including the \key{set} instruction. The instruction
  4508. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4509. depending on whether the comparison comes out according to the
  4510. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4511. for less-or-equal, \key{g} for greater, \key{ge} for
  4512. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4513. that its destination argument must be single byte register, such as
  4514. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4515. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4516. instruction can be used to move from a single byte register to a
  4517. normal 64-bit register. The abstract syntax for the \code{set}
  4518. instruction differs from the concrete syntax in that it separates the
  4519. instruction name from the condition code.
  4520. The x86 instruction for conditional jump is relevant to the
  4521. compilation of \key{if} expressions. The instruction
  4522. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4523. the instruction after \itm{label} depending on whether the result in
  4524. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4525. jump instruction falls through to the next instruction. Like the
  4526. abstract syntax for \code{set}, the abstract syntax for conditional
  4527. jump separates the instruction name from the condition code. For
  4528. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4529. the conditional jump instruction relies on the EFLAGS register, it is
  4530. common for it to be immediately preceded by a \key{cmpq} instruction
  4531. to set the EFLAGS register.
  4532. \section{Shrink the \LangIf{} Language}
  4533. \label{sec:shrink-Rif}
  4534. The \LangIf{} language includes several operators that are easily
  4535. expressible with other operators. For example, subtraction is
  4536. expressible using addition and negation.
  4537. \[
  4538. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4539. \]
  4540. Several of the comparison operations are expressible using less-than
  4541. and logical negation.
  4542. \[
  4543. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4544. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4545. \]
  4546. The \key{let} is needed in the above translation to ensure that
  4547. expression $e_1$ is evaluated before $e_2$.
  4548. By performing these translations in the front-end of the compiler, the
  4549. later passes of the compiler do not need to deal with these operators,
  4550. making the passes shorter.
  4551. %% On the other hand, sometimes
  4552. %% these translations make it more difficult to generate the most
  4553. %% efficient code with respect to the number of instructions. However,
  4554. %% these differences typically do not affect the number of accesses to
  4555. %% memory, which is the primary factor that determines execution time on
  4556. %% modern computer architectures.
  4557. \begin{exercise}\normalfont
  4558. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4559. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4560. translating them to other constructs in \LangIf{}.
  4561. %
  4562. Create six test programs that involve these operators.
  4563. %
  4564. In the \code{run-tests.rkt} script, add the following entry for
  4565. \code{shrink} to the list of passes (it should be the only pass at
  4566. this point).
  4567. \begin{lstlisting}
  4568. (list "shrink" shrink interp-Rif type-check-Rif)
  4569. \end{lstlisting}
  4570. This instructs \code{interp-tests} to run the intepreter
  4571. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4572. output of \code{shrink}.
  4573. %
  4574. Run the script to test your compiler on all the test programs.
  4575. \end{exercise}
  4576. \section{Uniquify Variables}
  4577. \label{sec:uniquify-Rif}
  4578. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4579. \code{if} expressions.
  4580. \begin{exercise}\normalfont
  4581. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4582. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4583. \begin{lstlisting}
  4584. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4585. \end{lstlisting}
  4586. Run the script to test your compiler.
  4587. \end{exercise}
  4588. \section{Remove Complex Operands}
  4589. \label{sec:remove-complex-opera-Rif}
  4590. The output language for this pass is \LangIfANF{}
  4591. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4592. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4593. \code{If} is not. All three sub-expressions of an \code{If} are
  4594. allowed to be complex expressions but the operands of \code{not} and
  4595. the comparisons must be atoms.
  4596. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4597. \code{rco-atom} functions according to whether the output needs to be
  4598. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4599. Regarding \code{If}, it is particularly important to \textbf{not}
  4600. replace its condition with a temporary variable because that would
  4601. interfere with the generation of high-quality output in the
  4602. \code{explicate-control} pass.
  4603. \begin{figure}[tp]
  4604. \centering
  4605. \fbox{
  4606. \begin{minipage}{0.96\textwidth}
  4607. \[
  4608. \begin{array}{rcl}
  4609. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4610. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4611. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4612. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4613. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4614. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4615. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4616. \end{array}
  4617. \]
  4618. \end{minipage}
  4619. }
  4620. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4621. \label{fig:Rif-anf-syntax}
  4622. \end{figure}
  4623. \begin{exercise}\normalfont
  4624. %
  4625. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4626. and \code{rco-exp} functions in \code{compiler.rkt}.
  4627. %
  4628. Create three new \LangInt{} programs that exercise the interesting
  4629. code in this pass.
  4630. %
  4631. In the \code{run-tests.rkt} script, add the following entry to the
  4632. list of \code{passes} and then run the script to test your compiler.
  4633. \begin{lstlisting}
  4634. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4635. \end{lstlisting}
  4636. \end{exercise}
  4637. \section{Explicate Control}
  4638. \label{sec:explicate-control-Rif}
  4639. Recall that the purpose of \code{explicate-control} is to make the
  4640. order of evaluation explicit in the syntax of the program. With the
  4641. addition of \key{if} this get more interesting.
  4642. As a motivating example, consider the following program that has an
  4643. \key{if} expression nested in the predicate of another \key{if}.
  4644. % cond_test_41.rkt
  4645. \begin{center}
  4646. \begin{minipage}{0.96\textwidth}
  4647. \begin{lstlisting}
  4648. (let ([x (read)])
  4649. (let ([y (read)])
  4650. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4651. (+ y 2)
  4652. (+ y 10))))
  4653. \end{lstlisting}
  4654. \end{minipage}
  4655. \end{center}
  4656. %
  4657. The naive way to compile \key{if} and the comparison would be to
  4658. handle each of them in isolation, regardless of their context. Each
  4659. comparison would be translated into a \key{cmpq} instruction followed
  4660. by a couple instructions to move the result from the EFLAGS register
  4661. into a general purpose register or stack location. Each \key{if} would
  4662. be translated into a \key{cmpq} instruction followed by a conditional
  4663. jump. The generated code for the inner \key{if} in the above example
  4664. would be as follows.
  4665. \begin{center}
  4666. \begin{minipage}{0.96\textwidth}
  4667. \begin{lstlisting}
  4668. ...
  4669. cmpq $1, x ;; (< x 1)
  4670. setl %al
  4671. movzbq %al, tmp
  4672. cmpq $1, tmp ;; (if ...)
  4673. je then_branch_1
  4674. jmp else_branch_1
  4675. ...
  4676. \end{lstlisting}
  4677. \end{minipage}
  4678. \end{center}
  4679. However, if we take context into account we can do better and reduce
  4680. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4681. Our goal will be compile \key{if} expressions so that the relevant
  4682. comparison instruction appears directly before the conditional jump.
  4683. For example, we want to generate the following code for the inner
  4684. \code{if}.
  4685. \begin{center}
  4686. \begin{minipage}{0.96\textwidth}
  4687. \begin{lstlisting}
  4688. ...
  4689. cmpq $1, x
  4690. je then_branch_1
  4691. jmp else_branch_1
  4692. ...
  4693. \end{lstlisting}
  4694. \end{minipage}
  4695. \end{center}
  4696. One way to achieve this is to reorganize the code at the level of
  4697. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4698. the following code.
  4699. \begin{center}
  4700. \begin{minipage}{0.96\textwidth}
  4701. \begin{lstlisting}
  4702. (let ([x (read)])
  4703. (let ([y (read)])
  4704. (if (< x 1)
  4705. (if (eq? x 0)
  4706. (+ y 2)
  4707. (+ y 10))
  4708. (if (eq? x 2)
  4709. (+ y 2)
  4710. (+ y 10)))))
  4711. \end{lstlisting}
  4712. \end{minipage}
  4713. \end{center}
  4714. Unfortunately, this approach duplicates the two branches from the
  4715. outer \code{if} and a compiler must never duplicate code!
  4716. We need a way to perform the above transformation but without
  4717. duplicating code. That is, we need a way for different parts of a
  4718. program to refer to the same piece of code. At the level of x86
  4719. assembly this is straightforward because we can label the code for
  4720. each branch and insert jumps in all the places that need to execute
  4721. the branch. In our intermediate language, we need to move away from
  4722. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4723. particular, we use a standard program representation called a
  4724. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4725. \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex is a
  4726. labeled sequence of code, called a \emph{basic block}, and each edge
  4727. represents a jump to another block. The \key{CProgram} construct of
  4728. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4729. as an alist mapping labels to basic blocks. Each basic block is
  4730. represented by the $\Tail$ non-terminal.
  4731. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4732. \code{remove-complex-opera*} pass and then the
  4733. \code{explicate-control} pass on the example program. We walk through
  4734. the output program and then discuss the algorithm.
  4735. %
  4736. Following the order of evaluation in the output of
  4737. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4738. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4739. inner \key{if}. In the output of \code{explicate-control}, in the
  4740. block labeled \code{start}, is two assignment statements followed by a
  4741. \code{if} statement that branches to \code{block40} or
  4742. \code{block41}. The blocks associated with those labels contain the
  4743. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4744. respectively. In particular, we start \code{block40} with the
  4745. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4746. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4747. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4748. \code{block41} is similar.
  4749. \begin{figure}[tbp]
  4750. \begin{tabular}{lll}
  4751. \begin{minipage}{0.4\textwidth}
  4752. % cond_test_41.rkt
  4753. \begin{lstlisting}
  4754. (let ([x (read)])
  4755. (let ([y (read)])
  4756. (if (if (< x 1)
  4757. (eq? x 0)
  4758. (eq? x 2))
  4759. (+ y 2)
  4760. (+ y 10))))
  4761. \end{lstlisting}
  4762. \hspace{40pt}$\Downarrow$
  4763. \begin{lstlisting}
  4764. (let ([x (read)])
  4765. (let ([y (read)])
  4766. (if (if (< x 1)
  4767. (eq? x 0)
  4768. (eq? x 2))
  4769. (+ y 2)
  4770. (+ y 10))))
  4771. \end{lstlisting}
  4772. \end{minipage}
  4773. &
  4774. $\Rightarrow$
  4775. &
  4776. \begin{minipage}{0.55\textwidth}
  4777. \begin{lstlisting}
  4778. start:
  4779. x = (read);
  4780. y = (read);
  4781. if (< x 1) goto block40;
  4782. else goto block41;
  4783. block40:
  4784. if (eq? x 0) goto block38;
  4785. else goto block39;
  4786. block41:
  4787. if (eq? x 2) goto block38;
  4788. else goto block39;
  4789. block38:
  4790. return (+ y 2);
  4791. block39:
  4792. return (+ y 10);
  4793. \end{lstlisting}
  4794. \end{minipage}
  4795. \end{tabular}
  4796. \caption{Translation from \LangIf{} to \LangCIf{}
  4797. via the \code{explicate-control}.}
  4798. \label{fig:explicate-control-s1-38}
  4799. \end{figure}
  4800. %% The nice thing about the output of \code{explicate-control} is that
  4801. %% there are no unnecessary comparisons and every comparison is part of a
  4802. %% conditional jump.
  4803. %% The down-side of this output is that it includes
  4804. %% trivial blocks, such as the blocks labeled \code{block92} through
  4805. %% \code{block95}, that only jump to another block. We discuss a solution
  4806. %% to this problem in Section~\ref{sec:opt-jumps}.
  4807. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  4808. \code{explicate-control} for \LangVar{} using two mutually recursive
  4809. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4810. former function translates expressions in tail position whereas the
  4811. later function translates expressions on the right-hand-side of a
  4812. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4813. have a new kind of position to deal with: the predicate position of
  4814. the \key{if}. We need another function, \code{explicate-pred}, that
  4815. takes an \LangIf{} expression and two blocks for the then-branch and
  4816. else-branch. The output of \code{explicate-pred} is a block.
  4817. %
  4818. In the following paragraphs we discuss specific cases in the
  4819. \code{explicate-pred} function as well as additions to the
  4820. \code{explicate-tail} and \code{explicate-assign} functions.
  4821. \begin{figure}[tbp]
  4822. \begin{lstlisting}
  4823. (define (explicate-pred cnd thn els)
  4824. (match cnd
  4825. [(Var x) ___]
  4826. [(Let x rhs body) ___]
  4827. [(Prim 'not (list e)) ___]
  4828. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  4829. (IfStmt (Prim op arg*) (force (block->goto thn))
  4830. (force (block->goto els)))]
  4831. [(Bool b) (if b thn els)]
  4832. [(If cnd^ thn^ els^) ___]
  4833. [else (error "explicate-pred unhandled case" cnd)]))
  4834. \end{lstlisting}
  4835. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  4836. \label{fig:explicate-pred}
  4837. \end{figure}
  4838. The skeleton for the \code{explicate-pred} function is given in
  4839. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  4840. that can have type \code{Boolean}. We detail a few cases here and
  4841. leave the rest for the reader. The input to this function is an
  4842. expression and two blocks, \code{thn} and \code{els}, for the two
  4843. branches of the enclosing \key{if}.
  4844. %
  4845. Consider the case for Boolean constants in
  4846. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  4847. evaluation\index{subject}{partial evaluation} and output either the \code{thn}
  4848. or \code{els} branch depending on whether the constant is true or
  4849. false. This case demonstrates that we sometimes discard the \code{thn}
  4850. or \code{els} blocks that are input to \code{explicate-pred}.
  4851. The case for \key{if} in \code{explicate-pred} is particularly
  4852. illuminating because it deals with the challenges we discussed above
  4853. regarding nested \key{if} expressions
  4854. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  4855. \lstinline{els^} branches of the \key{if} inherit their context from
  4856. the current one, that is, predicate context. So you should recursively
  4857. apply \code{explicate-pred} to the \lstinline{thn^} and
  4858. \lstinline{els^} branches. For both of those recursive calls, pass
  4859. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  4860. and \code{els} may get used twice, once inside each recursive call. As
  4861. discussed above, to avoid duplicating code, we need to add them to the
  4862. control-flow graph so that we can instead refer to them by name and
  4863. execute them with a \key{goto}. However, as we saw in the cases above
  4864. for Boolean constants, the blocks \code{thn} and \code{els} may not
  4865. get used at all and we don't want to prematurely add them to the
  4866. control-flow graph if they end up being discarded.
  4867. The solution to this conundrum is to use \emph{lazy
  4868. evaluation}\index{subject}{lazy evaluation}\citep{Friedman:1976aa} to delay
  4869. adding the blocks to the control-flow graph until the points where we
  4870. know they will be used. Racket provides support for lazy evaluation
  4871. with the
  4872. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4873. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4874. \index{subject}{delay} creates a \emph{promise}\index{subject}{promise} in which the
  4875. evaluation of the expressions is postponed. When \key{(force}
  4876. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the first
  4877. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4878. $e_n$ is cached in the promise and returned. If \code{force} is
  4879. applied again to the same promise, then the cached result is returned.
  4880. If \code{force} is applied to an argument that is not a promise,
  4881. \code{force} simply returns the argument.
  4882. We use lazy evaluation for the input and output blocks of the
  4883. functions \code{explicate-pred} and \code{explicate-assign} and for
  4884. the output block of \code{explicate-tail}. So instead of taking and
  4885. returning blocks, they take and return promises. Furthermore, when we
  4886. come to a situation in which we a block might be used more than once,
  4887. as in the case for \code{if} in \code{explicate-pred}, we transform
  4888. the promise into a new promise that will add the block to the
  4889. control-flow graph and return a \code{goto}. The following auxiliary
  4890. function named \code{block->goto} accomplishes this task. It begins
  4891. with \code{delay} to create a promise. When forced, this promise will
  4892. force the original promise. If that returns a \code{goto} (because the
  4893. block was already added to the control-flow graph), then we return the
  4894. \code{goto}. Otherwise we add the block to the control-flow graph with
  4895. another auxiliary function named \code{add-node}. That function
  4896. returns the label for the new block, which we use to create a
  4897. \code{goto}.
  4898. \begin{lstlisting}
  4899. (define (block->goto block)
  4900. (delay
  4901. (define b (force block))
  4902. (match b
  4903. [(Goto label) (Goto label)]
  4904. [else (Goto (add-node b))])))
  4905. \end{lstlisting}
  4906. Returning to the discussion of \code{explicate-pred}
  4907. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  4908. operators. This is one of the base cases of the recursive function so
  4909. we translate the comparison to an \code{if} statement. We apply
  4910. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  4911. that will add then to the control-flow graph, which we can immediately
  4912. \code{force} to obtain the two goto's that form the branches of the
  4913. \code{if} statement.
  4914. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  4915. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  4916. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4917. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4918. %% results from the two recursive calls. We complete the case for
  4919. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  4920. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4921. %% the result $B_5$.
  4922. %% \[
  4923. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4924. %% \quad\Rightarrow\quad
  4925. %% B_5
  4926. %% \]
  4927. The \code{explicate-tail} and \code{explicate-assign} functions need
  4928. additional cases for Boolean constants and \key{if}.
  4929. %
  4930. In the cases for \code{if}, the two branches inherit the current
  4931. context, so in \code{explicate-tail} they are in tail position and in
  4932. \code{explicate-assign} they are in assignment position. The
  4933. \code{cont} parameter of \code{explicate-assign} is used in both
  4934. recursive calls, so make sure to use \code{block->goto} on it.
  4935. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  4936. %% inherit the current context, so they are in tail position. Thus, the
  4937. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  4938. %% \code{explicate-tail}.
  4939. %% %
  4940. %% We need to pass $B_0$ as the accumulator argument for both of these
  4941. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  4942. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4943. %% to the control-flow graph and obtain a promised goto $G_0$.
  4944. %% %
  4945. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4946. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4947. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4948. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4949. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4950. %% \[
  4951. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4952. %% \]
  4953. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4954. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4955. %% should not be confused with the labels for the blocks that appear in
  4956. %% the generated code. We initially construct unlabeled blocks; we only
  4957. %% attach labels to blocks when we add them to the control-flow graph, as
  4958. %% we see in the next case.
  4959. %% Next consider the case for \key{if} in the \code{explicate-assign}
  4960. %% function. The context of the \key{if} is an assignment to some
  4961. %% variable $x$ and then the control continues to some promised block
  4962. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  4963. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4964. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4965. %% branches of the \key{if} inherit the current context, so they are in
  4966. %% assignment positions. Let $B_2$ be the result of applying
  4967. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4968. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4969. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4970. %% the result of applying \code{explicate-pred} to the predicate
  4971. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4972. %% translates to the promise $B_4$.
  4973. %% \[
  4974. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4975. %% \]
  4976. %% This completes the description of \code{explicate-control} for \LangIf{}.
  4977. The way in which the \code{shrink} pass transforms logical operations
  4978. such as \code{and} and \code{or} can impact the quality of code
  4979. generated by \code{explicate-control}. For example, consider the
  4980. following program.
  4981. % cond_test_21.rkt
  4982. \begin{lstlisting}
  4983. (if (and (eq? (read) 0) (eq? (read) 1))
  4984. 0
  4985. 42)
  4986. \end{lstlisting}
  4987. The \code{and} operation should transform into something that the
  4988. \code{explicate-pred} function can still analyze and descend through to
  4989. reach the underlying \code{eq?} conditions. Ideally, your
  4990. \code{explicate-control} pass should generate code similar to the
  4991. following for the above program.
  4992. \begin{center}
  4993. \begin{lstlisting}
  4994. start:
  4995. tmp1 = (read);
  4996. if (eq? tmp1 0) goto block40;
  4997. else goto block39;
  4998. block40:
  4999. tmp2 = (read);
  5000. if (eq? tmp2 1) goto block38;
  5001. else goto block39;
  5002. block38:
  5003. return 0;
  5004. block39:
  5005. return 42;
  5006. \end{lstlisting}
  5007. \end{center}
  5008. \begin{exercise}\normalfont
  5009. Implement the pass \code{explicate-control} by adding the cases for
  5010. Boolean constants and \key{if} to the \code{explicate-tail} and
  5011. \code{explicate-assign}. Implement the auxiliary function
  5012. \code{explicate-pred} for predicate contexts.
  5013. %
  5014. Create test cases that exercise all of the new cases in the code for
  5015. this pass.
  5016. %
  5017. Add the following entry to the list of \code{passes} in
  5018. \code{run-tests.rkt} and then run this script to test your compiler.
  5019. \begin{lstlisting}
  5020. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5021. \end{lstlisting}
  5022. \end{exercise}
  5023. \section{Select Instructions}
  5024. \label{sec:select-Rif}
  5025. \index{subject}{instruction selection}
  5026. The \code{select-instructions} pass translate \LangCIf{} to
  5027. \LangXIfVar{}. Recall that we implement this pass using three
  5028. auxiliary functions, one for each of the non-terminals $\Atm$,
  5029. $\Stmt$, and $\Tail$.
  5030. For $\Atm$, we have new cases for the Booleans. We take the usual
  5031. approach of encoding them as integers, with true as 1 and false as 0.
  5032. \[
  5033. \key{\#t} \Rightarrow \key{1}
  5034. \qquad
  5035. \key{\#f} \Rightarrow \key{0}
  5036. \]
  5037. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5038. be implemented in terms of \code{xorq} as we discussed at the
  5039. beginning of this section. Given an assignment
  5040. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5041. if the left-hand side $\itm{var}$ is
  5042. the same as $\Atm$, then just the \code{xorq} suffices.
  5043. \[
  5044. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5045. \quad\Rightarrow\quad
  5046. \key{xorq}~\key{\$}1\key{,}~\Var
  5047. \]
  5048. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5049. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5050. x86. Then we have
  5051. \[
  5052. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5053. \quad\Rightarrow\quad
  5054. \begin{array}{l}
  5055. \key{movq}~\Arg\key{,}~\Var\\
  5056. \key{xorq}~\key{\$}1\key{,}~\Var
  5057. \end{array}
  5058. \]
  5059. Next consider the cases for \code{eq?} and less-than comparison.
  5060. Translating these operations to x86 is slightly involved due to the
  5061. unusual nature of the \key{cmpq} instruction discussed above. We
  5062. recommend translating an assignment from \code{eq?} into the following
  5063. sequence of three instructions. \\
  5064. \begin{tabular}{lll}
  5065. \begin{minipage}{0.4\textwidth}
  5066. \begin{lstlisting}
  5067. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5068. \end{lstlisting}
  5069. \end{minipage}
  5070. &
  5071. $\Rightarrow$
  5072. &
  5073. \begin{minipage}{0.4\textwidth}
  5074. \begin{lstlisting}
  5075. cmpq |$\Arg_2$|, |$\Arg_1$|
  5076. sete %al
  5077. movzbq %al, |$\Var$|
  5078. \end{lstlisting}
  5079. \end{minipage}
  5080. \end{tabular} \\
  5081. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5082. and \key{if} statements. Both are straightforward to translate to
  5083. x86. A \key{goto} becomes a jump instruction.
  5084. \[
  5085. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5086. \]
  5087. An \key{if} statement becomes a compare instruction followed by a
  5088. conditional jump (for the ``then'' branch) and the fall-through is to
  5089. a regular jump (for the ``else'' branch).\\
  5090. \begin{tabular}{lll}
  5091. \begin{minipage}{0.4\textwidth}
  5092. \begin{lstlisting}
  5093. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5094. else goto |$\ell_2$|;
  5095. \end{lstlisting}
  5096. \end{minipage}
  5097. &
  5098. $\Rightarrow$
  5099. &
  5100. \begin{minipage}{0.4\textwidth}
  5101. \begin{lstlisting}
  5102. cmpq |$\Arg_2$|, |$\Arg_1$|
  5103. je |$\ell_1$|
  5104. jmp |$\ell_2$|
  5105. \end{lstlisting}
  5106. \end{minipage}
  5107. \end{tabular} \\
  5108. \begin{exercise}\normalfont
  5109. Expand your \code{select-instructions} pass to handle the new features
  5110. of the \LangIf{} language.
  5111. %
  5112. Add the following entry to the list of \code{passes} in
  5113. \code{run-tests.rkt}
  5114. \begin{lstlisting}
  5115. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5116. \end{lstlisting}
  5117. %
  5118. Run the script to test your compiler on all the test programs.
  5119. \end{exercise}
  5120. \section{Register Allocation}
  5121. \label{sec:register-allocation-Rif}
  5122. \index{subject}{register allocation}
  5123. The changes required for \LangIf{} affect liveness analysis, building the
  5124. interference graph, and assigning homes, but the graph coloring
  5125. algorithm itself does not change.
  5126. \subsection{Liveness Analysis}
  5127. \label{sec:liveness-analysis-Rif}
  5128. \index{subject}{liveness analysis}
  5129. Recall that for \LangVar{} we implemented liveness analysis for a single
  5130. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5131. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5132. produces many basic blocks arranged in a control-flow graph. We
  5133. recommend that you create a new auxiliary function named
  5134. \code{uncover-live-CFG} that applies liveness analysis to a
  5135. control-flow graph.
  5136. The first question we is: what order should we process the basic
  5137. blocks in the control-flow graph? Recall that to perform liveness
  5138. analysis on a basic block we need to know its live-after set. If a
  5139. basic block has no successors (i.e. no out-edges in the control flow
  5140. graph), then it has an empty live-after set and we can immediately
  5141. apply liveness analysis to it. If a basic block has some successors,
  5142. then we need to complete liveness analysis on those blocks first. In
  5143. graph theory, a sequence of nodes is in \emph{topological
  5144. order}\index{subject}{topological order} if each vertex comes before its
  5145. successors. We need the opposite, so we can transpose the graph
  5146. before computing a topological order.
  5147. %
  5148. Use the \code{tsort} and \code{transpose} functions of the Racket
  5149. \code{graph} package to accomplish this.
  5150. %
  5151. As an aside, a topological ordering is only guaranteed to exist if the
  5152. graph does not contain any cycles. That is indeed the case for the
  5153. control-flow graphs that we generate from \LangIf{} programs.
  5154. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5155. learn how to handle cycles in the control-flow graph.
  5156. You'll need to construct a directed graph to represent the
  5157. control-flow graph. Do not use the \code{directed-graph} of the
  5158. \code{graph} package because that only allows at most one edge between
  5159. each pair of vertices, but a control-flow graph may have multiple
  5160. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5161. the support code implements a graph representation that allows
  5162. multiple edges between a pair of vertices.
  5163. The next question is how to analyze jump instructions. Recall that in
  5164. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5165. \code{label->live} that maps each label to the set of live locations
  5166. at the beginning of its block. We use \code{label->live} to determine
  5167. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5168. that we have many basic blocks, \code{label->live} needs to be updated
  5169. as we process the blocks. In particular, after performing liveness
  5170. analysis on a block, we take the live-before set of its first
  5171. instruction and associate that with the block's label in the
  5172. \code{label->live}.
  5173. In \LangXIfVar{} we also have the conditional jump
  5174. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5175. this instruction is particularly interesting because during
  5176. compilation we do not know which way a conditional jump will go. So
  5177. we do not know whether to use the live-before set for the following
  5178. instruction or the live-before set for the $\itm{label}$. However,
  5179. there is no harm to the correctness of the compiler if we classify
  5180. more locations as live than the ones that are truly live during a
  5181. particular execution of the instruction. Thus, we can take the union
  5182. of the live-before sets from the following instruction and from the
  5183. mapping for $\itm{label}$ in \code{label->live}.
  5184. The auxiliary functions for computing the variables in an
  5185. instruction's argument and for computing the variables read-from ($R$)
  5186. or written-to ($W$) by an instruction need to be updated to handle the
  5187. new kinds of arguments and instructions in \LangXIfVar{}.
  5188. \begin{exercise}\normalfont
  5189. Update the \code{uncover-live} pass and implement the
  5190. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5191. to the control-flow graph. Add the following entry to the list of
  5192. \code{passes} in the \code{run-tests.rkt} script.
  5193. \begin{lstlisting}
  5194. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5195. \end{lstlisting}
  5196. \end{exercise}
  5197. \subsection{Build the Interference Graph}
  5198. \label{sec:build-interference-Rif}
  5199. Many of the new instructions in \LangXIfVar{} can be handled in the
  5200. same way as the instructions in \LangXVar{}. Thus, if your code was
  5201. already quite general, it will not need to be changed to handle the
  5202. new instructions. If you code is not general enough, we recommend that
  5203. you change your code to be more general. For example, you can factor
  5204. out the computing of the the read and write sets for each kind of
  5205. instruction into two auxiliary functions.
  5206. Note that the \key{movzbq} instruction requires some special care,
  5207. similar to the \key{movq} instruction. See rule number 1 in
  5208. Section~\ref{sec:build-interference}.
  5209. \begin{exercise}\normalfont
  5210. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5211. following entries to the list of \code{passes} in the
  5212. \code{run-tests.rkt} script.
  5213. \begin{lstlisting}
  5214. (list "build-interference" build-interference interp-pseudo-x86-1)
  5215. (list "allocate-registers" allocate-registers interp-x86-1)
  5216. \end{lstlisting}
  5217. Run the script to test your compiler on all the \LangIf{} test
  5218. programs.
  5219. \end{exercise}
  5220. \section{Patch Instructions}
  5221. The second argument of the \key{cmpq} instruction must not be an
  5222. immediate value (such as an integer). So if you are comparing two
  5223. immediates, we recommend inserting a \key{movq} instruction to put the
  5224. second argument in \key{rax}. Also, recall that instructions may have
  5225. at most one memory reference.
  5226. %
  5227. The second argument of the \key{movzbq} must be a register.
  5228. %
  5229. There are no special restrictions on the jump instructions.
  5230. \begin{exercise}\normalfont
  5231. %
  5232. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5233. %
  5234. Add the following entry to the list of \code{passes} in
  5235. \code{run-tests.rkt} and then run this script to test your compiler.
  5236. \begin{lstlisting}
  5237. (list "patch-instructions" patch-instructions interp-x86-1)
  5238. \end{lstlisting}
  5239. \end{exercise}
  5240. \begin{figure}[tbp]
  5241. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5242. \node (Rif) at (0,2) {\large \LangIf{}};
  5243. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5244. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5245. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5246. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5247. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5248. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5249. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5250. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5251. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5252. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5253. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5254. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5255. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5256. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5257. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5258. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5259. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5260. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5261. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5262. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5263. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5264. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5265. \end{tikzpicture}
  5266. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5267. \label{fig:Rif-passes}
  5268. \end{figure}
  5269. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5270. compilation of \LangIf{}.
  5271. \section{An Example Translation}
  5272. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5273. \LangIf{} translated to x86, showing the results of
  5274. \code{explicate-control}, \code{select-instructions}, and the final
  5275. x86 assembly code.
  5276. \begin{figure}[tbp]
  5277. \begin{tabular}{lll}
  5278. \begin{minipage}{0.4\textwidth}
  5279. % cond_test_20.rkt
  5280. \begin{lstlisting}
  5281. (if (eq? (read) 1) 42 0)
  5282. \end{lstlisting}
  5283. $\Downarrow$
  5284. \begin{lstlisting}
  5285. start:
  5286. tmp7951 = (read);
  5287. if (eq? tmp7951 1)
  5288. goto block7952;
  5289. else
  5290. goto block7953;
  5291. block7952:
  5292. return 42;
  5293. block7953:
  5294. return 0;
  5295. \end{lstlisting}
  5296. $\Downarrow$
  5297. \begin{lstlisting}
  5298. start:
  5299. callq read_int
  5300. movq %rax, tmp7951
  5301. cmpq $1, tmp7951
  5302. je block7952
  5303. jmp block7953
  5304. block7953:
  5305. movq $0, %rax
  5306. jmp conclusion
  5307. block7952:
  5308. movq $42, %rax
  5309. jmp conclusion
  5310. \end{lstlisting}
  5311. \end{minipage}
  5312. &
  5313. $\Rightarrow\qquad$
  5314. \begin{minipage}{0.4\textwidth}
  5315. \begin{lstlisting}
  5316. start:
  5317. callq read_int
  5318. movq %rax, %rcx
  5319. cmpq $1, %rcx
  5320. je block7952
  5321. jmp block7953
  5322. block7953:
  5323. movq $0, %rax
  5324. jmp conclusion
  5325. block7952:
  5326. movq $42, %rax
  5327. jmp conclusion
  5328. .globl main
  5329. main:
  5330. pushq %rbp
  5331. movq %rsp, %rbp
  5332. pushq %r13
  5333. pushq %r12
  5334. pushq %rbx
  5335. pushq %r14
  5336. subq $0, %rsp
  5337. jmp start
  5338. conclusion:
  5339. addq $0, %rsp
  5340. popq %r14
  5341. popq %rbx
  5342. popq %r12
  5343. popq %r13
  5344. popq %rbp
  5345. retq
  5346. \end{lstlisting}
  5347. \end{minipage}
  5348. \end{tabular}
  5349. \caption{Example compilation of an \key{if} expression to x86.}
  5350. \label{fig:if-example-x86}
  5351. \end{figure}
  5352. \section{Challenge: Remove Jumps}
  5353. \label{sec:opt-jumps}
  5354. %% Recall that in the example output of \code{explicate-control} in
  5355. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5356. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5357. %% block. The first goal of this challenge assignment is to remove those
  5358. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5359. %% \code{explicate-control} on the left and shows the result of bypassing
  5360. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5361. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5362. %% \code{block55}. The optimized code on the right of
  5363. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5364. %% \code{then} branch jumping directly to \code{block55}. The story is
  5365. %% similar for the \code{else} branch, as well as for the two branches in
  5366. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5367. %% have been optimized in this way, there are no longer any jumps to
  5368. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5369. %% \begin{figure}[tbp]
  5370. %% \begin{tabular}{lll}
  5371. %% \begin{minipage}{0.4\textwidth}
  5372. %% \begin{lstlisting}
  5373. %% block62:
  5374. %% tmp54 = (read);
  5375. %% if (eq? tmp54 2) then
  5376. %% goto block59;
  5377. %% else
  5378. %% goto block60;
  5379. %% block61:
  5380. %% tmp53 = (read);
  5381. %% if (eq? tmp53 0) then
  5382. %% goto block57;
  5383. %% else
  5384. %% goto block58;
  5385. %% block60:
  5386. %% goto block56;
  5387. %% block59:
  5388. %% goto block55;
  5389. %% block58:
  5390. %% goto block56;
  5391. %% block57:
  5392. %% goto block55;
  5393. %% block56:
  5394. %% return (+ 700 77);
  5395. %% block55:
  5396. %% return (+ 10 32);
  5397. %% start:
  5398. %% tmp52 = (read);
  5399. %% if (eq? tmp52 1) then
  5400. %% goto block61;
  5401. %% else
  5402. %% goto block62;
  5403. %% \end{lstlisting}
  5404. %% \end{minipage}
  5405. %% &
  5406. %% $\Rightarrow$
  5407. %% &
  5408. %% \begin{minipage}{0.55\textwidth}
  5409. %% \begin{lstlisting}
  5410. %% block62:
  5411. %% tmp54 = (read);
  5412. %% if (eq? tmp54 2) then
  5413. %% goto block55;
  5414. %% else
  5415. %% goto block56;
  5416. %% block61:
  5417. %% tmp53 = (read);
  5418. %% if (eq? tmp53 0) then
  5419. %% goto block55;
  5420. %% else
  5421. %% goto block56;
  5422. %% block56:
  5423. %% return (+ 700 77);
  5424. %% block55:
  5425. %% return (+ 10 32);
  5426. %% start:
  5427. %% tmp52 = (read);
  5428. %% if (eq? tmp52 1) then
  5429. %% goto block61;
  5430. %% else
  5431. %% goto block62;
  5432. %% \end{lstlisting}
  5433. %% \end{minipage}
  5434. %% \end{tabular}
  5435. %% \caption{Optimize jumps by removing trivial blocks.}
  5436. %% \label{fig:optimize-jumps}
  5437. %% \end{figure}
  5438. %% The name of this pass is \code{optimize-jumps}. We recommend
  5439. %% implementing this pass in two phases. The first phrase builds a hash
  5440. %% table that maps labels to possibly improved labels. The second phase
  5441. %% changes the target of each \code{goto} to use the improved label. If
  5442. %% the label is for a trivial block, then the hash table should map the
  5443. %% label to the first non-trivial block that can be reached from this
  5444. %% label by jumping through trivial blocks. If the label is for a
  5445. %% non-trivial block, then the hash table should map the label to itself;
  5446. %% we do not want to change jumps to non-trivial blocks.
  5447. %% The first phase can be accomplished by constructing an empty hash
  5448. %% table, call it \code{short-cut}, and then iterating over the control
  5449. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5450. %% then update the hash table, mapping the block's source to the target
  5451. %% of the \code{goto}. Also, the hash table may already have mapped some
  5452. %% labels to the block's source, to you must iterate through the hash
  5453. %% table and update all of those so that they instead map to the target
  5454. %% of the \code{goto}.
  5455. %% For the second phase, we recommend iterating through the $\Tail$ of
  5456. %% each block in the program, updating the target of every \code{goto}
  5457. %% according to the mapping in \code{short-cut}.
  5458. %% \begin{exercise}\normalfont
  5459. %% Implement the \code{optimize-jumps} pass as a transformation from
  5460. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5461. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5462. %% example programs. Then check that your compiler still passes all of
  5463. %% your tests.
  5464. %% \end{exercise}
  5465. There is an opportunity for optimizing jumps that is apparent in the
  5466. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5467. ends with a jump to \code{block7953} and there are no other jumps to
  5468. \code{block7953} in the rest of the program. In this situation we can
  5469. avoid the runtime overhead of this jump by merging \code{block7953}
  5470. into the preceding block, in this case the \code{start} block.
  5471. Figure~\ref{fig:remove-jumps} shows the output of
  5472. \code{select-instructions} on the left and the result of this
  5473. optimization on the right.
  5474. \begin{figure}[tbp]
  5475. \begin{tabular}{lll}
  5476. \begin{minipage}{0.5\textwidth}
  5477. % cond_test_20.rkt
  5478. \begin{lstlisting}
  5479. start:
  5480. callq read_int
  5481. movq %rax, tmp7951
  5482. cmpq $1, tmp7951
  5483. je block7952
  5484. jmp block7953
  5485. block7953:
  5486. movq $0, %rax
  5487. jmp conclusion
  5488. block7952:
  5489. movq $42, %rax
  5490. jmp conclusion
  5491. \end{lstlisting}
  5492. \end{minipage}
  5493. &
  5494. $\Rightarrow\qquad$
  5495. \begin{minipage}{0.4\textwidth}
  5496. \begin{lstlisting}
  5497. start:
  5498. callq read_int
  5499. movq %rax, tmp7951
  5500. cmpq $1, tmp7951
  5501. je block7952
  5502. movq $0, %rax
  5503. jmp conclusion
  5504. block7952:
  5505. movq $42, %rax
  5506. jmp conclusion
  5507. \end{lstlisting}
  5508. \end{minipage}
  5509. \end{tabular}
  5510. \caption{Merging basic blocks by removing unnecessary jumps.}
  5511. \label{fig:remove-jumps}
  5512. \end{figure}
  5513. \begin{exercise}\normalfont
  5514. %
  5515. Implement a pass named \code{remove-jumps} that merges basic blocks
  5516. into their preceding basic block, when there is only one preceding
  5517. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5518. %
  5519. In the \code{run-tests.rkt} script, add the following entry to the
  5520. list of \code{passes} between \code{allocate-registers}
  5521. and \code{patch-instructions}.
  5522. \begin{lstlisting}
  5523. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5524. \end{lstlisting}
  5525. Run this script to test your compiler.
  5526. %
  5527. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5528. blocks on several test programs.
  5529. \end{exercise}
  5530. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5531. \chapter{Tuples and Garbage Collection}
  5532. \label{ch:Rvec}
  5533. \index{subject}{tuple}
  5534. \index{subject}{vector}
  5535. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5536. %% all the IR grammars are spelled out! \\ --Jeremy}
  5537. %% \margincomment{\scriptsize Be more explicit about how to deal with
  5538. %% the root stack. \\ --Jeremy}
  5539. In this chapter we study the implementation of mutable tuples, called
  5540. vectors in Racket. This language feature is the first to use the
  5541. computer's \emph{heap}\index{subject}{heap} because the lifetime of a Racket
  5542. tuple is indefinite, that is, a tuple lives forever from the
  5543. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5544. is important to reclaim the space associated with a tuple when it is
  5545. no longer needed, which is why we also study \emph{garbage collection}
  5546. \emph{garbage collection} techniques in this chapter.
  5547. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5548. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5549. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  5550. \code{void} value. The reason for including the later is that the
  5551. \code{vector-set!} operation returns a value of type
  5552. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5553. called the \code{Unit} type in the programming languages
  5554. literature. Racket's \code{Void} type is inhabited by a single value
  5555. \code{void} which corresponds to \code{unit} or \code{()} in the
  5556. literature~\citep{Pierce:2002hj}.}.
  5557. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5558. copying live objects back and forth between two halves of the
  5559. heap. The garbage collector requires coordination with the compiler so
  5560. that it can see all of the \emph{root} pointers, that is, pointers in
  5561. registers or on the procedure call stack.
  5562. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5563. discuss all the necessary changes and additions to the compiler
  5564. passes, including a new compiler pass named \code{expose-allocation}.
  5565. \section{The \LangVec{} Language}
  5566. \label{sec:r3}
  5567. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5568. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5569. \LangVec{} language includes three new forms: \code{vector} for creating a
  5570. tuple, \code{vector-ref} for reading an element of a tuple, and
  5571. \code{vector-set!} for writing to an element of a tuple. The program
  5572. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5573. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5574. the 3-tuple, demonstrating that tuples are first-class values. The
  5575. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5576. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5577. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5578. 1-tuple. So the result of the program is \code{42}.
  5579. \begin{figure}[tbp]
  5580. \centering
  5581. \fbox{
  5582. \begin{minipage}{0.96\textwidth}
  5583. \[
  5584. \begin{array}{lcl}
  5585. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5586. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5587. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5588. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5589. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5590. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5591. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5592. \mid \LP\key{not}\;\Exp\RP } \\
  5593. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5594. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5595. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5596. \mid \LP\key{vector-length}\;\Exp\RP \\
  5597. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5598. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5599. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5600. \LangVecM{} &::=& \Exp
  5601. \end{array}
  5602. \]
  5603. \end{minipage}
  5604. }
  5605. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5606. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5607. \label{fig:Rvec-concrete-syntax}
  5608. \end{figure}
  5609. \begin{figure}[tbp]
  5610. \begin{lstlisting}
  5611. (let ([t (vector 40 #t (vector 2))])
  5612. (if (vector-ref t 1)
  5613. (+ (vector-ref t 0)
  5614. (vector-ref (vector-ref t 2) 0))
  5615. 44))
  5616. \end{lstlisting}
  5617. \caption{Example program that creates tuples and reads from them.}
  5618. \label{fig:vector-eg}
  5619. \end{figure}
  5620. \begin{figure}[tp]
  5621. \centering
  5622. \fbox{
  5623. \begin{minipage}{0.96\textwidth}
  5624. \[
  5625. \begin{array}{lcl}
  5626. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5627. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5628. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5629. \mid \BOOL{\itm{bool}}
  5630. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5631. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5632. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5633. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5634. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5635. \end{array}
  5636. \]
  5637. \end{minipage}
  5638. }
  5639. \caption{The abstract syntax of \LangVec{}.}
  5640. \label{fig:Rvec-syntax}
  5641. \end{figure}
  5642. \index{subject}{allocate}
  5643. \index{subject}{heap allocate}
  5644. Tuples are our first encounter with heap-allocated data, which raises
  5645. several interesting issues. First, variable binding performs a
  5646. shallow-copy when dealing with tuples, which means that different
  5647. variables can refer to the same tuple, that is, different variables
  5648. can be \emph{aliases} for the same entity. Consider the following
  5649. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5650. Thus, the mutation through \code{t2} is visible when referencing the
  5651. tuple from \code{t1}, so the result of this program is \code{42}.
  5652. \index{subject}{alias}\index{subject}{mutation}
  5653. \begin{center}
  5654. \begin{minipage}{0.96\textwidth}
  5655. \begin{lstlisting}
  5656. (let ([t1 (vector 3 7)])
  5657. (let ([t2 t1])
  5658. (let ([_ (vector-set! t2 0 42)])
  5659. (vector-ref t1 0))))
  5660. \end{lstlisting}
  5661. \end{minipage}
  5662. \end{center}
  5663. The next issue concerns the lifetime of tuples. Of course, they are
  5664. created by the \code{vector} form, but when does their lifetime end?
  5665. Notice that \LangVec{} does not include an operation for deleting
  5666. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5667. of static scoping. For example, the following program returns
  5668. \code{42} even though the variable \code{w} goes out of scope prior to
  5669. the \code{vector-ref} that reads from the vector it was bound to.
  5670. \begin{center}
  5671. \begin{minipage}{0.96\textwidth}
  5672. \begin{lstlisting}
  5673. (let ([v (vector (vector 44))])
  5674. (let ([x (let ([w (vector 42)])
  5675. (let ([_ (vector-set! v 0 w)])
  5676. 0))])
  5677. (+ x (vector-ref (vector-ref v 0) 0))))
  5678. \end{lstlisting}
  5679. \end{minipage}
  5680. \end{center}
  5681. From the perspective of programmer-observable behavior, tuples live
  5682. forever. Of course, if they really lived forever, then many programs
  5683. would run out of memory.\footnote{The \LangVec{} language does not have
  5684. looping or recursive functions, so it is nigh impossible to write a
  5685. program in \LangVec{} that will run out of memory. However, we add
  5686. recursive functions in the next Chapter!} A Racket implementation
  5687. must therefore perform automatic garbage collection.
  5688. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5689. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5690. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5691. terms of the corresponding operations in Racket. One subtle point is
  5692. that the \code{vector-set!} operation returns the \code{\#<void>}
  5693. value. The \code{\#<void>} value can be passed around just like other
  5694. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5695. compared for equality with another \code{\#<void>} value. However,
  5696. there are no other operations specific to the the \code{\#<void>}
  5697. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5698. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5699. otherwise.
  5700. \begin{figure}[tbp]
  5701. \begin{lstlisting}
  5702. (define interp-Rvec-class
  5703. (class interp-Rif-class
  5704. (super-new)
  5705. (define/override (interp-op op)
  5706. (match op
  5707. ['eq? (lambda (v1 v2)
  5708. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5709. (and (boolean? v1) (boolean? v2))
  5710. (and (vector? v1) (vector? v2))
  5711. (and (void? v1) (void? v2)))
  5712. (eq? v1 v2)]))]
  5713. ['vector vector]
  5714. ['vector-length vector-length]
  5715. ['vector-ref vector-ref]
  5716. ['vector-set! vector-set!]
  5717. [else (super interp-op op)]
  5718. ))
  5719. (define/override ((interp-exp env) e)
  5720. (define recur (interp-exp env))
  5721. (match e
  5722. [(HasType e t) (recur e)]
  5723. [(Void) (void)]
  5724. [else ((super interp-exp env) e)]
  5725. ))
  5726. ))
  5727. (define (interp-Rvec p)
  5728. (send (new interp-Rvec-class) interp-program p))
  5729. \end{lstlisting}
  5730. \caption{Interpreter for the \LangVec{} language.}
  5731. \label{fig:interp-Rvec}
  5732. \end{figure}
  5733. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5734. deserves some explanation. When allocating a vector, we need to know
  5735. which elements of the vector are pointers (i.e. are also vectors). We
  5736. can obtain this information during type checking. The type checker in
  5737. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5738. expression, it also wraps every \key{vector} creation with the form
  5739. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5740. %
  5741. To create the s-expression for the \code{Vector} type in
  5742. Figure~\ref{fig:type-check-Rvec}, we use the
  5743. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5744. operator} \code{,@} to insert the list \code{t*} without its usual
  5745. start and end parentheses. \index{subject}{unquote-slicing}
  5746. \begin{figure}[tp]
  5747. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5748. (define type-check-Rvec-class
  5749. (class type-check-Rif-class
  5750. (super-new)
  5751. (inherit check-type-equal?)
  5752. (define/override (type-check-exp env)
  5753. (lambda (e)
  5754. (define recur (type-check-exp env))
  5755. (match e
  5756. [(Void) (values (Void) 'Void)]
  5757. [(Prim 'vector es)
  5758. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5759. (define t `(Vector ,@t*))
  5760. (values (HasType (Prim 'vector e*) t) t)]
  5761. [(Prim 'vector-ref (list e1 (Int i)))
  5762. (define-values (e1^ t) (recur e1))
  5763. (match t
  5764. [`(Vector ,ts ...)
  5765. (unless (and (0 . <= . i) (i . < . (length ts)))
  5766. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5767. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5768. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5769. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5770. (define-values (e-vec t-vec) (recur e1))
  5771. (define-values (e-arg^ t-arg) (recur arg))
  5772. (match t-vec
  5773. [`(Vector ,ts ...)
  5774. (unless (and (0 . <= . i) (i . < . (length ts)))
  5775. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5776. (check-type-equal? (list-ref ts i) t-arg e)
  5777. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5778. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5779. [(Prim 'vector-length (list e))
  5780. (define-values (e^ t) (recur e))
  5781. (match t
  5782. [`(Vector ,ts ...)
  5783. (values (Prim 'vector-length (list e^)) 'Integer)]
  5784. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5785. [(Prim 'eq? (list arg1 arg2))
  5786. (define-values (e1 t1) (recur arg1))
  5787. (define-values (e2 t2) (recur arg2))
  5788. (match* (t1 t2)
  5789. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5790. [(other wise) (check-type-equal? t1 t2 e)])
  5791. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5792. [(HasType (Prim 'vector es) t)
  5793. ((type-check-exp env) (Prim 'vector es))]
  5794. [(HasType e1 t)
  5795. (define-values (e1^ t^) (recur e1))
  5796. (check-type-equal? t t^ e)
  5797. (values (HasType e1^ t) t)]
  5798. [else ((super type-check-exp env) e)]
  5799. )))
  5800. ))
  5801. (define (type-check-Rvec p)
  5802. (send (new type-check-Rvec-class) type-check-program p))
  5803. \end{lstlisting}
  5804. \caption{Type checker for the \LangVec{} language.}
  5805. \label{fig:type-check-Rvec}
  5806. \end{figure}
  5807. \section{Garbage Collection}
  5808. \label{sec:GC}
  5809. Here we study a relatively simple algorithm for garbage collection
  5810. that is the basis of state-of-the-art garbage
  5811. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5812. particular, we describe a two-space copying
  5813. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5814. perform the
  5815. copy~\citep{Cheney:1970aa}.
  5816. \index{subject}{copying collector}
  5817. \index{subject}{two-space copying collector}
  5818. Figure~\ref{fig:copying-collector} gives a
  5819. coarse-grained depiction of what happens in a two-space collector,
  5820. showing two time steps, prior to garbage collection (on the top) and
  5821. after garbage collection (on the bottom). In a two-space collector,
  5822. the heap is divided into two parts named the FromSpace and the
  5823. ToSpace. Initially, all allocations go to the FromSpace until there is
  5824. not enough room for the next allocation request. At that point, the
  5825. garbage collector goes to work to make more room.
  5826. \index{subject}{ToSpace}
  5827. \index{subject}{FromSpace}
  5828. The garbage collector must be careful not to reclaim tuples that will
  5829. be used by the program in the future. Of course, it is impossible in
  5830. general to predict what a program will do, but we can over approximate
  5831. the will-be-used tuples by preserving all tuples that could be
  5832. accessed by \emph{any} program given the current computer state. A
  5833. program could access any tuple whose address is in a register or on
  5834. the procedure call stack. These addresses are called the \emph{root
  5835. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  5836. transitively reachable from the root set. Thus, it is safe for the
  5837. garbage collector to reclaim the tuples that are not reachable in this
  5838. way.
  5839. So the goal of the garbage collector is twofold:
  5840. \begin{enumerate}
  5841. \item preserve all tuple that are reachable from the root set via a
  5842. path of pointers, that is, the \emph{live} tuples, and
  5843. \item reclaim the memory of everything else, that is, the
  5844. \emph{garbage}.
  5845. \end{enumerate}
  5846. A copying collector accomplishes this by copying all of the live
  5847. objects from the FromSpace into the ToSpace and then performs a sleight
  5848. of hand, treating the ToSpace as the new FromSpace and the old
  5849. FromSpace as the new ToSpace. In the example of
  5850. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5851. root set, one in a register and two on the stack. All of the live
  5852. objects have been copied to the ToSpace (the right-hand side of
  5853. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5854. pointer relationships. For example, the pointer in the register still
  5855. points to a 2-tuple whose first element is a 3-tuple and whose second
  5856. element is a 2-tuple. There are four tuples that are not reachable
  5857. from the root set and therefore do not get copied into the ToSpace.
  5858. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5859. created by a well-typed program in \LangVec{} because it contains a
  5860. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5861. We design the garbage collector to deal with cycles to begin with so
  5862. we will not need to revisit this issue.
  5863. \begin{figure}[tbp]
  5864. \centering
  5865. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5866. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5867. \caption{A copying collector in action.}
  5868. \label{fig:copying-collector}
  5869. \end{figure}
  5870. There are many alternatives to copying collectors (and their bigger
  5871. siblings, the generational collectors) when its comes to garbage
  5872. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5873. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5874. collectors are that allocation is fast (just a comparison and pointer
  5875. increment), there is no fragmentation, cyclic garbage is collected,
  5876. and the time complexity of collection only depends on the amount of
  5877. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5878. main disadvantages of a two-space copying collector is that it uses a
  5879. lot of space and takes a long time to perform the copy, though these
  5880. problems are ameliorated in generational collectors. Racket and
  5881. Scheme programs tend to allocate many small objects and generate a lot
  5882. of garbage, so copying and generational collectors are a good fit.
  5883. Garbage collection is an active research topic, especially concurrent
  5884. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5885. developing new techniques and revisiting old
  5886. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5887. meet every year at the International Symposium on Memory Management to
  5888. present these findings.
  5889. \subsection{Graph Copying via Cheney's Algorithm}
  5890. \label{sec:cheney}
  5891. \index{subject}{Cheney's algorithm}
  5892. Let us take a closer look at the copying of the live objects. The
  5893. allocated objects and pointers can be viewed as a graph and we need to
  5894. copy the part of the graph that is reachable from the root set. To
  5895. make sure we copy all of the reachable vertices in the graph, we need
  5896. an exhaustive graph traversal algorithm, such as depth-first search or
  5897. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5898. such algorithms take into account the possibility of cycles by marking
  5899. which vertices have already been visited, so as to ensure termination
  5900. of the algorithm. These search algorithms also use a data structure
  5901. such as a stack or queue as a to-do list to keep track of the vertices
  5902. that need to be visited. We use breadth-first search and a trick
  5903. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5904. and copying tuples into the ToSpace.
  5905. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5906. copy progresses. The queue is represented by a chunk of contiguous
  5907. memory at the beginning of the ToSpace, using two pointers to track
  5908. the front and the back of the queue. The algorithm starts by copying
  5909. all tuples that are immediately reachable from the root set into the
  5910. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5911. old tuple to indicate that it has been visited. We discuss how this
  5912. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5913. pointers inside the copied tuples in the queue still point back to the
  5914. FromSpace. Once the initial queue has been created, the algorithm
  5915. enters a loop in which it repeatedly processes the tuple at the front
  5916. of the queue and pops it off the queue. To process a tuple, the
  5917. algorithm copies all the tuple that are directly reachable from it to
  5918. the ToSpace, placing them at the back of the queue. The algorithm then
  5919. updates the pointers in the popped tuple so they point to the newly
  5920. copied tuples.
  5921. \begin{figure}[tbp]
  5922. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5923. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5924. \label{fig:cheney}
  5925. \end{figure}
  5926. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5927. tuple whose second element is $42$ to the back of the queue. The other
  5928. pointer goes to a tuple that has already been copied, so we do not
  5929. need to copy it again, but we do need to update the pointer to the new
  5930. location. This can be accomplished by storing a \emph{forwarding
  5931. pointer} to the new location in the old tuple, back when we initially
  5932. copied the tuple into the ToSpace. This completes one step of the
  5933. algorithm. The algorithm continues in this way until the front of the
  5934. queue is empty, that is, until the front catches up with the back.
  5935. \subsection{Data Representation}
  5936. \label{sec:data-rep-gc}
  5937. The garbage collector places some requirements on the data
  5938. representations used by our compiler. First, the garbage collector
  5939. needs to distinguish between pointers and other kinds of data. There
  5940. are several ways to accomplish this.
  5941. \begin{enumerate}
  5942. \item Attached a tag to each object that identifies what type of
  5943. object it is~\citep{McCarthy:1960dz}.
  5944. \item Store different types of objects in different
  5945. regions~\citep{Steele:1977ab}.
  5946. \item Use type information from the program to either generate
  5947. type-specific code for collecting or to generate tables that can
  5948. guide the
  5949. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5950. \end{enumerate}
  5951. Dynamically typed languages, such as Lisp, need to tag objects
  5952. anyways, so option 1 is a natural choice for those languages.
  5953. However, \LangVec{} is a statically typed language, so it would be
  5954. unfortunate to require tags on every object, especially small and
  5955. pervasive objects like integers and Booleans. Option 3 is the
  5956. best-performing choice for statically typed languages, but comes with
  5957. a relatively high implementation complexity. To keep this chapter
  5958. within a 2-week time budget, we recommend a combination of options 1
  5959. and 2, using separate strategies for the stack and the heap.
  5960. Regarding the stack, we recommend using a separate stack for pointers,
  5961. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  5962. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5963. is, when a local variable needs to be spilled and is of type
  5964. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5965. stack instead of the normal procedure call stack. Furthermore, we
  5966. always spill vector-typed variables if they are live during a call to
  5967. the collector, thereby ensuring that no pointers are in registers
  5968. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5969. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5970. the data layout using a root stack. The root stack contains the two
  5971. pointers from the regular stack and also the pointer in the second
  5972. register.
  5973. \begin{figure}[tbp]
  5974. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5975. \caption{Maintaining a root stack to facilitate garbage collection.}
  5976. \label{fig:shadow-stack}
  5977. \end{figure}
  5978. The problem of distinguishing between pointers and other kinds of data
  5979. also arises inside of each tuple on the heap. We solve this problem by
  5980. attaching a tag, an extra 64-bits, to each
  5981. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5982. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5983. that we have drawn the bits in a big-endian way, from right-to-left,
  5984. with bit location 0 (the least significant bit) on the far right,
  5985. which corresponds to the direction of the x86 shifting instructions
  5986. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5987. is dedicated to specifying which elements of the tuple are pointers,
  5988. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5989. indicates there is a pointer and a 0 bit indicates some other kind of
  5990. data. The pointer mask starts at bit location 7. We have limited
  5991. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5992. the pointer mask. The tag also contains two other pieces of
  5993. information. The length of the tuple (number of elements) is stored in
  5994. bits location 1 through 6. Finally, the bit at location 0 indicates
  5995. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5996. value 1, then this tuple has not yet been copied. If the bit has
  5997. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5998. of a pointer are always zero anyways because our tuples are 8-byte
  5999. aligned.)
  6000. \begin{figure}[tbp]
  6001. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6002. \caption{Representation of tuples in the heap.}
  6003. \label{fig:tuple-rep}
  6004. \end{figure}
  6005. \subsection{Implementation of the Garbage Collector}
  6006. \label{sec:organize-gz}
  6007. \index{subject}{prelude}
  6008. An implementation of the copying collector is provided in the
  6009. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6010. interface to the garbage collector that is used by the compiler. The
  6011. \code{initialize} function creates the FromSpace, ToSpace, and root
  6012. stack and should be called in the prelude of the \code{main}
  6013. function. The arguments of \code{initialize} are the root stack size
  6014. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6015. good choice for both. The \code{initialize} function puts the address
  6016. of the beginning of the FromSpace into the global variable
  6017. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6018. the address that is 1-past the last element of the FromSpace. (We use
  6019. half-open intervals to represent chunks of
  6020. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6021. points to the first element of the root stack.
  6022. As long as there is room left in the FromSpace, your generated code
  6023. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6024. %
  6025. The amount of room left in FromSpace is the difference between the
  6026. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6027. function should be called when there is not enough room left in the
  6028. FromSpace for the next allocation. The \code{collect} function takes
  6029. a pointer to the current top of the root stack (one past the last item
  6030. that was pushed) and the number of bytes that need to be
  6031. allocated. The \code{collect} function performs the copying collection
  6032. and leaves the heap in a state such that the next allocation will
  6033. succeed.
  6034. \begin{figure}[tbp]
  6035. \begin{lstlisting}
  6036. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6037. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6038. int64_t* free_ptr;
  6039. int64_t* fromspace_begin;
  6040. int64_t* fromspace_end;
  6041. int64_t** rootstack_begin;
  6042. \end{lstlisting}
  6043. \caption{The compiler's interface to the garbage collector.}
  6044. \label{fig:gc-header}
  6045. \end{figure}
  6046. %% \begin{exercise}
  6047. %% In the file \code{runtime.c} you will find the implementation of
  6048. %% \code{initialize} and a partial implementation of \code{collect}.
  6049. %% The \code{collect} function calls another function, \code{cheney},
  6050. %% to perform the actual copy, and that function is left to the reader
  6051. %% to implement. The following is the prototype for \code{cheney}.
  6052. %% \begin{lstlisting}
  6053. %% static void cheney(int64_t** rootstack_ptr);
  6054. %% \end{lstlisting}
  6055. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6056. %% rootstack (which is an array of pointers). The \code{cheney} function
  6057. %% also communicates with \code{collect} through the global
  6058. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6059. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6060. %% the ToSpace:
  6061. %% \begin{lstlisting}
  6062. %% static int64_t* tospace_begin;
  6063. %% static int64_t* tospace_end;
  6064. %% \end{lstlisting}
  6065. %% The job of the \code{cheney} function is to copy all the live
  6066. %% objects (reachable from the root stack) into the ToSpace, update
  6067. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6068. %% update the root stack so that it points to the objects in the
  6069. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6070. %% and ToSpace.
  6071. %% \end{exercise}
  6072. %% \section{Compiler Passes}
  6073. %% \label{sec:code-generation-gc}
  6074. The introduction of garbage collection has a non-trivial impact on our
  6075. compiler passes. We introduce a new compiler pass named
  6076. \code{expose-allocation}. We make
  6077. significant changes to \code{select-instructions},
  6078. \code{build-interference}, \code{allocate-registers}, and
  6079. \code{print-x86} and make minor changes in several more passes. The
  6080. following program will serve as our running example. It creates two
  6081. tuples, one nested inside the other. Both tuples have length one. The
  6082. program accesses the element in the inner tuple tuple via two vector
  6083. references.
  6084. % tests/s2_17.rkt
  6085. \begin{lstlisting}
  6086. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6087. \end{lstlisting}
  6088. \section{Shrink}
  6089. \label{sec:shrink-Rvec}
  6090. Recall that the \code{shrink} pass translates the primitives operators
  6091. into a smaller set of primitives. Because this pass comes after type
  6092. checking, but before the passes that require the type information in
  6093. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6094. to wrap \code{HasType} around each AST node that it generates.
  6095. \section{Expose Allocation}
  6096. \label{sec:expose-allocation}
  6097. The pass \code{expose-allocation} lowers the \code{vector} creation
  6098. form into a conditional call to the collector followed by the
  6099. allocation. We choose to place the \code{expose-allocation} pass
  6100. before \code{remove-complex-opera*} because the code generated by
  6101. \code{expose-allocation} contains complex operands. We also place
  6102. \code{expose-allocation} before \code{explicate-control} because
  6103. \code{expose-allocation} introduces new variables using \code{let},
  6104. but \code{let} is gone after \code{explicate-control}.
  6105. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6106. extends \LangVec{} with the three new forms that we use in the translation
  6107. of the \code{vector} form.
  6108. \[
  6109. \begin{array}{lcl}
  6110. \Exp &::=& \cdots
  6111. \mid (\key{collect} \,\itm{int})
  6112. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6113. \mid (\key{global-value} \,\itm{name})
  6114. \end{array}
  6115. \]
  6116. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6117. $n$ bytes. It will become a call to the \code{collect} function in
  6118. \code{runtime.c} in \code{select-instructions}. The
  6119. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6120. \index{subject}{allocate}
  6121. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6122. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6123. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6124. a global variable, such as \code{free\_ptr}.
  6125. In the following, we show the transformation for the \code{vector}
  6126. form into 1) a sequence of let-bindings for the initializing
  6127. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6128. \code{allocate}, and 4) the initialization of the vector. In the
  6129. following, \itm{len} refers to the length of the vector and
  6130. \itm{bytes} is how many total bytes need to be allocated for the
  6131. vector, which is 8 for the tag plus \itm{len} times 8.
  6132. \begin{lstlisting}
  6133. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6134. |$\Longrightarrow$|
  6135. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6136. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6137. (global-value fromspace_end))
  6138. (void)
  6139. (collect |\itm{bytes}|))])
  6140. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6141. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6142. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6143. |$v$|) ... )))) ...)
  6144. \end{lstlisting}
  6145. In the above, we suppressed all of the \code{has-type} forms in the
  6146. output for the sake of readability. The placement of the initializing
  6147. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6148. sequence of \code{vector-set!} is important, as those expressions may
  6149. trigger garbage collection and we cannot have an allocated but
  6150. uninitialized tuple on the heap during a collection.
  6151. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6152. \code{expose-allocation} pass on our running example.
  6153. \begin{figure}[tbp]
  6154. % tests/s2_17.rkt
  6155. \begin{lstlisting}
  6156. (vector-ref
  6157. (vector-ref
  6158. (let ([vecinit7976
  6159. (let ([vecinit7972 42])
  6160. (let ([collectret7974
  6161. (if (< (+ (global-value free_ptr) 16)
  6162. (global-value fromspace_end))
  6163. (void)
  6164. (collect 16)
  6165. )])
  6166. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6167. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6168. alloc7971)
  6169. )
  6170. )
  6171. )
  6172. ])
  6173. (let ([collectret7978
  6174. (if (< (+ (global-value free_ptr) 16)
  6175. (global-value fromspace_end))
  6176. (void)
  6177. (collect 16)
  6178. )])
  6179. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6180. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6181. alloc7975)
  6182. )
  6183. )
  6184. )
  6185. 0)
  6186. 0)
  6187. \end{lstlisting}
  6188. \caption{Output of the \code{expose-allocation} pass, minus
  6189. all of the \code{has-type} forms.}
  6190. \label{fig:expose-alloc-output}
  6191. \end{figure}
  6192. \section{Remove Complex Operands}
  6193. \label{sec:remove-complex-opera-Rvec}
  6194. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6195. should all be treated as complex operands.
  6196. %% A new case for
  6197. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6198. %% handled carefully to prevent the \code{Prim} node from being separated
  6199. %% from its enclosing \code{HasType}.
  6200. Figure~\ref{fig:Rvec-anf-syntax}
  6201. shows the grammar for the output language \LangVecANF{} of this
  6202. pass, which is \LangVec{} in administrative normal form.
  6203. \begin{figure}[tp]
  6204. \centering
  6205. \fbox{
  6206. \begin{minipage}{0.96\textwidth}
  6207. \small
  6208. \[
  6209. \begin{array}{rcl}
  6210. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6211. \mid \VOID{} \\
  6212. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6213. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6214. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6215. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6216. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6217. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6218. \mid \LP\key{GlobalValue}~\Var\RP\\
  6219. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6220. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6221. \end{array}
  6222. \]
  6223. \end{minipage}
  6224. }
  6225. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6226. \label{fig:Rvec-anf-syntax}
  6227. \end{figure}
  6228. \section{Explicate Control and the \LangCVec{} language}
  6229. \label{sec:explicate-control-r3}
  6230. \begin{figure}[tp]
  6231. \fbox{
  6232. \begin{minipage}{0.96\textwidth}
  6233. \small
  6234. \[
  6235. \begin{array}{lcl}
  6236. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6237. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6238. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6239. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6240. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6241. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6242. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6243. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6244. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6245. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6246. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6247. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6248. \mid \GOTO{\itm{label}} } \\
  6249. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6250. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6251. \end{array}
  6252. \]
  6253. \end{minipage}
  6254. }
  6255. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6256. (Figure~\ref{fig:c1-syntax}).}
  6257. \label{fig:c2-syntax}
  6258. \end{figure}
  6259. The output of \code{explicate-control} is a program in the
  6260. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6261. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6262. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6263. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6264. \key{vector-set!}, and \key{global-value} expressions and the
  6265. \code{collect} statement. The \code{explicate-control} pass can treat
  6266. these new forms much like the other expression forms that we've
  6267. already encoutered.
  6268. \section{Select Instructions and the \LangXGlobal{} Language}
  6269. \label{sec:select-instructions-gc}
  6270. \index{subject}{instruction selection}
  6271. %% void (rep as zero)
  6272. %% allocate
  6273. %% collect (callq collect)
  6274. %% vector-ref
  6275. %% vector-set!
  6276. %% global (postpone)
  6277. In this pass we generate x86 code for most of the new operations that
  6278. were needed to compile tuples, including \code{Allocate},
  6279. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6280. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6281. the later has a different concrete syntax (see
  6282. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6283. \index{subject}{x86}
  6284. The \code{vector-ref} and \code{vector-set!} forms translate into
  6285. \code{movq} instructions. (The plus one in the offset is to get past
  6286. the tag at the beginning of the tuple representation.)
  6287. \begin{lstlisting}
  6288. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6289. |$\Longrightarrow$|
  6290. movq |$\itm{vec}'$|, %r11
  6291. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6292. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6293. |$\Longrightarrow$|
  6294. movq |$\itm{vec}'$|, %r11
  6295. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6296. movq $0, |$\itm{lhs'}$|
  6297. \end{lstlisting}
  6298. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6299. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6300. register \code{r11} ensures that offset expression
  6301. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6302. removing \code{r11} from consideration by the register allocating.
  6303. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6304. \code{rax}. Then the generated code for \code{vector-set!} would be
  6305. \begin{lstlisting}
  6306. movq |$\itm{vec}'$|, %rax
  6307. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6308. movq $0, |$\itm{lhs}'$|
  6309. \end{lstlisting}
  6310. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6311. \code{patch-instructions} would insert a move through \code{rax}
  6312. as follows.
  6313. \begin{lstlisting}
  6314. movq |$\itm{vec}'$|, %rax
  6315. movq |$\itm{arg}'$|, %rax
  6316. movq %rax, |$8(n+1)$|(%rax)
  6317. movq $0, |$\itm{lhs}'$|
  6318. \end{lstlisting}
  6319. But the above sequence of instructions does not work because we're
  6320. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6321. $\itm{arg}'$) at the same time!
  6322. We compile the \code{allocate} form to operations on the
  6323. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6324. is the next free address in the FromSpace, so we copy it into
  6325. \code{r11} and then move it forward by enough space for the tuple
  6326. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6327. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6328. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6329. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6330. tag is organized. We recommend using the Racket operations
  6331. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6332. during compilation. The type annotation in the \code{vector} form is
  6333. used to determine the pointer mask region of the tag.
  6334. \begin{lstlisting}
  6335. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6336. |$\Longrightarrow$|
  6337. movq free_ptr(%rip), %r11
  6338. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6339. movq $|$\itm{tag}$|, 0(%r11)
  6340. movq %r11, |$\itm{lhs}'$|
  6341. \end{lstlisting}
  6342. The \code{collect} form is compiled to a call to the \code{collect}
  6343. function in the runtime. The arguments to \code{collect} are 1) the
  6344. top of the root stack and 2) the number of bytes that need to be
  6345. allocated. We use another dedicated register, \code{r15}, to
  6346. store the pointer to the top of the root stack. So \code{r15} is not
  6347. available for use by the register allocator.
  6348. \begin{lstlisting}
  6349. (collect |$\itm{bytes}$|)
  6350. |$\Longrightarrow$|
  6351. movq %r15, %rdi
  6352. movq $|\itm{bytes}|, %rsi
  6353. callq collect
  6354. \end{lstlisting}
  6355. \begin{figure}[tp]
  6356. \fbox{
  6357. \begin{minipage}{0.96\textwidth}
  6358. \[
  6359. \begin{array}{lcl}
  6360. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6361. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  6362. & & \gray{ \key{main:} \; \Instr\ldots }
  6363. \end{array}
  6364. \]
  6365. \end{minipage}
  6366. }
  6367. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6368. \label{fig:x86-2-concrete}
  6369. \end{figure}
  6370. \begin{figure}[tp]
  6371. \fbox{
  6372. \begin{minipage}{0.96\textwidth}
  6373. \small
  6374. \[
  6375. \begin{array}{lcl}
  6376. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6377. \mid \BYTEREG{\Reg}} \\
  6378. &\mid& (\key{Global}~\Var) \\
  6379. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6380. \end{array}
  6381. \]
  6382. \end{minipage}
  6383. }
  6384. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6385. \label{fig:x86-2}
  6386. \end{figure}
  6387. The concrete and abstract syntax of the \LangXGlobal{} language is
  6388. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6389. differs from \LangXIf{} just in the addition of the form for global
  6390. variables.
  6391. %
  6392. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6393. \code{select-instructions} pass on the running example.
  6394. \begin{figure}[tbp]
  6395. \centering
  6396. % tests/s2_17.rkt
  6397. \begin{minipage}[t]{0.5\textwidth}
  6398. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6399. block35:
  6400. movq free_ptr(%rip), alloc9024
  6401. addq $16, free_ptr(%rip)
  6402. movq alloc9024, %r11
  6403. movq $131, 0(%r11)
  6404. movq alloc9024, %r11
  6405. movq vecinit9025, 8(%r11)
  6406. movq $0, initret9026
  6407. movq alloc9024, %r11
  6408. movq 8(%r11), tmp9034
  6409. movq tmp9034, %r11
  6410. movq 8(%r11), %rax
  6411. jmp conclusion
  6412. block36:
  6413. movq $0, collectret9027
  6414. jmp block35
  6415. block38:
  6416. movq free_ptr(%rip), alloc9020
  6417. addq $16, free_ptr(%rip)
  6418. movq alloc9020, %r11
  6419. movq $3, 0(%r11)
  6420. movq alloc9020, %r11
  6421. movq vecinit9021, 8(%r11)
  6422. movq $0, initret9022
  6423. movq alloc9020, vecinit9025
  6424. movq free_ptr(%rip), tmp9031
  6425. movq tmp9031, tmp9032
  6426. addq $16, tmp9032
  6427. movq fromspace_end(%rip), tmp9033
  6428. cmpq tmp9033, tmp9032
  6429. jl block36
  6430. jmp block37
  6431. block37:
  6432. movq %r15, %rdi
  6433. movq $16, %rsi
  6434. callq 'collect
  6435. jmp block35
  6436. block39:
  6437. movq $0, collectret9023
  6438. jmp block38
  6439. \end{lstlisting}
  6440. \end{minipage}
  6441. \begin{minipage}[t]{0.45\textwidth}
  6442. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6443. start:
  6444. movq $42, vecinit9021
  6445. movq free_ptr(%rip), tmp9028
  6446. movq tmp9028, tmp9029
  6447. addq $16, tmp9029
  6448. movq fromspace_end(%rip), tmp9030
  6449. cmpq tmp9030, tmp9029
  6450. jl block39
  6451. jmp block40
  6452. block40:
  6453. movq %r15, %rdi
  6454. movq $16, %rsi
  6455. callq 'collect
  6456. jmp block38
  6457. \end{lstlisting}
  6458. \end{minipage}
  6459. \caption{Output of the \code{select-instructions} pass.}
  6460. \label{fig:select-instr-output-gc}
  6461. \end{figure}
  6462. \clearpage
  6463. \section{Register Allocation}
  6464. \label{sec:reg-alloc-gc}
  6465. \index{subject}{register allocation}
  6466. As discussed earlier in this chapter, the garbage collector needs to
  6467. access all the pointers in the root set, that is, all variables that
  6468. are vectors. It will be the responsibility of the register allocator
  6469. to make sure that:
  6470. \begin{enumerate}
  6471. \item the root stack is used for spilling vector-typed variables, and
  6472. \item if a vector-typed variable is live during a call to the
  6473. collector, it must be spilled to ensure it is visible to the
  6474. collector.
  6475. \end{enumerate}
  6476. The later responsibility can be handled during construction of the
  6477. interference graph, by adding interference edges between the call-live
  6478. vector-typed variables and all the callee-saved registers. (They
  6479. already interfere with the caller-saved registers.) The type
  6480. information for variables is in the \code{Program} form, so we
  6481. recommend adding another parameter to the \code{build-interference}
  6482. function to communicate this alist.
  6483. The spilling of vector-typed variables to the root stack can be
  6484. handled after graph coloring, when choosing how to assign the colors
  6485. (integers) to registers and stack locations. The \code{Program} output
  6486. of this pass changes to also record the number of spills to the root
  6487. stack.
  6488. % build-interference
  6489. %
  6490. % callq
  6491. % extra parameter for var->type assoc. list
  6492. % update 'program' and 'if'
  6493. % allocate-registers
  6494. % allocate spilled vectors to the rootstack
  6495. % don't change color-graph
  6496. \section{Print x86}
  6497. \label{sec:print-x86-gc}
  6498. \index{subject}{prelude}\index{subject}{conclusion}
  6499. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6500. \code{print-x86} pass on the running example. In the prelude and
  6501. conclusion of the \code{main} function, we treat the root stack very
  6502. much like the regular stack in that we move the root stack pointer
  6503. (\code{r15}) to make room for the spills to the root stack, except
  6504. that the root stack grows up instead of down. For the running
  6505. example, there was just one spill so we increment \code{r15} by 8
  6506. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6507. One issue that deserves special care is that there may be a call to
  6508. \code{collect} prior to the initializing assignments for all the
  6509. variables in the root stack. We do not want the garbage collector to
  6510. accidentally think that some uninitialized variable is a pointer that
  6511. needs to be followed. Thus, we zero-out all locations on the root
  6512. stack in the prelude of \code{main}. In
  6513. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6514. %
  6515. \lstinline{movq $0, (%r15)}
  6516. %
  6517. accomplishes this task. The garbage collector tests each root to see
  6518. if it is null prior to dereferencing it.
  6519. \begin{figure}[htbp]
  6520. \begin{minipage}[t]{0.5\textwidth}
  6521. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6522. block35:
  6523. movq free_ptr(%rip), %rcx
  6524. addq $16, free_ptr(%rip)
  6525. movq %rcx, %r11
  6526. movq $131, 0(%r11)
  6527. movq %rcx, %r11
  6528. movq -8(%r15), %rax
  6529. movq %rax, 8(%r11)
  6530. movq $0, %rdx
  6531. movq %rcx, %r11
  6532. movq 8(%r11), %rcx
  6533. movq %rcx, %r11
  6534. movq 8(%r11), %rax
  6535. jmp conclusion
  6536. block36:
  6537. movq $0, %rcx
  6538. jmp block35
  6539. block38:
  6540. movq free_ptr(%rip), %rcx
  6541. addq $16, free_ptr(%rip)
  6542. movq %rcx, %r11
  6543. movq $3, 0(%r11)
  6544. movq %rcx, %r11
  6545. movq %rbx, 8(%r11)
  6546. movq $0, %rdx
  6547. movq %rcx, -8(%r15)
  6548. movq free_ptr(%rip), %rcx
  6549. addq $16, %rcx
  6550. movq fromspace_end(%rip), %rdx
  6551. cmpq %rdx, %rcx
  6552. jl block36
  6553. movq %r15, %rdi
  6554. movq $16, %rsi
  6555. callq collect
  6556. jmp block35
  6557. block39:
  6558. movq $0, %rcx
  6559. jmp block38
  6560. \end{lstlisting}
  6561. \end{minipage}
  6562. \begin{minipage}[t]{0.45\textwidth}
  6563. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6564. start:
  6565. movq $42, %rbx
  6566. movq free_ptr(%rip), %rdx
  6567. addq $16, %rdx
  6568. movq fromspace_end(%rip), %rcx
  6569. cmpq %rcx, %rdx
  6570. jl block39
  6571. movq %r15, %rdi
  6572. movq $16, %rsi
  6573. callq collect
  6574. jmp block38
  6575. .globl main
  6576. main:
  6577. pushq %rbp
  6578. movq %rsp, %rbp
  6579. pushq %r13
  6580. pushq %r12
  6581. pushq %rbx
  6582. pushq %r14
  6583. subq $0, %rsp
  6584. movq $16384, %rdi
  6585. movq $16384, %rsi
  6586. callq initialize
  6587. movq rootstack_begin(%rip), %r15
  6588. movq $0, (%r15)
  6589. addq $8, %r15
  6590. jmp start
  6591. conclusion:
  6592. subq $8, %r15
  6593. addq $0, %rsp
  6594. popq %r14
  6595. popq %rbx
  6596. popq %r12
  6597. popq %r13
  6598. popq %rbp
  6599. retq
  6600. \end{lstlisting}
  6601. \end{minipage}
  6602. \caption{Output of the \code{print-x86} pass.}
  6603. \label{fig:print-x86-output-gc}
  6604. \end{figure}
  6605. \begin{figure}[p]
  6606. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6607. \node (Rvec) at (0,2) {\large \LangVec{}};
  6608. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6609. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6610. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6611. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6612. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6613. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6614. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6615. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6616. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6617. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6618. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6619. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6620. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6621. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6622. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6623. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6624. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6625. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6626. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6627. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6628. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6629. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6630. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6631. \end{tikzpicture}
  6632. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6633. \label{fig:Rvec-passes}
  6634. \end{figure}
  6635. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6636. for the compilation of \LangVec{}.
  6637. \section{Challenge: Simple Structures}
  6638. \label{sec:simple-structures}
  6639. \index{subject}{struct}
  6640. \index{subject}{structure}
  6641. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6642. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  6643. Recall that a \code{struct} in Typed Racket is a user-defined data
  6644. type that contains named fields and that is heap allocated, similar to
  6645. a vector. The following is an example of a structure definition, in
  6646. this case the definition of a \code{point} type.
  6647. \begin{lstlisting}
  6648. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6649. \end{lstlisting}
  6650. \begin{figure}[tbp]
  6651. \centering
  6652. \fbox{
  6653. \begin{minipage}{0.96\textwidth}
  6654. \[
  6655. \begin{array}{lcl}
  6656. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6657. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6658. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6659. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6660. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6661. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6662. \mid (\key{and}\;\Exp\;\Exp)
  6663. \mid (\key{or}\;\Exp\;\Exp)
  6664. \mid (\key{not}\;\Exp) } \\
  6665. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6666. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6667. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6668. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6669. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6670. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6671. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6672. \LangStruct{} &::=& \Def \ldots \; \Exp
  6673. \end{array}
  6674. \]
  6675. \end{minipage}
  6676. }
  6677. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  6678. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6679. \label{fig:r3s-concrete-syntax}
  6680. \end{figure}
  6681. An instance of a structure is created using function call syntax, with
  6682. the name of the structure in the function position:
  6683. \begin{lstlisting}
  6684. (point 7 12)
  6685. \end{lstlisting}
  6686. Function-call syntax is also used to read the value in a field of a
  6687. structure. The function name is formed by the structure name, a dash,
  6688. and the field name. The following example uses \code{point-x} and
  6689. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6690. instances.
  6691. \begin{center}
  6692. \begin{lstlisting}
  6693. (let ([pt1 (point 7 12)])
  6694. (let ([pt2 (point 4 3)])
  6695. (+ (- (point-x pt1) (point-x pt2))
  6696. (- (point-y pt1) (point-y pt2)))))
  6697. \end{lstlisting}
  6698. \end{center}
  6699. Similarly, to write to a field of a structure, use its set function,
  6700. whose name starts with \code{set-}, followed by the structure name,
  6701. then a dash, then the field name, and concluded with an exclamation
  6702. mark. The following example uses \code{set-point-x!} to change the
  6703. \code{x} field from \code{7} to \code{42}.
  6704. \begin{center}
  6705. \begin{lstlisting}
  6706. (let ([pt (point 7 12)])
  6707. (let ([_ (set-point-x! pt 42)])
  6708. (point-x pt)))
  6709. \end{lstlisting}
  6710. \end{center}
  6711. \begin{exercise}\normalfont
  6712. Extend your compiler with support for simple structures, compiling
  6713. \LangStruct{} to x86 assembly code. Create five new test cases that use
  6714. structures and test your compiler.
  6715. \end{exercise}
  6716. \section{Challenge: Generational Collection}
  6717. The copying collector described in Section~\ref{sec:GC} can incur
  6718. significant runtime overhead because the call to \code{collect} takes
  6719. time proportional to all of the live data. One way to reduce this
  6720. overhead is to reduce how much data is inspected in each call to
  6721. \code{collect}. In particular, researchers have observed that recently
  6722. allocated data is more likely to become garbage then data that has
  6723. survived one or more previous calls to \code{collect}. This insight
  6724. motivated the creation of \emph{generational garbage collectors}
  6725. \index{subject}{generational garbage collector} that
  6726. 1) segregates data according to its age into two or more generations,
  6727. 2) allocates less space for younger generations, so collecting them is
  6728. faster, and more space for the older generations, and 3) performs
  6729. collection on the younger generations more frequently then for older
  6730. generations~\citep{Wilson:1992fk}.
  6731. For this challenge assignment, the goal is to adapt the copying
  6732. collector implemented in \code{runtime.c} to use two generations, one
  6733. for young data and one for old data. Each generation consists of a
  6734. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6735. \code{collect} function to use the two generations.
  6736. \begin{enumerate}
  6737. \item Copy the young generation's FromSpace to its ToSpace then switch
  6738. the role of the ToSpace and FromSpace
  6739. \item If there is enough space for the requested number of bytes in
  6740. the young FromSpace, then return from \code{collect}.
  6741. \item If there is not enough space in the young FromSpace for the
  6742. requested bytes, then move the data from the young generation to the
  6743. old one with the following steps:
  6744. \begin{enumerate}
  6745. \item If there is enough room in the old FromSpace, copy the young
  6746. FromSpace to the old FromSpace and then return.
  6747. \item If there is not enough room in the old FromSpace, then collect
  6748. the old generation by copying the old FromSpace to the old ToSpace
  6749. and swap the roles of the old FromSpace and ToSpace.
  6750. \item If there is enough room now, copy the young FromSpace to the
  6751. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6752. and ToSpace for the old generation. Copy the young FromSpace and
  6753. the old FromSpace into the larger FromSpace for the old
  6754. generation and then return.
  6755. \end{enumerate}
  6756. \end{enumerate}
  6757. We recommend that you generalize the \code{cheney} function so that it
  6758. can be used for all the copies mentioned above: between the young
  6759. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6760. between the young FromSpace and old FromSpace. This can be
  6761. accomplished by adding parameters to \code{cheney} that replace its
  6762. use of the global variables \code{fromspace\_begin},
  6763. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6764. Note that the collection of the young generation does not traverse the
  6765. old generation. This introduces a potential problem: there may be
  6766. young data that is only reachable through pointers in the old
  6767. generation. If these pointers are not taken into account, the
  6768. collector could throw away young data that is live! One solution,
  6769. called \emph{pointer recording}, is to maintain a set of all the
  6770. pointers from the old generation into the new generation and consider
  6771. this set as part of the root set. To maintain this set, the compiler
  6772. must insert extra instructions around every \code{vector-set!}. If the
  6773. vector being modified is in the old generation, and if the value being
  6774. written is a pointer into the new generation, than that pointer must
  6775. be added to the set. Also, if the value being overwritten was a
  6776. pointer into the new generation, then that pointer should be removed
  6777. from the set.
  6778. \begin{exercise}\normalfont
  6779. Adapt the \code{collect} function in \code{runtime.c} to implement
  6780. generational garbage collection, as outlined in this section.
  6781. Update the code generation for \code{vector-set!} to implement
  6782. pointer recording. Make sure that your new compiler and runtime
  6783. passes your test suite.
  6784. \end{exercise}
  6785. % Further Reading
  6786. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6787. \chapter{Functions}
  6788. \label{ch:Rfun}
  6789. \index{subject}{function}
  6790. This chapter studies the compilation of functions similar to those
  6791. found in the C language. This corresponds to a subset of Typed Racket
  6792. in which only top-level function definitions are allowed. This kind of
  6793. function is an important stepping stone to implementing
  6794. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6795. is the topic of Chapter~\ref{ch:Rlam}.
  6796. \section{The \LangFun{} Language}
  6797. The concrete and abstract syntax for function definitions and function
  6798. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6799. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6800. \LangFun{} begin with zero or more function definitions. The function
  6801. names from these definitions are in-scope for the entire program,
  6802. including all other function definitions (so the ordering of function
  6803. definitions does not matter). The concrete syntax for function
  6804. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  6805. where the first expression must
  6806. evaluate to a function and the rest are the arguments.
  6807. The abstract syntax for function application is
  6808. $\APPLY{\Exp}{\Exp\ldots}$.
  6809. %% The syntax for function application does not include an explicit
  6810. %% keyword, which is error prone when using \code{match}. To alleviate
  6811. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6812. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6813. Functions are first-class in the sense that a function pointer
  6814. \index{subject}{function pointer} is data and can be stored in memory or passed
  6815. as a parameter to another function. Thus, we introduce a function
  6816. type, written
  6817. \begin{lstlisting}
  6818. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6819. \end{lstlisting}
  6820. for a function whose $n$ parameters have the types $\Type_1$ through
  6821. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6822. these functions (with respect to Racket functions) is that they are
  6823. not lexically scoped. That is, the only external entities that can be
  6824. referenced from inside a function body are other globally-defined
  6825. functions. The syntax of \LangFun{} prevents functions from being nested
  6826. inside each other.
  6827. \begin{figure}[tp]
  6828. \centering
  6829. \fbox{
  6830. \begin{minipage}{0.96\textwidth}
  6831. \small
  6832. \[
  6833. \begin{array}{lcl}
  6834. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6835. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6836. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6837. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6838. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6839. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6840. \mid (\key{and}\;\Exp\;\Exp)
  6841. \mid (\key{or}\;\Exp\;\Exp)
  6842. \mid (\key{not}\;\Exp)} \\
  6843. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6844. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6845. (\key{vector-ref}\;\Exp\;\Int)} \\
  6846. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6847. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6848. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6849. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6850. \LangFunM{} &::=& \Def \ldots \; \Exp
  6851. \end{array}
  6852. \]
  6853. \end{minipage}
  6854. }
  6855. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6856. \label{fig:Rfun-concrete-syntax}
  6857. \end{figure}
  6858. \begin{figure}[tp]
  6859. \centering
  6860. \fbox{
  6861. \begin{minipage}{0.96\textwidth}
  6862. \small
  6863. \[
  6864. \begin{array}{lcl}
  6865. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6866. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6867. &\mid& \gray{ \BOOL{\itm{bool}}
  6868. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6869. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6870. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6871. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6872. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6873. \end{array}
  6874. \]
  6875. \end{minipage}
  6876. }
  6877. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6878. \label{fig:Rfun-syntax}
  6879. \end{figure}
  6880. The program in Figure~\ref{fig:Rfun-function-example} is a
  6881. representative example of defining and using functions in \LangFun{}. We
  6882. define a function \code{map-vec} that applies some other function
  6883. \code{f} to both elements of a vector and returns a new
  6884. vector containing the results. We also define a function \code{add1}.
  6885. The program applies
  6886. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6887. \code{(vector 1 42)}, from which we return the \code{42}.
  6888. \begin{figure}[tbp]
  6889. \begin{lstlisting}
  6890. (define (map-vec [f : (Integer -> Integer)]
  6891. [v : (Vector Integer Integer)])
  6892. : (Vector Integer Integer)
  6893. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6894. (define (add1 [x : Integer]) : Integer
  6895. (+ x 1))
  6896. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6897. \end{lstlisting}
  6898. \caption{Example of using functions in \LangFun{}.}
  6899. \label{fig:Rfun-function-example}
  6900. \end{figure}
  6901. The definitional interpreter for \LangFun{} is in
  6902. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6903. responsible for setting up the mutual recursion between the top-level
  6904. function definitions. We use the classic back-patching \index{subject}{back-patching}
  6905. approach that uses mutable variables and makes two passes over the function
  6906. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6907. top-level environment using a mutable cons cell for each function
  6908. definition. Note that the \code{lambda} value for each function is
  6909. incomplete; it does not yet include the environment. Once the
  6910. top-level environment is constructed, we then iterate over it and
  6911. update the \code{lambda} values to use the top-level environment.
  6912. \begin{figure}[tp]
  6913. \begin{lstlisting}
  6914. (define interp-Rfun-class
  6915. (class interp-Rvec-class
  6916. (super-new)
  6917. (define/override ((interp-exp env) e)
  6918. (define recur (interp-exp env))
  6919. (match e
  6920. [(Var x) (unbox (dict-ref env x))]
  6921. [(Let x e body)
  6922. (define new-env (dict-set env x (box (recur e))))
  6923. ((interp-exp new-env) body)]
  6924. [(Apply fun args)
  6925. (define fun-val (recur fun))
  6926. (define arg-vals (for/list ([e args]) (recur e)))
  6927. (match fun-val
  6928. [`(function (,xs ...) ,body ,fun-env)
  6929. (define params-args (for/list ([x xs] [arg arg-vals])
  6930. (cons x (box arg))))
  6931. (define new-env (append params-args fun-env))
  6932. ((interp-exp new-env) body)]
  6933. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6934. [else ((super interp-exp env) e)]
  6935. ))
  6936. (define/public (interp-def d)
  6937. (match d
  6938. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6939. (cons f (box `(function ,xs ,body ())))]))
  6940. (define/override (interp-program p)
  6941. (match p
  6942. [(ProgramDefsExp info ds body)
  6943. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6944. (for/list ([f (in-dict-values top-level)])
  6945. (set-box! f (match (unbox f)
  6946. [`(function ,xs ,body ())
  6947. `(function ,xs ,body ,top-level)])))
  6948. ((interp-exp top-level) body))]))
  6949. ))
  6950. (define (interp-Rfun p)
  6951. (send (new interp-Rfun-class) interp-program p))
  6952. \end{lstlisting}
  6953. \caption{Interpreter for the \LangFun{} language.}
  6954. \label{fig:interp-Rfun}
  6955. \end{figure}
  6956. %\margincomment{TODO: explain type checker}
  6957. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  6958. \begin{figure}[tp]
  6959. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6960. (define type-check-Rfun-class
  6961. (class type-check-Rvec-class
  6962. (super-new)
  6963. (inherit check-type-equal?)
  6964. (define/public (type-check-apply env e es)
  6965. (define-values (e^ ty) ((type-check-exp env) e))
  6966. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6967. ((type-check-exp env) e)))
  6968. (match ty
  6969. [`(,ty^* ... -> ,rt)
  6970. (for ([arg-ty ty*] [param-ty ty^*])
  6971. (check-type-equal? arg-ty param-ty (Apply e es)))
  6972. (values e^ e* rt)]))
  6973. (define/override (type-check-exp env)
  6974. (lambda (e)
  6975. (match e
  6976. [(FunRef f)
  6977. (values (FunRef f) (dict-ref env f))]
  6978. [(Apply e es)
  6979. (define-values (e^ es^ rt) (type-check-apply env e es))
  6980. (values (Apply e^ es^) rt)]
  6981. [(Call e es)
  6982. (define-values (e^ es^ rt) (type-check-apply env e es))
  6983. (values (Call e^ es^) rt)]
  6984. [else ((super type-check-exp env) e)])))
  6985. (define/public (type-check-def env)
  6986. (lambda (e)
  6987. (match e
  6988. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6989. (define new-env (append (map cons xs ps) env))
  6990. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6991. (check-type-equal? ty^ rt body)
  6992. (Def f p:t* rt info body^)])))
  6993. (define/public (fun-def-type d)
  6994. (match d
  6995. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6996. (define/override (type-check-program e)
  6997. (match e
  6998. [(ProgramDefsExp info ds body)
  6999. (define new-env (for/list ([d ds])
  7000. (cons (Def-name d) (fun-def-type d))))
  7001. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7002. (define-values (body^ ty) ((type-check-exp new-env) body))
  7003. (check-type-equal? ty 'Integer body)
  7004. (ProgramDefsExp info ds^ body^)]))))
  7005. (define (type-check-Rfun p)
  7006. (send (new type-check-Rfun-class) type-check-program p))
  7007. \end{lstlisting}
  7008. \caption{Type checker for the \LangFun{} language.}
  7009. \label{fig:type-check-Rfun}
  7010. \end{figure}
  7011. \section{Functions in x86}
  7012. \label{sec:fun-x86}
  7013. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  7014. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7015. %% \margincomment{\tiny Talk about the return address on the
  7016. %% stack and what callq and retq does.\\ --Jeremy }
  7017. The x86 architecture provides a few features to support the
  7018. implementation of functions. We have already seen that x86 provides
  7019. labels so that one can refer to the location of an instruction, as is
  7020. needed for jump instructions. Labels can also be used to mark the
  7021. beginning of the instructions for a function. Going further, we can
  7022. obtain the address of a label by using the \key{leaq} instruction and
  7023. PC-relative addressing. For example, the following puts the
  7024. address of the \code{add1} label into the \code{rbx} register.
  7025. \begin{lstlisting}
  7026. leaq add1(%rip), %rbx
  7027. \end{lstlisting}
  7028. The instruction pointer register \key{rip} (aka. the program counter
  7029. \index{subject}{program counter}) always points to the next instruction to be
  7030. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7031. linker computes the distance $d$ between the address of \code{add1}
  7032. and where the \code{rip} would be at that moment and then changes
  7033. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7034. the address of \code{add1}.
  7035. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7036. jump to a function whose location is given by a label. To support
  7037. function calls in this chapter we instead will be jumping to a
  7038. function whose location is given by an address in a register, that is,
  7039. we need to make an \emph{indirect function call}. The x86 syntax for
  7040. this is a \code{callq} instruction but with an asterisk before the
  7041. register name.\index{subject}{indirect function call}
  7042. \begin{lstlisting}
  7043. callq *%rbx
  7044. \end{lstlisting}
  7045. \subsection{Calling Conventions}
  7046. \index{subject}{calling conventions}
  7047. The \code{callq} instruction provides partial support for implementing
  7048. functions: it pushes the return address on the stack and it jumps to
  7049. the target. However, \code{callq} does not handle
  7050. \begin{enumerate}
  7051. \item parameter passing,
  7052. \item pushing frames on the procedure call stack and popping them off,
  7053. or
  7054. \item determining how registers are shared by different functions.
  7055. \end{enumerate}
  7056. Regarding (1) parameter passing, recall that the following six
  7057. registers are used to pass arguments to a function, in this order.
  7058. \begin{lstlisting}
  7059. rdi rsi rdx rcx r8 r9
  7060. \end{lstlisting}
  7061. If there are
  7062. more than six arguments, then the convention is to use space on the
  7063. frame of the caller for the rest of the arguments. However, to ease
  7064. the implementation of efficient tail calls
  7065. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7066. arguments.
  7067. %
  7068. Also recall that the register \code{rax} is for the return value of
  7069. the function.
  7070. \index{subject}{prelude}\index{subject}{conclusion}
  7071. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  7072. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  7073. the stack grows down, with each function call using a chunk of space
  7074. called a frame. The caller sets the stack pointer, register
  7075. \code{rsp}, to the last data item in its frame. The callee must not
  7076. change anything in the caller's frame, that is, anything that is at or
  7077. above the stack pointer. The callee is free to use locations that are
  7078. below the stack pointer.
  7079. Recall that we are storing variables of vector type on the root stack.
  7080. So the prelude needs to move the root stack pointer \code{r15} up and
  7081. the conclusion needs to move the root stack pointer back down. Also,
  7082. the prelude must initialize to \code{0} this frame's slots in the root
  7083. stack to signal to the garbage collector that those slots do not yet
  7084. contain a pointer to a vector. Otherwise the garbage collector will
  7085. interpret the garbage bits in those slots as memory addresses and try
  7086. to traverse them, causing serious mayhem!
  7087. Regarding (3) the sharing of registers between different functions,
  7088. recall from Section~\ref{sec:calling-conventions} that the registers
  7089. are divided into two groups, the caller-saved registers and the
  7090. callee-saved registers. The caller should assume that all the
  7091. caller-saved registers get overwritten with arbitrary values by the
  7092. callee. That is why we recommend in
  7093. Section~\ref{sec:calling-conventions} that variables that are live
  7094. during a function call should not be assigned to caller-saved
  7095. registers.
  7096. On the flip side, if the callee wants to use a callee-saved register,
  7097. the callee must save the contents of those registers on their stack
  7098. frame and then put them back prior to returning to the caller. That
  7099. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7100. the register allocator assigns a variable to a callee-saved register,
  7101. then the prelude of the \code{main} function must save that register
  7102. to the stack and the conclusion of \code{main} must restore it. This
  7103. recommendation now generalizes to all functions.
  7104. Also recall that the base pointer, register \code{rbp}, is used as a
  7105. point-of-reference within a frame, so that each local variable can be
  7106. accessed at a fixed offset from the base pointer
  7107. (Section~\ref{sec:x86}).
  7108. %
  7109. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7110. and callee frames.
  7111. \begin{figure}[tbp]
  7112. \centering
  7113. \begin{tabular}{r|r|l|l} \hline
  7114. Caller View & Callee View & Contents & Frame \\ \hline
  7115. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7116. 0(\key{\%rbp}) & & old \key{rbp} \\
  7117. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7118. \ldots & & \ldots \\
  7119. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7120. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7121. \ldots & & \ldots \\
  7122. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7123. %% & & \\
  7124. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7125. %% & \ldots & \ldots \\
  7126. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7127. \hline
  7128. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7129. & 0(\key{\%rbp}) & old \key{rbp} \\
  7130. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7131. & \ldots & \ldots \\
  7132. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7133. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7134. & \ldots & \ldots \\
  7135. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7136. \end{tabular}
  7137. \caption{Memory layout of caller and callee frames.}
  7138. \label{fig:call-frames}
  7139. \end{figure}
  7140. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7141. %% local variables and for storing the values of callee-saved registers
  7142. %% (we shall refer to all of these collectively as ``locals''), and that
  7143. %% at the beginning of a function we move the stack pointer \code{rsp}
  7144. %% down to make room for them.
  7145. %% We recommend storing the local variables
  7146. %% first and then the callee-saved registers, so that the local variables
  7147. %% can be accessed using \code{rbp} the same as before the addition of
  7148. %% functions.
  7149. %% To make additional room for passing arguments, we shall
  7150. %% move the stack pointer even further down. We count how many stack
  7151. %% arguments are needed for each function call that occurs inside the
  7152. %% body of the function and find their maximum. Adding this number to the
  7153. %% number of locals gives us how much the \code{rsp} should be moved at
  7154. %% the beginning of the function. In preparation for a function call, we
  7155. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7156. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7157. %% so on.
  7158. %% Upon calling the function, the stack arguments are retrieved by the
  7159. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7160. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7161. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7162. %% the layout of the caller and callee frames. Notice how important it is
  7163. %% that we correctly compute the maximum number of arguments needed for
  7164. %% function calls; if that number is too small then the arguments and
  7165. %% local variables will smash into each other!
  7166. \subsection{Efficient Tail Calls}
  7167. \label{sec:tail-call}
  7168. In general, the amount of stack space used by a program is determined
  7169. by the longest chain of nested function calls. That is, if function
  7170. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7171. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7172. $n$ can grow quite large in the case of recursive or mutually
  7173. recursive functions. However, in some cases we can arrange to use only
  7174. constant space, i.e. $O(1)$, instead of $O(n)$.
  7175. If a function call is the last action in a function body, then that
  7176. call is said to be a \emph{tail call}\index{subject}{tail call}.
  7177. For example, in the following
  7178. program, the recursive call to \code{tail-sum} is a tail call.
  7179. \begin{center}
  7180. \begin{lstlisting}
  7181. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7182. (if (eq? n 0)
  7183. r
  7184. (tail-sum (- n 1) (+ n r))))
  7185. (+ (tail-sum 5 0) 27)
  7186. \end{lstlisting}
  7187. \end{center}
  7188. At a tail call, the frame of the caller is no longer needed, so we
  7189. can pop the caller's frame before making the tail call. With this
  7190. approach, a recursive function that only makes tail calls will only
  7191. use $O(1)$ stack space. Functional languages like Racket typically
  7192. rely heavily on recursive functions, so they typically guarantee that
  7193. all tail calls will be optimized in this way.
  7194. \index{subject}{frame}
  7195. However, some care is needed with regards to argument passing in tail
  7196. calls. As mentioned above, for arguments beyond the sixth, the
  7197. convention is to use space in the caller's frame for passing
  7198. arguments. But for a tail call we pop the caller's frame and can no
  7199. longer use it. Another alternative is to use space in the callee's
  7200. frame for passing arguments. However, this option is also problematic
  7201. because the caller and callee's frame overlap in memory. As we begin
  7202. to copy the arguments from their sources in the caller's frame, the
  7203. target locations in the callee's frame might overlap with the sources
  7204. for later arguments! We solve this problem by not using the stack for
  7205. passing more than six arguments but instead using the heap, as we
  7206. describe in the Section~\ref{sec:limit-functions-r4}.
  7207. As mentioned above, for a tail call we pop the caller's frame prior to
  7208. making the tail call. The instructions for popping a frame are the
  7209. instructions that we usually place in the conclusion of a
  7210. function. Thus, we also need to place such code immediately before
  7211. each tail call. These instructions include restoring the callee-saved
  7212. registers, so it is good that the argument passing registers are all
  7213. caller-saved registers.
  7214. One last note regarding which instruction to use to make the tail
  7215. call. When the callee is finished, it should not return to the current
  7216. function, but it should return to the function that called the current
  7217. one. Thus, the return address that is already on the stack is the
  7218. right one, and we should not use \key{callq} to make the tail call, as
  7219. that would unnecessarily overwrite the return address. Instead we can
  7220. simply use the \key{jmp} instruction. Like the indirect function call,
  7221. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  7222. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7223. jump target because the preceding conclusion overwrites just about
  7224. everything else.
  7225. \begin{lstlisting}
  7226. jmp *%rax
  7227. \end{lstlisting}
  7228. \section{Shrink \LangFun{}}
  7229. \label{sec:shrink-r4}
  7230. The \code{shrink} pass performs a minor modification to ease the
  7231. later passes. This pass introduces an explicit \code{main} function
  7232. and changes the top \code{ProgramDefsExp} form to
  7233. \code{ProgramDefs} as follows.
  7234. \begin{lstlisting}
  7235. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7236. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7237. \end{lstlisting}
  7238. where $\itm{mainDef}$ is
  7239. \begin{lstlisting}
  7240. (Def 'main '() 'Integer '() |$\Exp'$|)
  7241. \end{lstlisting}
  7242. \section{Reveal Functions and the \LangFunRef{} language}
  7243. \label{sec:reveal-functions-r4}
  7244. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7245. respect: it conflates the use of function names and local
  7246. variables. This is a problem because we need to compile the use of a
  7247. function name differently than the use of a local variable; we need to
  7248. use \code{leaq} to convert the function name (a label in x86) to an
  7249. address in a register. Thus, it is a good idea to create a new pass
  7250. that changes function references from just a symbol $f$ to
  7251. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7252. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7253. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7254. \begin{figure}[tp]
  7255. \centering
  7256. \fbox{
  7257. \begin{minipage}{0.96\textwidth}
  7258. \[
  7259. \begin{array}{lcl}
  7260. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7261. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7262. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7263. \end{array}
  7264. \]
  7265. \end{minipage}
  7266. }
  7267. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7268. (Figure~\ref{fig:Rfun-syntax}).}
  7269. \label{fig:f1-syntax}
  7270. \end{figure}
  7271. %% Distinguishing between calls in tail position and non-tail position
  7272. %% requires the pass to have some notion of context. We recommend using
  7273. %% two mutually recursive functions, one for processing expressions in
  7274. %% tail position and another for the rest.
  7275. Placing this pass after \code{uniquify} will make sure that there are
  7276. no local variables and functions that share the same name. On the
  7277. other hand, \code{reveal-functions} needs to come before the
  7278. \code{explicate-control} pass because that pass helps us compile
  7279. \code{FunRef} forms into assignment statements.
  7280. \section{Limit Functions}
  7281. \label{sec:limit-functions-r4}
  7282. Recall that we wish to limit the number of function parameters to six
  7283. so that we do not need to use the stack for argument passing, which
  7284. makes it easier to implement efficient tail calls. However, because
  7285. the input language \LangFun{} supports arbitrary numbers of function
  7286. arguments, we have some work to do!
  7287. This pass transforms functions and function calls that involve more
  7288. than six arguments to pass the first five arguments as usual, but it
  7289. packs the rest of the arguments into a vector and passes it as the
  7290. sixth argument.
  7291. Each function definition with too many parameters is transformed as
  7292. follows.
  7293. \begin{lstlisting}
  7294. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7295. |$\Rightarrow$|
  7296. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7297. \end{lstlisting}
  7298. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7299. the occurrences of the later parameters with vector references.
  7300. \begin{lstlisting}
  7301. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7302. \end{lstlisting}
  7303. For function calls with too many arguments, the \code{limit-functions}
  7304. pass transforms them in the following way.
  7305. \begin{tabular}{lll}
  7306. \begin{minipage}{0.2\textwidth}
  7307. \begin{lstlisting}
  7308. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7309. \end{lstlisting}
  7310. \end{minipage}
  7311. &
  7312. $\Rightarrow$
  7313. &
  7314. \begin{minipage}{0.4\textwidth}
  7315. \begin{lstlisting}
  7316. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7317. \end{lstlisting}
  7318. \end{minipage}
  7319. \end{tabular}
  7320. \section{Remove Complex Operands}
  7321. \label{sec:rco-r4}
  7322. The primary decisions to make for this pass is whether to classify
  7323. \code{FunRef} and \code{Apply} as either atomic or complex
  7324. expressions. Recall that a simple expression will eventually end up as
  7325. just an immediate argument of an x86 instruction. Function
  7326. application will be translated to a sequence of instructions, so
  7327. \code{Apply} must be classified as complex expression.
  7328. On the other hand, the arguments of \code{Apply} should be
  7329. atomic expressions.
  7330. %
  7331. Regarding \code{FunRef}, as discussed above, the function label needs
  7332. to be converted to an address using the \code{leaq} instruction. Thus,
  7333. even though \code{FunRef} seems rather simple, it needs to be
  7334. classified as a complex expression so that we generate an assignment
  7335. statement with a left-hand side that can serve as the target of the
  7336. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7337. output language \LangFunANF{} of this pass.
  7338. \begin{figure}[tp]
  7339. \centering
  7340. \fbox{
  7341. \begin{minipage}{0.96\textwidth}
  7342. \small
  7343. \[
  7344. \begin{array}{rcl}
  7345. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7346. \mid \VOID{} } \\
  7347. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7348. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7349. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7350. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7351. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7352. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7353. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7354. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7355. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7356. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7357. \end{array}
  7358. \]
  7359. \end{minipage}
  7360. }
  7361. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7362. \label{fig:Rfun-anf-syntax}
  7363. \end{figure}
  7364. \section{Explicate Control and the \LangCFun{} language}
  7365. \label{sec:explicate-control-r4}
  7366. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7367. output of \key{explicate-control}. (The concrete syntax is given in
  7368. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7369. functions for assignment and tail contexts should be updated with
  7370. cases for \code{Apply} and \code{FunRef} and the function for
  7371. predicate context should be updated for \code{Apply} but not
  7372. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7373. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7374. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7375. defining a new auxiliary function for processing function definitions.
  7376. This code is similar to the case for \code{Program} in \LangVec{}. The
  7377. top-level \code{explicate-control} function that handles the
  7378. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7379. all the function definitions.
  7380. \begin{figure}[tp]
  7381. \fbox{
  7382. \begin{minipage}{0.96\textwidth}
  7383. \small
  7384. \[
  7385. \begin{array}{lcl}
  7386. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7387. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7388. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7389. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7390. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7391. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7392. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7393. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7394. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7395. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7396. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7397. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7398. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7399. \mid \GOTO{\itm{label}} } \\
  7400. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7401. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7402. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7403. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7404. \end{array}
  7405. \]
  7406. \end{minipage}
  7407. }
  7408. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7409. \label{fig:c3-syntax}
  7410. \end{figure}
  7411. \section{Select Instructions and the \LangXIndCall{} Language}
  7412. \label{sec:select-r4}
  7413. \index{subject}{instruction selection}
  7414. The output of select instructions is a program in the \LangXIndCall{}
  7415. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7416. \index{subject}{x86}
  7417. \begin{figure}[tp]
  7418. \fbox{
  7419. \begin{minipage}{0.96\textwidth}
  7420. \small
  7421. \[
  7422. \begin{array}{lcl}
  7423. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7424. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7425. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7426. \Instr &::=& \ldots
  7427. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7428. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7429. \Block &::= & \Instr\ldots \\
  7430. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7431. \LangXIndCallM{} &::= & \Def\ldots
  7432. \end{array}
  7433. \]
  7434. \end{minipage}
  7435. }
  7436. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7437. \label{fig:x86-3-concrete}
  7438. \end{figure}
  7439. \begin{figure}[tp]
  7440. \fbox{
  7441. \begin{minipage}{0.96\textwidth}
  7442. \small
  7443. \[
  7444. \begin{array}{lcl}
  7445. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7446. \mid \BYTEREG{\Reg} } \\
  7447. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7448. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7449. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7450. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7451. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7452. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7453. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7454. \end{array}
  7455. \]
  7456. \end{minipage}
  7457. }
  7458. \caption{The abstract syntax of \LangXIndCall{} (extends
  7459. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7460. \label{fig:x86-3}
  7461. \end{figure}
  7462. An assignment of a function reference to a variable becomes a
  7463. load-effective-address instruction as follows: \\
  7464. \begin{tabular}{lcl}
  7465. \begin{minipage}{0.35\textwidth}
  7466. \begin{lstlisting}
  7467. |$\itm{lhs}$| = (fun-ref |$f$|);
  7468. \end{lstlisting}
  7469. \end{minipage}
  7470. &
  7471. $\Rightarrow$\qquad\qquad
  7472. &
  7473. \begin{minipage}{0.3\textwidth}
  7474. \begin{lstlisting}
  7475. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7476. \end{lstlisting}
  7477. \end{minipage}
  7478. \end{tabular} \\
  7479. Regarding function definitions, we need to remove the parameters and
  7480. instead perform parameter passing using the conventions discussed in
  7481. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7482. registers. We recommend turning the parameters into local variables
  7483. and generating instructions at the beginning of the function to move
  7484. from the argument passing registers to these local variables.
  7485. \begin{lstlisting}
  7486. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7487. |$\Rightarrow$|
  7488. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7489. \end{lstlisting}
  7490. The $G'$ control-flow graph is the same as $G$ except that the
  7491. \code{start} block is modified to add the instructions for moving from
  7492. the argument registers to the parameter variables. So the \code{start}
  7493. block of $G$ shown on the left is changed to the code on the right.
  7494. \begin{center}
  7495. \begin{minipage}{0.3\textwidth}
  7496. \begin{lstlisting}
  7497. start:
  7498. |$\itm{instr}_1$|
  7499. |$\vdots$|
  7500. |$\itm{instr}_n$|
  7501. \end{lstlisting}
  7502. \end{minipage}
  7503. $\Rightarrow$
  7504. \begin{minipage}{0.3\textwidth}
  7505. \begin{lstlisting}
  7506. start:
  7507. movq %rdi, |$x_1$|
  7508. movq %rsi, |$x_2$|
  7509. |$\vdots$|
  7510. |$\itm{instr}_1$|
  7511. |$\vdots$|
  7512. |$\itm{instr}_n$|
  7513. \end{lstlisting}
  7514. \end{minipage}
  7515. \end{center}
  7516. By changing the parameters to local variables, we are giving the
  7517. register allocator control over which registers or stack locations to
  7518. use for them. If you implemented the move-biasing challenge
  7519. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7520. assign the parameter variables to the corresponding argument register,
  7521. in which case the \code{patch-instructions} pass will remove the
  7522. \code{movq} instruction. This happens in the example translation in
  7523. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7524. the \code{add} function.
  7525. %
  7526. Also, note that the register allocator will perform liveness analysis
  7527. on this sequence of move instructions and build the interference
  7528. graph. So, for example, $x_1$ will be marked as interfering with
  7529. \code{rsi} and that will prevent the assignment of $x_1$ to
  7530. \code{rsi}, which is good, because that would overwrite the argument
  7531. that needs to move into $x_2$.
  7532. Next, consider the compilation of function calls. In the mirror image
  7533. of handling the parameters of function definitions, the arguments need
  7534. to be moved to the argument passing registers. The function call
  7535. itself is performed with an indirect function call. The return value
  7536. from the function is stored in \code{rax}, so it needs to be moved
  7537. into the \itm{lhs}.
  7538. \begin{lstlisting}
  7539. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7540. |$\Rightarrow$|
  7541. movq |$\itm{arg}_1$|, %rdi
  7542. movq |$\itm{arg}_2$|, %rsi
  7543. |$\vdots$|
  7544. callq *|\itm{fun}|
  7545. movq %rax, |\itm{lhs}|
  7546. \end{lstlisting}
  7547. The \code{IndirectCallq} AST node includes an integer for the arity of
  7548. the function, i.e., the number of parameters. That information is
  7549. useful in the \code{uncover-live} pass for determining which
  7550. argument-passing registers are potentially read during the call.
  7551. For tail calls, the parameter passing is the same as non-tail calls:
  7552. generate instructions to move the arguments into to the argument
  7553. passing registers. After that we need to pop the frame from the
  7554. procedure call stack. However, we do not yet know how big the frame
  7555. is; that gets determined during register allocation. So instead of
  7556. generating those instructions here, we invent a new instruction that
  7557. means ``pop the frame and then do an indirect jump'', which we name
  7558. \code{TailJmp}. The abstract syntax for this instruction includes an
  7559. argument that specifies where to jump and an integer that represents
  7560. the arity of the function being called.
  7561. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7562. using the label \code{start} for the initial block of a program, and
  7563. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7564. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7565. can be compiled to an assignment to \code{rax} followed by a jump to
  7566. \code{conclusion}. With the addition of function definitions, we will
  7567. have a starting block and conclusion for each function, but their
  7568. labels need to be unique. We recommend prepending the function's name
  7569. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7570. labels. (Alternatively, one could \code{gensym} labels for the start
  7571. and conclusion and store them in the $\itm{info}$ field of the
  7572. function definition.)
  7573. \section{Register Allocation}
  7574. \label{sec:register-allocation-r4}
  7575. \subsection{Liveness Analysis}
  7576. \label{sec:liveness-analysis-r4}
  7577. \index{subject}{liveness analysis}
  7578. %% The rest of the passes need only minor modifications to handle the new
  7579. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7580. %% \code{leaq}.
  7581. The \code{IndirectCallq} instruction should be treated like
  7582. \code{Callq} regarding its written locations $W$, in that they should
  7583. include all the caller-saved registers. Recall that the reason for
  7584. that is to force call-live variables to be assigned to callee-saved
  7585. registers or to be spilled to the stack.
  7586. Regarding the set of read locations $R$ the arity field of
  7587. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7588. argument-passing registers should be considered as read by those
  7589. instructions.
  7590. \subsection{Build Interference Graph}
  7591. \label{sec:build-interference-r4}
  7592. With the addition of function definitions, we compute an interference
  7593. graph for each function (not just one for the whole program).
  7594. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7595. spill vector-typed variables that are live during a call to the
  7596. \code{collect}. With the addition of functions to our language, we
  7597. need to revisit this issue. Many functions perform allocation and
  7598. therefore have calls to the collector inside of them. Thus, we should
  7599. not only spill a vector-typed variable when it is live during a call
  7600. to \code{collect}, but we should spill the variable if it is live
  7601. during any function call. Thus, in the \code{build-interference} pass,
  7602. we recommend adding interference edges between call-live vector-typed
  7603. variables and the callee-saved registers (in addition to the usual
  7604. addition of edges between call-live variables and the caller-saved
  7605. registers).
  7606. \subsection{Allocate Registers}
  7607. The primary change to the \code{allocate-registers} pass is adding an
  7608. auxiliary function for handling definitions (the \Def{} non-terminal
  7609. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7610. logic is the same as described in
  7611. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7612. allocation is performed many times, once for each function definition,
  7613. instead of just once for the whole program.
  7614. \section{Patch Instructions}
  7615. In \code{patch-instructions}, you should deal with the x86
  7616. idiosyncrasy that the destination argument of \code{leaq} must be a
  7617. register. Additionally, you should ensure that the argument of
  7618. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7619. code generation more convenient, because we trample many registers
  7620. before the tail call (as explained in the next section).
  7621. \section{Print x86}
  7622. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7623. \code{IndirectCallq} are straightforward: output their concrete
  7624. syntax.
  7625. \begin{lstlisting}
  7626. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7627. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7628. \end{lstlisting}
  7629. The \code{TailJmp} node requires a bit work. A straightforward
  7630. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7631. before the jump we need to pop the current frame. This sequence of
  7632. instructions is the same as the code for the conclusion of a function,
  7633. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7634. Regarding function definitions, you will need to generate a prelude
  7635. and conclusion for each one. This code is similar to the prelude and
  7636. conclusion that you generated for the \code{main} function in
  7637. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  7638. should carry out the following steps.
  7639. \begin{enumerate}
  7640. \item Start with \code{.global} and \code{.align} directives followed
  7641. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7642. example.)
  7643. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7644. pointer.
  7645. \item Push to the stack all of the callee-saved registers that were
  7646. used for register allocation.
  7647. \item Move the stack pointer \code{rsp} down by the size of the stack
  7648. frame for this function, which depends on the number of regular
  7649. spills. (Aligned to 16 bytes.)
  7650. \item Move the root stack pointer \code{r15} up by the size of the
  7651. root-stack frame for this function, which depends on the number of
  7652. spilled vectors. \label{root-stack-init}
  7653. \item Initialize to zero all of the entries in the root-stack frame.
  7654. \item Jump to the start block.
  7655. \end{enumerate}
  7656. The prelude of the \code{main} function has one additional task: call
  7657. the \code{initialize} function to set up the garbage collector and
  7658. move the value of the global \code{rootstack\_begin} in
  7659. \code{r15}. This should happen before step \ref{root-stack-init}
  7660. above, which depends on \code{r15}.
  7661. The conclusion of every function should do the following.
  7662. \begin{enumerate}
  7663. \item Move the stack pointer back up by the size of the stack frame
  7664. for this function.
  7665. \item Restore the callee-saved registers by popping them from the
  7666. stack.
  7667. \item Move the root stack pointer back down by the size of the
  7668. root-stack frame for this function.
  7669. \item Restore \code{rbp} by popping it from the stack.
  7670. \item Return to the caller with the \code{retq} instruction.
  7671. \end{enumerate}
  7672. \begin{exercise}\normalfont
  7673. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7674. Create 5 new programs that use functions, including examples that pass
  7675. functions and return functions from other functions, recursive
  7676. functions, functions that create vectors, and functions that make tail
  7677. calls. Test your compiler on these new programs and all of your
  7678. previously created test programs.
  7679. \end{exercise}
  7680. \begin{figure}[tbp]
  7681. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7682. \node (Rfun) at (0,2) {\large \LangFun{}};
  7683. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7684. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7685. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7686. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7687. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7688. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7689. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7690. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7691. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7692. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7693. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7694. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7695. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7696. \path[->,bend left=15] (Rfun) edge [above] node
  7697. {\ttfamily\footnotesize shrink} (Rfun-1);
  7698. \path[->,bend left=15] (Rfun-1) edge [above] node
  7699. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7700. \path[->,bend left=15] (Rfun-2) edge [right] node
  7701. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7702. \path[->,bend left=15] (F1-1) edge [below] node
  7703. {\ttfamily\footnotesize limit-functions} (F1-2);
  7704. \path[->,bend right=15] (F1-2) edge [above] node
  7705. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7706. \path[->,bend right=15] (F1-3) edge [above] node
  7707. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7708. \path[->,bend left=15] (F1-4) edge [right] node
  7709. {\ttfamily\footnotesize explicate-control} (C3-2);
  7710. \path[->,bend right=15] (C3-2) edge [left] node
  7711. {\ttfamily\footnotesize select-instr.} (x86-2);
  7712. \path[->,bend left=15] (x86-2) edge [left] node
  7713. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7714. \path[->,bend right=15] (x86-2-1) edge [below] node
  7715. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7716. \path[->,bend right=15] (x86-2-2) edge [left] node
  7717. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7718. \path[->,bend left=15] (x86-3) edge [above] node
  7719. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7720. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7721. \end{tikzpicture}
  7722. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7723. \label{fig:Rfun-passes}
  7724. \end{figure}
  7725. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7726. compiling \LangFun{} to x86.
  7727. \section{An Example Translation}
  7728. \label{sec:functions-example}
  7729. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7730. function in \LangFun{} to x86. The figure also includes the results of the
  7731. \code{explicate-control} and \code{select-instructions} passes.
  7732. \begin{figure}[htbp]
  7733. \begin{tabular}{ll}
  7734. \begin{minipage}{0.5\textwidth}
  7735. % s3_2.rkt
  7736. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7737. (define (add [x : Integer] [y : Integer])
  7738. : Integer
  7739. (+ x y))
  7740. (add 40 2)
  7741. \end{lstlisting}
  7742. $\Downarrow$
  7743. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7744. (define (add86 [x87 : Integer]
  7745. [y88 : Integer]) : Integer
  7746. add86start:
  7747. return (+ x87 y88);
  7748. )
  7749. (define (main) : Integer ()
  7750. mainstart:
  7751. tmp89 = (fun-ref add86);
  7752. (tail-call tmp89 40 2)
  7753. )
  7754. \end{lstlisting}
  7755. \end{minipage}
  7756. &
  7757. $\Rightarrow$
  7758. \begin{minipage}{0.5\textwidth}
  7759. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7760. (define (add86) : Integer
  7761. add86start:
  7762. movq %rdi, x87
  7763. movq %rsi, y88
  7764. movq x87, %rax
  7765. addq y88, %rax
  7766. jmp add11389conclusion
  7767. )
  7768. (define (main) : Integer
  7769. mainstart:
  7770. leaq (fun-ref add86), tmp89
  7771. movq $40, %rdi
  7772. movq $2, %rsi
  7773. tail-jmp tmp89
  7774. )
  7775. \end{lstlisting}
  7776. $\Downarrow$
  7777. \end{minipage}
  7778. \end{tabular}
  7779. \begin{tabular}{ll}
  7780. \begin{minipage}{0.3\textwidth}
  7781. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7782. .globl add86
  7783. .align 16
  7784. add86:
  7785. pushq %rbp
  7786. movq %rsp, %rbp
  7787. jmp add86start
  7788. add86start:
  7789. movq %rdi, %rax
  7790. addq %rsi, %rax
  7791. jmp add86conclusion
  7792. add86conclusion:
  7793. popq %rbp
  7794. retq
  7795. \end{lstlisting}
  7796. \end{minipage}
  7797. &
  7798. \begin{minipage}{0.5\textwidth}
  7799. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7800. .globl main
  7801. .align 16
  7802. main:
  7803. pushq %rbp
  7804. movq %rsp, %rbp
  7805. movq $16384, %rdi
  7806. movq $16384, %rsi
  7807. callq initialize
  7808. movq rootstack_begin(%rip), %r15
  7809. jmp mainstart
  7810. mainstart:
  7811. leaq add86(%rip), %rcx
  7812. movq $40, %rdi
  7813. movq $2, %rsi
  7814. movq %rcx, %rax
  7815. popq %rbp
  7816. jmp *%rax
  7817. mainconclusion:
  7818. popq %rbp
  7819. retq
  7820. \end{lstlisting}
  7821. \end{minipage}
  7822. \end{tabular}
  7823. \caption{Example compilation of a simple function to x86.}
  7824. \label{fig:add-fun}
  7825. \end{figure}
  7826. % Challenge idea: inlining! (simple version)
  7827. % Further Reading
  7828. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7829. \chapter{Lexically Scoped Functions}
  7830. \label{ch:Rlam}
  7831. \index{subject}{lambda}
  7832. \index{subject}{lexical scoping}
  7833. This chapter studies lexically scoped functions as they appear in
  7834. functional languages such as Racket. By lexical scoping we mean that a
  7835. function's body may refer to variables whose binding site is outside
  7836. of the function, in an enclosing scope.
  7837. %
  7838. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7839. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7840. \key{lambda} form. The body of the \key{lambda}, refers to three
  7841. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7842. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7843. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7844. parameter of function \code{f}. The \key{lambda} is returned from the
  7845. function \code{f}. The main expression of the program includes two
  7846. calls to \code{f} with different arguments for \code{x}, first
  7847. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7848. to variables \code{g} and \code{h}. Even though these two functions
  7849. were created by the same \code{lambda}, they are really different
  7850. functions because they use different values for \code{x}. Applying
  7851. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7852. \code{15} produces \code{22}. The result of this program is \code{42}.
  7853. \begin{figure}[btp]
  7854. % s4_6.rkt
  7855. \begin{lstlisting}
  7856. (define (f [x : Integer]) : (Integer -> Integer)
  7857. (let ([y 4])
  7858. (lambda: ([z : Integer]) : Integer
  7859. (+ x (+ y z)))))
  7860. (let ([g (f 5)])
  7861. (let ([h (f 3)])
  7862. (+ (g 11) (h 15))))
  7863. \end{lstlisting}
  7864. \caption{Example of a lexically scoped function.}
  7865. \label{fig:lexical-scoping}
  7866. \end{figure}
  7867. The approach that we take for implementing lexically scoped
  7868. functions is to compile them into top-level function definitions,
  7869. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7870. provide special treatment for variable occurrences such as \code{x}
  7871. and \code{y} in the body of the \code{lambda} of
  7872. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7873. refer to variables defined outside of it. To identify such variable
  7874. occurrences, we review the standard notion of free variable.
  7875. \begin{definition}
  7876. A variable is \emph{free in expression} $e$ if the variable occurs
  7877. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  7878. variable}
  7879. \end{definition}
  7880. For example, in the expression \code{(+ x (+ y z))} the variables
  7881. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7882. only \code{x} and \code{y} are free in the following expression
  7883. because \code{z} is bound by the \code{lambda}.
  7884. \begin{lstlisting}
  7885. (lambda: ([z : Integer]) : Integer
  7886. (+ x (+ y z)))
  7887. \end{lstlisting}
  7888. So the free variables of a \code{lambda} are the ones that will need
  7889. special treatment. We need to arrange for some way to transport, at
  7890. runtime, the values of those variables from the point where the
  7891. \code{lambda} was created to the point where the \code{lambda} is
  7892. applied. An efficient solution to the problem, due to
  7893. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7894. free variables together with the function pointer for the lambda's
  7895. code, an arrangement called a \emph{flat closure} (which we shorten to
  7896. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  7897. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  7898. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  7899. pointers. The function pointer resides at index $0$ and the
  7900. values for the free variables will fill in the rest of the vector.
  7901. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7902. how closures work. It's a three-step dance. The program first calls
  7903. function \code{f}, which creates a closure for the \code{lambda}. The
  7904. closure is a vector whose first element is a pointer to the top-level
  7905. function that we will generate for the \code{lambda}, the second
  7906. element is the value of \code{x}, which is \code{5}, and the third
  7907. element is \code{4}, the value of \code{y}. The closure does not
  7908. contain an element for \code{z} because \code{z} is not a free
  7909. variable of the \code{lambda}. Creating the closure is step 1 of the
  7910. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7911. shown in Figure~\ref{fig:closures}.
  7912. %
  7913. The second call to \code{f} creates another closure, this time with
  7914. \code{3} in the second slot (for \code{x}). This closure is also
  7915. returned from \code{f} but bound to \code{h}, which is also shown in
  7916. Figure~\ref{fig:closures}.
  7917. \begin{figure}[tbp]
  7918. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7919. \caption{Example closure representation for the \key{lambda}'s
  7920. in Figure~\ref{fig:lexical-scoping}.}
  7921. \label{fig:closures}
  7922. \end{figure}
  7923. Continuing with the example, consider the application of \code{g} to
  7924. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7925. obtain the function pointer in the first element of the closure and
  7926. call it, passing in the closure itself and then the regular arguments,
  7927. in this case \code{11}. This technique for applying a closure is step
  7928. 2 of the dance.
  7929. %
  7930. But doesn't this \code{lambda} only take 1 argument, for parameter
  7931. \code{z}? The third and final step of the dance is generating a
  7932. top-level function for a \code{lambda}. We add an additional
  7933. parameter for the closure and we insert a \code{let} at the beginning
  7934. of the function for each free variable, to bind those variables to the
  7935. appropriate elements from the closure parameter.
  7936. %
  7937. This three-step dance is known as \emph{closure conversion}. We
  7938. discuss the details of closure conversion in
  7939. Section~\ref{sec:closure-conversion} and the code generated from the
  7940. example in Section~\ref{sec:example-lambda}. But first we define the
  7941. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7942. \section{The \LangLam{} Language}
  7943. \label{sec:r5}
  7944. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  7945. functions and lexical scoping, is defined in
  7946. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  7947. the \key{lambda} form to the grammar for \LangFun{}, which already has
  7948. syntax for function application.
  7949. \begin{figure}[tp]
  7950. \centering
  7951. \fbox{
  7952. \begin{minipage}{0.96\textwidth}
  7953. \small
  7954. \[
  7955. \begin{array}{lcl}
  7956. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7957. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7958. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7959. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7960. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7961. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7962. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7963. \mid (\key{and}\;\Exp\;\Exp)
  7964. \mid (\key{or}\;\Exp\;\Exp)
  7965. \mid (\key{not}\;\Exp) } \\
  7966. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7967. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7968. (\key{vector-ref}\;\Exp\;\Int)} \\
  7969. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7970. \mid (\Exp \; \Exp\ldots) } \\
  7971. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7972. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7973. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7974. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  7975. \end{array}
  7976. \]
  7977. \end{minipage}
  7978. }
  7979. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  7980. with \key{lambda}.}
  7981. \label{fig:Rlam-concrete-syntax}
  7982. \end{figure}
  7983. \begin{figure}[tp]
  7984. \centering
  7985. \fbox{
  7986. \begin{minipage}{0.96\textwidth}
  7987. \small
  7988. \[
  7989. \begin{array}{lcl}
  7990. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7991. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7992. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7993. &\mid& \gray{ \BOOL{\itm{bool}}
  7994. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7995. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7996. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7997. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7998. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7999. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8000. \end{array}
  8001. \]
  8002. \end{minipage}
  8003. }
  8004. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8005. \label{fig:Rlam-syntax}
  8006. \end{figure}
  8007. \index{subject}{interpreter}
  8008. \label{sec:interp-Rlambda}
  8009. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8010. \LangLam{}. The case for \key{lambda} saves the current environment
  8011. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8012. the environment from the \key{lambda}, the \code{lam-env}, when
  8013. interpreting the body of the \key{lambda}. The \code{lam-env}
  8014. environment is extended with the mapping of parameters to argument
  8015. values.
  8016. \begin{figure}[tbp]
  8017. \begin{lstlisting}
  8018. (define interp-Rlambda-class
  8019. (class interp-Rfun-class
  8020. (super-new)
  8021. (define/override (interp-op op)
  8022. (match op
  8023. ['procedure-arity
  8024. (lambda (v)
  8025. (match v
  8026. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8027. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8028. [else (super interp-op op)]))
  8029. (define/override ((interp-exp env) e)
  8030. (define recur (interp-exp env))
  8031. (match e
  8032. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8033. `(function ,xs ,body ,env)]
  8034. [else ((super interp-exp env) e)]))
  8035. ))
  8036. (define (interp-Rlambda p)
  8037. (send (new interp-Rlambda-class) interp-program p))
  8038. \end{lstlisting}
  8039. \caption{Interpreter for \LangLam{}.}
  8040. \label{fig:interp-Rlambda}
  8041. \end{figure}
  8042. \label{sec:type-check-r5}
  8043. \index{subject}{type checking}
  8044. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8045. \key{lambda} form. The body of the \key{lambda} is checked in an
  8046. environment that includes the current environment (because it is
  8047. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8048. require the body's type to match the declared return type.
  8049. \begin{figure}[tbp]
  8050. \begin{lstlisting}
  8051. (define (type-check-Rlambda env)
  8052. (lambda (e)
  8053. (match e
  8054. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8055. (define-values (new-body bodyT)
  8056. ((type-check-exp (append (map cons xs Ts) env)) body))
  8057. (define ty `(,@Ts -> ,rT))
  8058. (cond
  8059. [(equal? rT bodyT)
  8060. (values (HasType (Lambda params rT new-body) ty) ty)]
  8061. [else
  8062. (error "mismatch in return type" bodyT rT)])]
  8063. ...
  8064. )))
  8065. \end{lstlisting}
  8066. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8067. \label{fig:type-check-Rlambda}
  8068. \end{figure}
  8069. \section{Reveal Functions and the $F_2$ language}
  8070. \label{sec:reveal-functions-r5}
  8071. To support the \code{procedure-arity} operator we need to communicate
  8072. the arity of a function to the point of closure creation. We can
  8073. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8074. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8075. output of this pass is the language $F_2$, whose syntax is defined in
  8076. Figure~\ref{fig:f2-syntax}.
  8077. \begin{figure}[tp]
  8078. \centering
  8079. \fbox{
  8080. \begin{minipage}{0.96\textwidth}
  8081. \[
  8082. \begin{array}{lcl}
  8083. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8084. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8085. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8086. \end{array}
  8087. \]
  8088. \end{minipage}
  8089. }
  8090. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8091. (Figure~\ref{fig:Rlam-syntax}).}
  8092. \label{fig:f2-syntax}
  8093. \end{figure}
  8094. \section{Closure Conversion}
  8095. \label{sec:closure-conversion}
  8096. \index{subject}{closure conversion}
  8097. The compiling of lexically-scoped functions into top-level function
  8098. definitions is accomplished in the pass \code{convert-to-closures}
  8099. that comes after \code{reveal-functions} and before
  8100. \code{limit-functions}.
  8101. As usual, we implement the pass as a recursive function over the
  8102. AST. All of the action is in the cases for \key{Lambda} and
  8103. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8104. that creates a closure, that is, a vector whose first element is a
  8105. function pointer and the rest of the elements are the free variables
  8106. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8107. using \code{vector} so that we can distinguish closures from vectors
  8108. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8109. the generated code below, the \itm{name} is a unique symbol generated
  8110. to identify the function and the \itm{arity} is the number of
  8111. parameters (the length of \itm{ps}).
  8112. \begin{lstlisting}
  8113. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8114. |$\Rightarrow$|
  8115. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8116. \end{lstlisting}
  8117. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8118. create a top-level function definition for each \key{Lambda}, as
  8119. shown below.\\
  8120. \begin{minipage}{0.8\textwidth}
  8121. \begin{lstlisting}
  8122. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8123. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8124. ...
  8125. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8126. |\itm{body'}|)...))
  8127. \end{lstlisting}
  8128. \end{minipage}\\
  8129. The \code{clos} parameter refers to the closure. Translate the type
  8130. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8131. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8132. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8133. underscore \code{\_} is a dummy type that we use because it is rather
  8134. difficult to give a type to the function in the closure's
  8135. type.\footnote{To give an accurate type to a closure, we would need to
  8136. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8137. The dummy type is considered to be equal to any other type during type
  8138. checking. The sequence of \key{Let} forms bind the free variables to
  8139. their values obtained from the closure.
  8140. Closure conversion turns functions into vectors, so the type
  8141. annotations in the program must also be translated. We recommend
  8142. defining a auxiliary recursive function for this purpose. Function
  8143. types should be translated as follows.
  8144. \begin{lstlisting}
  8145. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8146. |$\Rightarrow$|
  8147. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8148. \end{lstlisting}
  8149. The above type says that the first thing in the vector is a function
  8150. pointer. The first parameter of the function pointer is a vector (a
  8151. closure) and the rest of the parameters are the ones from the original
  8152. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8153. the closure omits the types of the free variables because 1) those
  8154. types are not available in this context and 2) we do not need them in
  8155. the code that is generated for function application.
  8156. We transform function application into code that retrieves the
  8157. function pointer from the closure and then calls the function, passing
  8158. in the closure as the first argument. We bind $e'$ to a temporary
  8159. variable to avoid code duplication.
  8160. \begin{lstlisting}
  8161. (Apply |$e$| |\itm{es}|)
  8162. |$\Rightarrow$|
  8163. (Let |\itm{tmp}| |$e'$|
  8164. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8165. \end{lstlisting}
  8166. There is also the question of what to do with references top-level
  8167. function definitions. To maintain a uniform translation of function
  8168. application, we turn function references into closures.
  8169. \begin{tabular}{lll}
  8170. \begin{minipage}{0.3\textwidth}
  8171. \begin{lstlisting}
  8172. (FunRefArity |$f$| |$n$|)
  8173. \end{lstlisting}
  8174. \end{minipage}
  8175. &
  8176. $\Rightarrow$
  8177. &
  8178. \begin{minipage}{0.5\textwidth}
  8179. \begin{lstlisting}
  8180. (Closure |$n$| (FunRef |$f$|) '())
  8181. \end{lstlisting}
  8182. \end{minipage}
  8183. \end{tabular} \\
  8184. %
  8185. The top-level function definitions need to be updated as well to take
  8186. an extra closure parameter.
  8187. \section{An Example Translation}
  8188. \label{sec:example-lambda}
  8189. Figure~\ref{fig:lexical-functions-example} shows the result of
  8190. \code{reveal-functions} and \code{convert-to-closures} for the example
  8191. program demonstrating lexical scoping that we discussed at the
  8192. beginning of this chapter.
  8193. \begin{figure}[tbp]
  8194. \begin{minipage}{0.8\textwidth}
  8195. % tests/lambda_test_6.rkt
  8196. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8197. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8198. (let ([y8 4])
  8199. (lambda: ([z9 : Integer]) : Integer
  8200. (+ x7 (+ y8 z9)))))
  8201. (define (main) : Integer
  8202. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8203. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8204. (+ (g0 11) (h1 15)))))
  8205. \end{lstlisting}
  8206. $\Rightarrow$
  8207. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8208. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8209. (let ([y8 4])
  8210. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8211. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8212. (let ([x7 (vector-ref fvs3 1)])
  8213. (let ([y8 (vector-ref fvs3 2)])
  8214. (+ x7 (+ y8 z9)))))
  8215. (define (main) : Integer
  8216. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8217. ((vector-ref clos5 0) clos5 5))])
  8218. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8219. ((vector-ref clos6 0) clos6 3))])
  8220. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8221. \end{lstlisting}
  8222. \end{minipage}
  8223. \caption{Example of closure conversion.}
  8224. \label{fig:lexical-functions-example}
  8225. \end{figure}
  8226. \begin{exercise}\normalfont
  8227. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8228. Create 5 new programs that use \key{lambda} functions and make use of
  8229. lexical scoping. Test your compiler on these new programs and all of
  8230. your previously created test programs.
  8231. \end{exercise}
  8232. \section{Expose Allocation}
  8233. \label{sec:expose-allocation-r5}
  8234. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8235. that allocates and initializes a vector, similar to the translation of
  8236. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8237. The only difference is replacing the use of
  8238. \ALLOC{\itm{len}}{\itm{type}} with
  8239. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8240. \section{Explicate Control and \LangCLam{}}
  8241. \label{sec:explicate-r5}
  8242. The output language of \code{explicate-control} is \LangCLam{} whose
  8243. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8244. difference with respect to \LangCFun{} is the addition of the
  8245. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8246. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8247. similar to the handling of other expressions such as primitive
  8248. operators.
  8249. \begin{figure}[tp]
  8250. \fbox{
  8251. \begin{minipage}{0.96\textwidth}
  8252. \small
  8253. \[
  8254. \begin{array}{lcl}
  8255. \Exp &::= & \ldots
  8256. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8257. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8258. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8259. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8260. \mid \GOTO{\itm{label}} } \\
  8261. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8262. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8263. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8264. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8265. \end{array}
  8266. \]
  8267. \end{minipage}
  8268. }
  8269. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8270. \label{fig:c4-syntax}
  8271. \end{figure}
  8272. \section{Select Instructions}
  8273. \label{sec:select-instructions-Rlambda}
  8274. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8275. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8276. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8277. that you should place the \itm{arity} in the tag that is stored at
  8278. position $0$ of the vector. Recall that in
  8279. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8280. was not used. We store the arity in the $5$ bits starting at position
  8281. $58$.
  8282. Compile the \code{procedure-arity} operator into a sequence of
  8283. instructions that access the tag from position $0$ of the vector and
  8284. extract the $5$-bits starting at position $58$ from the tag.
  8285. \begin{figure}[p]
  8286. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8287. \node (Rfun) at (0,2) {\large \LangFun{}};
  8288. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8289. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8290. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8291. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8292. \node (F1-3) at (6,0) {\large $F_1$};
  8293. \node (F1-4) at (3,0) {\large $F_1$};
  8294. \node (F1-5) at (0,0) {\large $F_1$};
  8295. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8296. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8297. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8298. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8299. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8300. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8301. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8302. \path[->,bend left=15] (Rfun) edge [above] node
  8303. {\ttfamily\footnotesize shrink} (Rfun-2);
  8304. \path[->,bend left=15] (Rfun-2) edge [above] node
  8305. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8306. \path[->,bend left=15] (Rfun-3) edge [right] node
  8307. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8308. \path[->,bend left=15] (F1-1) edge [below] node
  8309. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8310. \path[->,bend right=15] (F1-2) edge [above] node
  8311. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8312. \path[->,bend right=15] (F1-3) edge [above] node
  8313. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8314. \path[->,bend right=15] (F1-4) edge [above] node
  8315. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8316. \path[->,bend right=15] (F1-5) edge [right] node
  8317. {\ttfamily\footnotesize explicate-control} (C3-2);
  8318. \path[->,bend left=15] (C3-2) edge [left] node
  8319. {\ttfamily\footnotesize select-instr.} (x86-2);
  8320. \path[->,bend right=15] (x86-2) edge [left] node
  8321. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8322. \path[->,bend right=15] (x86-2-1) edge [below] node
  8323. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8324. \path[->,bend right=15] (x86-2-2) edge [left] node
  8325. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8326. \path[->,bend left=15] (x86-3) edge [above] node
  8327. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8328. \path[->,bend left=15] (x86-4) edge [right] node
  8329. {\ttfamily\footnotesize print-x86} (x86-5);
  8330. \end{tikzpicture}
  8331. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8332. functions.}
  8333. \label{fig:Rlambda-passes}
  8334. \end{figure}
  8335. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8336. for the compilation of \LangLam{}.
  8337. \clearpage
  8338. \section{Challenge: Optimize Closures}
  8339. \label{sec:optimize-closures}
  8340. In this chapter we compiled lexically-scoped functions into a
  8341. relatively efficient representation: flat closures. However, even this
  8342. representation comes with some overhead. For example, consider the
  8343. following program with a function \code{tail-sum} that does not have
  8344. any free variables and where all the uses of \code{tail-sum} are in
  8345. applications where we know that only \code{tail-sum} is being applied
  8346. (and not any other functions).
  8347. \begin{center}
  8348. \begin{minipage}{0.95\textwidth}
  8349. \begin{lstlisting}
  8350. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8351. (if (eq? n 0)
  8352. r
  8353. (tail-sum (- n 1) (+ n r))))
  8354. (+ (tail-sum 5 0) 27)
  8355. \end{lstlisting}
  8356. \end{minipage}
  8357. \end{center}
  8358. As described in this chapter, we uniformly apply closure conversion to
  8359. all functions, obtaining the following output for this program.
  8360. \begin{center}
  8361. \begin{minipage}{0.95\textwidth}
  8362. \begin{lstlisting}
  8363. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8364. (if (eq? n2 0)
  8365. r3
  8366. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8367. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8368. (define (main) : Integer
  8369. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8370. ((vector-ref clos6 0) clos6 5 0)) 27))
  8371. \end{lstlisting}
  8372. \end{minipage}
  8373. \end{center}
  8374. In the previous Chapter, there would be no allocation in the program
  8375. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8376. the above program allocates memory for each \code{closure} and the
  8377. calls to \code{tail-sum} are indirect. These two differences incur
  8378. considerable overhead in a program such as this one, where the
  8379. allocations and indirect calls occur inside a tight loop.
  8380. One might think that this problem is trivial to solve: can't we just
  8381. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8382. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8383. e'_n$)} instead of treating it like a call to a closure? We would
  8384. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8385. %
  8386. However, this problem is not so trivial because a global function may
  8387. ``escape'' and become involved in applications that also involve
  8388. closures. Consider the following example in which the application
  8389. \code{(f 41)} needs to be compiled into a closure application, because
  8390. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8391. function might also get bound to \code{f}.
  8392. \begin{lstlisting}
  8393. (define (add1 [x : Integer]) : Integer
  8394. (+ x 1))
  8395. (let ([y (read)])
  8396. (let ([f (if (eq? (read) 0)
  8397. add1
  8398. (lambda: ([x : Integer]) : Integer (- x y)))])
  8399. (f 41)))
  8400. \end{lstlisting}
  8401. If a global function name is used in any way other than as the
  8402. operator in a direct call, then we say that the function
  8403. \emph{escapes}. If a global function does not escape, then we do not
  8404. need to perform closure conversion on the function.
  8405. \begin{exercise}\normalfont
  8406. Implement an auxiliary function for detecting which global
  8407. functions escape. Using that function, implement an improved version
  8408. of closure conversion that does not apply closure conversion to
  8409. global functions that do not escape but instead compiles them as
  8410. regular functions. Create several new test cases that check whether
  8411. you properly detect whether global functions escape or not.
  8412. \end{exercise}
  8413. So far we have reduced the overhead of calling global functions, but
  8414. it would also be nice to reduce the overhead of calling a
  8415. \code{lambda} when we can determine at compile time which
  8416. \code{lambda} will be called. We refer to such calls as \emph{known
  8417. calls}. Consider the following example in which a \code{lambda} is
  8418. bound to \code{f} and then applied.
  8419. \begin{lstlisting}
  8420. (let ([y (read)])
  8421. (let ([f (lambda: ([x : Integer]) : Integer
  8422. (+ x y))])
  8423. (f 21)))
  8424. \end{lstlisting}
  8425. Closure conversion compiles \code{(f 21)} into an indirect call:
  8426. \begin{lstlisting}
  8427. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8428. (let ([y2 (vector-ref fvs6 1)])
  8429. (+ x3 y2)))
  8430. (define (main) : Integer
  8431. (let ([y2 (read)])
  8432. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8433. ((vector-ref f4 0) f4 21))))
  8434. \end{lstlisting}
  8435. but we can instead compile the application \code{(f 21)} into a direct call
  8436. to \code{lambda5}:
  8437. \begin{lstlisting}
  8438. (define (main) : Integer
  8439. (let ([y2 (read)])
  8440. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8441. ((fun-ref lambda5) f4 21))))
  8442. \end{lstlisting}
  8443. The problem of determining which lambda will be called from a
  8444. particular application is quite challenging in general and the topic
  8445. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8446. following exercise we recommend that you compile an application to a
  8447. direct call when the operator is a variable and the variable is
  8448. \code{let}-bound to a closure. This can be accomplished by maintaining
  8449. an environment mapping \code{let}-bound variables to function names.
  8450. Extend the environment whenever you encounter a closure on the
  8451. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8452. to the name of the global function for the closure. This pass should
  8453. come after closure conversion.
  8454. \begin{exercise}\normalfont
  8455. Implement a compiler pass, named \code{optimize-known-calls}, that
  8456. compiles known calls into direct calls. Verify that your compiler is
  8457. successful in this regard on several example programs.
  8458. \end{exercise}
  8459. These exercises only scratches the surface of optimizing of
  8460. closures. A good next step for the interested reader is to look at the
  8461. work of \citet{Keep:2012ab}.
  8462. \section{Further Reading}
  8463. The notion of lexically scoped anonymous functions predates modern
  8464. computers by about a decade. They were invented by
  8465. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  8466. foundation for logic. Anonymous functions were included in the
  8467. LISP~\citep{McCarthy:1960dz} programming language but were initially
  8468. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  8469. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  8470. compile Scheme programs. However, environments were represented as
  8471. linked lists, so variable lookup was linear in the size of the
  8472. environment. In this chapter we represent environments using flat
  8473. closures, which were invented by
  8474. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  8475. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  8476. closures, variable lookup is constant time but the time to create a
  8477. closure is proportional to the number of its free variables. Flat
  8478. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  8479. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  8480. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8481. \chapter{Dynamic Typing}
  8482. \label{ch:Rdyn}
  8483. \index{subject}{dynamic typing}
  8484. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8485. typed language that is a subset of Racket. This is in contrast to the
  8486. previous chapters, which have studied the compilation of Typed
  8487. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8488. expression may produce a value of a different type each time it is
  8489. executed. Consider the following example with a conditional \code{if}
  8490. expression that may return a Boolean or an integer depending on the
  8491. input to the program.
  8492. % part of dynamic_test_25.rkt
  8493. \begin{lstlisting}
  8494. (not (if (eq? (read) 1) #f 0))
  8495. \end{lstlisting}
  8496. Languages that allow expressions to produce different kinds of values
  8497. are called \emph{polymorphic}, a word composed of the Greek roots
  8498. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8499. are several kinds of polymorphism in programming languages, such as
  8500. subtype polymorphism and parametric
  8501. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8502. study in this chapter does not have a special name but it is the kind
  8503. that arises in dynamically typed languages.
  8504. Another characteristic of dynamically typed languages is that
  8505. primitive operations, such as \code{not}, are often defined to operate
  8506. on many different types of values. In fact, in Racket, the \code{not}
  8507. operator produces a result for any kind of value: given \code{\#f} it
  8508. returns \code{\#t} and given anything else it returns \code{\#f}.
  8509. Furthermore, even when primitive operations restrict their inputs to
  8510. values of a certain type, this restriction is enforced at runtime
  8511. instead of during compilation. For example, the following vector
  8512. reference results in a run-time contract violation because the index
  8513. must be in integer, not a Boolean such as \code{\#t}.
  8514. \begin{lstlisting}
  8515. (vector-ref (vector 42) #t)
  8516. \end{lstlisting}
  8517. \begin{figure}[tp]
  8518. \centering
  8519. \fbox{
  8520. \begin{minipage}{0.97\textwidth}
  8521. \[
  8522. \begin{array}{rcl}
  8523. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8524. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8525. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8526. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8527. &\mid& \key{\#t} \mid \key{\#f}
  8528. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8529. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8530. \mid \CUNIOP{\key{not}}{\Exp} \\
  8531. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8532. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8533. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8534. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8535. &\mid& \LP\Exp \; \Exp\ldots\RP
  8536. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8537. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8538. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8539. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8540. \LangDynM{} &::=& \Def\ldots\; \Exp
  8541. \end{array}
  8542. \]
  8543. \end{minipage}
  8544. }
  8545. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8546. \label{fig:r7-concrete-syntax}
  8547. \end{figure}
  8548. \begin{figure}[tp]
  8549. \centering
  8550. \fbox{
  8551. \begin{minipage}{0.96\textwidth}
  8552. \small
  8553. \[
  8554. \begin{array}{lcl}
  8555. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8556. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8557. &\mid& \BOOL{\itm{bool}}
  8558. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8559. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8560. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8561. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8562. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8563. \end{array}
  8564. \]
  8565. \end{minipage}
  8566. }
  8567. \caption{The abstract syntax of \LangDyn{}.}
  8568. \label{fig:r7-syntax}
  8569. \end{figure}
  8570. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8571. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8572. \ref{fig:r7-syntax}.
  8573. %
  8574. There is no type checker for \LangDyn{} because it is not a statically
  8575. typed language (it's dynamically typed!).
  8576. The definitional interpreter for \LangDyn{} is presented in
  8577. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  8578. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8579. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8580. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8581. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  8582. value} that combines an underlying value with a tag that identifies
  8583. what kind of value it is. We define the following struct
  8584. to represented tagged values.
  8585. \begin{lstlisting}
  8586. (struct Tagged (value tag) #:transparent)
  8587. \end{lstlisting}
  8588. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8589. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8590. but don't always capture all the information that a type does. For
  8591. example, a vector of type \code{(Vector Any Any)} is tagged with
  8592. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8593. is tagged with \code{Procedure}.
  8594. Next consider the match case for \code{vector-ref}. The
  8595. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8596. is used to ensure that the first argument is a vector and the second
  8597. is an integer. If they are not, a \code{trapped-error} is raised.
  8598. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8599. interpreter raises a \code{trapped-error} error, the compiled code
  8600. must also signal an error by exiting with return code \code{255}. A
  8601. \code{trapped-error} is also raised if the index is not less than
  8602. length of the vector.
  8603. \begin{figure}[tbp]
  8604. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8605. (define ((interp-Rdyn-exp env) ast)
  8606. (define recur (interp-Rdyn-exp env))
  8607. (match ast
  8608. [(Var x) (lookup x env)]
  8609. [(Int n) (Tagged n 'Integer)]
  8610. [(Bool b) (Tagged b 'Boolean)]
  8611. [(Lambda xs rt body)
  8612. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8613. [(Prim 'vector es)
  8614. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8615. [(Prim 'vector-ref (list e1 e2))
  8616. (define vec (recur e1)) (define i (recur e2))
  8617. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8618. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8619. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8620. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8621. [(Prim 'vector-set! (list e1 e2 e3))
  8622. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8623. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8624. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8625. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8626. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8627. (Tagged (void) 'Void)]
  8628. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8629. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8630. [(Prim 'or (list e1 e2))
  8631. (define v1 (recur e1))
  8632. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8633. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8634. [(Prim op (list e1))
  8635. #:when (set-member? type-predicates op)
  8636. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8637. [(Prim op es)
  8638. (define args (map recur es))
  8639. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8640. (unless (for/or ([expected-tags (op-tags op)])
  8641. (equal? expected-tags tags))
  8642. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8643. (tag-value
  8644. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8645. [(If q t f)
  8646. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8647. [(Apply f es)
  8648. (define new-f (recur f)) (define args (map recur es))
  8649. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8650. (match f-val
  8651. [`(function ,xs ,body ,lam-env)
  8652. (unless (eq? (length xs) (length args))
  8653. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8654. (define new-env (append (map cons xs args) lam-env))
  8655. ((interp-Rdyn-exp new-env) body)]
  8656. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8657. \end{lstlisting}
  8658. \caption{Interpreter for the \LangDyn{} language.}
  8659. \label{fig:interp-Rdyn}
  8660. \end{figure}
  8661. \begin{figure}[tbp]
  8662. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8663. (define (interp-op op)
  8664. (match op
  8665. ['+ fx+]
  8666. ['- fx-]
  8667. ['read read-fixnum]
  8668. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8669. ['< (lambda (v1 v2)
  8670. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8671. ['<= (lambda (v1 v2)
  8672. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8673. ['> (lambda (v1 v2)
  8674. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8675. ['>= (lambda (v1 v2)
  8676. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8677. ['boolean? boolean?]
  8678. ['integer? fixnum?]
  8679. ['void? void?]
  8680. ['vector? vector?]
  8681. ['vector-length vector-length]
  8682. ['procedure? (match-lambda
  8683. [`(functions ,xs ,body ,env) #t] [else #f])]
  8684. [else (error 'interp-op "unknown operator" op)]))
  8685. (define (op-tags op)
  8686. (match op
  8687. ['+ '((Integer Integer))]
  8688. ['- '((Integer Integer) (Integer))]
  8689. ['read '(())]
  8690. ['not '((Boolean))]
  8691. ['< '((Integer Integer))]
  8692. ['<= '((Integer Integer))]
  8693. ['> '((Integer Integer))]
  8694. ['>= '((Integer Integer))]
  8695. ['vector-length '((Vector))]))
  8696. (define type-predicates
  8697. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8698. (define (tag-value v)
  8699. (cond [(boolean? v) (Tagged v 'Boolean)]
  8700. [(fixnum? v) (Tagged v 'Integer)]
  8701. [(procedure? v) (Tagged v 'Procedure)]
  8702. [(vector? v) (Tagged v 'Vector)]
  8703. [(void? v) (Tagged v 'Void)]
  8704. [else (error 'tag-value "unidentified value ~a" v)]))
  8705. (define (check-tag val expected ast)
  8706. (define tag (Tagged-tag val))
  8707. (unless (eq? tag expected)
  8708. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8709. \end{lstlisting}
  8710. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8711. \label{fig:interp-Rdyn-aux}
  8712. \end{figure}
  8713. \clearpage
  8714. \section{Representation of Tagged Values}
  8715. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8716. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8717. values at the bit level. Because almost every operation in \LangDyn{}
  8718. involves manipulating tagged values, the representation must be
  8719. efficient. Recall that all of our values are 64 bits. We shall steal
  8720. the 3 right-most bits to encode the tag. We use $001$ to identify
  8721. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8722. and $101$ for the void value. We define the following auxiliary
  8723. function for mapping types to tag codes.
  8724. \begin{align*}
  8725. \itm{tagof}(\key{Integer}) &= 001 \\
  8726. \itm{tagof}(\key{Boolean}) &= 100 \\
  8727. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8728. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8729. \itm{tagof}(\key{Void}) &= 101
  8730. \end{align*}
  8731. This stealing of 3 bits comes at some price: our integers are reduced
  8732. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8733. affect vectors and procedures because those values are addresses, and
  8734. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8735. they are always $000$. Thus, we do not lose information by overwriting
  8736. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8737. to recover the original address.
  8738. To make tagged values into first-class entities, we can give them a
  8739. type, called \code{Any}, and define operations such as \code{Inject}
  8740. and \code{Project} for creating and using them, yielding the \LangAny{}
  8741. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8742. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8743. in greater detail.
  8744. \section{The \LangAny{} Language}
  8745. \label{sec:Rany-lang}
  8746. \begin{figure}[tp]
  8747. \centering
  8748. \fbox{
  8749. \begin{minipage}{0.96\textwidth}
  8750. \small
  8751. \[
  8752. \begin{array}{lcl}
  8753. \Type &::= & \ldots \mid \key{Any} \\
  8754. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8755. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8756. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8757. \mid \code{procedure?} \mid \code{void?} \\
  8758. \Exp &::=& \ldots
  8759. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8760. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8761. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8762. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8763. \end{array}
  8764. \]
  8765. \end{minipage}
  8766. }
  8767. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8768. \label{fig:Rany-syntax}
  8769. \end{figure}
  8770. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  8771. (The concrete syntax of \LangAny{} is in the Appendix,
  8772. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8773. converts the value produced by expression $e$ of type $T$ into a
  8774. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8775. produced by expression $e$ into a value of type $T$ or else halts the
  8776. program if the type tag is not equivalent to $T$.
  8777. %
  8778. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8779. restricted to a flat type $\FType$, which simplifies the
  8780. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8781. The \code{any-vector} operators adapt the vector operations so that
  8782. they can be applied to a value of type \code{Any}. They also
  8783. generalize the vector operations in that the index is not restricted
  8784. to be a literal integer in the grammar but is allowed to be any
  8785. expression.
  8786. The type predicates such as \key{boolean?} expect their argument to
  8787. produce a tagged value; they return \key{\#t} if the tag corresponds
  8788. to the predicate and they return \key{\#f} otherwise.
  8789. The type checker for \LangAny{} is shown in
  8790. Figures~\ref{fig:type-check-Rany-part-1} and
  8791. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8792. Figure~\ref{fig:type-check-Rany-aux}.
  8793. %
  8794. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8795. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8796. in Figure~\ref{fig:apply-project}.
  8797. \begin{figure}[btp]
  8798. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8799. (define type-check-Rany-class
  8800. (class type-check-Rlambda-class
  8801. (super-new)
  8802. (inherit check-type-equal?)
  8803. (define/override (type-check-exp env)
  8804. (lambda (e)
  8805. (define recur (type-check-exp env))
  8806. (match e
  8807. [(Inject e1 ty)
  8808. (unless (flat-ty? ty)
  8809. (error 'type-check "may only inject from flat type, not ~a" ty))
  8810. (define-values (new-e1 e-ty) (recur e1))
  8811. (check-type-equal? e-ty ty e)
  8812. (values (Inject new-e1 ty) 'Any)]
  8813. [(Project e1 ty)
  8814. (unless (flat-ty? ty)
  8815. (error 'type-check "may only project to flat type, not ~a" ty))
  8816. (define-values (new-e1 e-ty) (recur e1))
  8817. (check-type-equal? e-ty 'Any e)
  8818. (values (Project new-e1 ty) ty)]
  8819. [(Prim 'any-vector-length (list e1))
  8820. (define-values (e1^ t1) (recur e1))
  8821. (check-type-equal? t1 'Any e)
  8822. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8823. [(Prim 'any-vector-ref (list e1 e2))
  8824. (define-values (e1^ t1) (recur e1))
  8825. (define-values (e2^ t2) (recur e2))
  8826. (check-type-equal? t1 'Any e)
  8827. (check-type-equal? t2 'Integer e)
  8828. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8829. [(Prim 'any-vector-set! (list e1 e2 e3))
  8830. (define-values (e1^ t1) (recur e1))
  8831. (define-values (e2^ t2) (recur e2))
  8832. (define-values (e3^ t3) (recur e3))
  8833. (check-type-equal? t1 'Any e)
  8834. (check-type-equal? t2 'Integer e)
  8835. (check-type-equal? t3 'Any e)
  8836. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8837. \end{lstlisting}
  8838. \caption{Type checker for the \LangAny{} language, part 1.}
  8839. \label{fig:type-check-Rany-part-1}
  8840. \end{figure}
  8841. \begin{figure}[btp]
  8842. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8843. [(ValueOf e ty)
  8844. (define-values (new-e e-ty) (recur e))
  8845. (values (ValueOf new-e ty) ty)]
  8846. [(Prim pred (list e1))
  8847. #:when (set-member? (type-predicates) pred)
  8848. (define-values (new-e1 e-ty) (recur e1))
  8849. (check-type-equal? e-ty 'Any e)
  8850. (values (Prim pred (list new-e1)) 'Boolean)]
  8851. [(If cnd thn els)
  8852. (define-values (cnd^ Tc) (recur cnd))
  8853. (define-values (thn^ Tt) (recur thn))
  8854. (define-values (els^ Te) (recur els))
  8855. (check-type-equal? Tc 'Boolean cnd)
  8856. (check-type-equal? Tt Te e)
  8857. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8858. [(Exit) (values (Exit) '_)]
  8859. [(Prim 'eq? (list arg1 arg2))
  8860. (define-values (e1 t1) (recur arg1))
  8861. (define-values (e2 t2) (recur arg2))
  8862. (match* (t1 t2)
  8863. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8864. [(other wise) (check-type-equal? t1 t2 e)])
  8865. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8866. [else ((super type-check-exp env) e)])))
  8867. ))
  8868. \end{lstlisting}
  8869. \caption{Type checker for the \LangAny{} language, part 2.}
  8870. \label{fig:type-check-Rany-part-2}
  8871. \end{figure}
  8872. \begin{figure}[tbp]
  8873. \begin{lstlisting}
  8874. (define/override (operator-types)
  8875. (append
  8876. '((integer? . ((Any) . Boolean))
  8877. (vector? . ((Any) . Boolean))
  8878. (procedure? . ((Any) . Boolean))
  8879. (void? . ((Any) . Boolean))
  8880. (tag-of-any . ((Any) . Integer))
  8881. (make-any . ((_ Integer) . Any))
  8882. )
  8883. (super operator-types)))
  8884. (define/public (type-predicates)
  8885. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8886. (define/public (combine-types t1 t2)
  8887. (match (list t1 t2)
  8888. [(list '_ t2) t2]
  8889. [(list t1 '_) t1]
  8890. [(list `(Vector ,ts1 ...)
  8891. `(Vector ,ts2 ...))
  8892. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8893. (combine-types t1 t2)))]
  8894. [(list `(,ts1 ... -> ,rt1)
  8895. `(,ts2 ... -> ,rt2))
  8896. `(,@(for/list ([t1 ts1] [t2 ts2])
  8897. (combine-types t1 t2))
  8898. -> ,(combine-types rt1 rt2))]
  8899. [else t1]))
  8900. (define/public (flat-ty? ty)
  8901. (match ty
  8902. [(or `Integer `Boolean '_ `Void) #t]
  8903. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8904. [`(,ts ... -> ,rt)
  8905. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8906. [else #f]))
  8907. \end{lstlisting}
  8908. \caption{Auxiliary methods for type checking \LangAny{}.}
  8909. \label{fig:type-check-Rany-aux}
  8910. \end{figure}
  8911. \begin{figure}[btp]
  8912. \begin{lstlisting}
  8913. (define interp-Rany-class
  8914. (class interp-Rlambda-class
  8915. (super-new)
  8916. (define/override (interp-op op)
  8917. (match op
  8918. ['boolean? (match-lambda
  8919. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8920. [else #f])]
  8921. ['integer? (match-lambda
  8922. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8923. [else #f])]
  8924. ['vector? (match-lambda
  8925. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8926. [else #f])]
  8927. ['procedure? (match-lambda
  8928. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8929. [else #f])]
  8930. ['eq? (match-lambda*
  8931. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8932. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8933. [ls (apply (super interp-op op) ls)])]
  8934. ['any-vector-ref (lambda (v i)
  8935. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8936. ['any-vector-set! (lambda (v i a)
  8937. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8938. ['any-vector-length (lambda (v)
  8939. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8940. [else (super interp-op op)]))
  8941. (define/override ((interp-exp env) e)
  8942. (define recur (interp-exp env))
  8943. (match e
  8944. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8945. [(Project e ty2) (apply-project (recur e) ty2)]
  8946. [else ((super interp-exp env) e)]))
  8947. ))
  8948. (define (interp-Rany p)
  8949. (send (new interp-Rany-class) interp-program p))
  8950. \end{lstlisting}
  8951. \caption{Interpreter for \LangAny{}.}
  8952. \label{fig:interp-Rany}
  8953. \end{figure}
  8954. \begin{figure}[tbp]
  8955. \begin{lstlisting}
  8956. (define/public (apply-inject v tg) (Tagged v tg))
  8957. (define/public (apply-project v ty2)
  8958. (define tag2 (any-tag ty2))
  8959. (match v
  8960. [(Tagged v1 tag1)
  8961. (cond
  8962. [(eq? tag1 tag2)
  8963. (match ty2
  8964. [`(Vector ,ts ...)
  8965. (define l1 ((interp-op 'vector-length) v1))
  8966. (cond
  8967. [(eq? l1 (length ts)) v1]
  8968. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  8969. l1 (length ts))])]
  8970. [`(,ts ... -> ,rt)
  8971. (match v1
  8972. [`(function ,xs ,body ,env)
  8973. (cond [(eq? (length xs) (length ts)) v1]
  8974. [else
  8975. (error 'apply-project "arity mismatch ~a != ~a"
  8976. (length xs) (length ts))])]
  8977. [else (error 'apply-project "expected function not ~a" v1)])]
  8978. [else v1])]
  8979. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  8980. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  8981. \end{lstlisting}
  8982. \caption{Auxiliary functions for injection and projection.}
  8983. \label{fig:apply-project}
  8984. \end{figure}
  8985. \clearpage
  8986. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  8987. \label{sec:compile-r7}
  8988. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  8989. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  8990. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  8991. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  8992. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  8993. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  8994. the Boolean \code{\#t}, which must be injected to produce an
  8995. expression of type \key{Any}.
  8996. %
  8997. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  8998. addition, is representative of compilation for many primitive
  8999. operations: the arguments have type \key{Any} and must be projected to
  9000. \key{Integer} before the addition can be performed.
  9001. The compilation of \key{lambda} (third row of
  9002. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9003. produce type annotations: we simply use \key{Any}.
  9004. %
  9005. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9006. has to account for some differences in behavior between \LangDyn{} and
  9007. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9008. kind of values can be used in various places. For example, the
  9009. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9010. the arguments need not be of the same type (in that case the
  9011. result is \code{\#f}).
  9012. \begin{figure}[btp]
  9013. \centering
  9014. \begin{tabular}{|lll|} \hline
  9015. \begin{minipage}{0.27\textwidth}
  9016. \begin{lstlisting}
  9017. #t
  9018. \end{lstlisting}
  9019. \end{minipage}
  9020. &
  9021. $\Rightarrow$
  9022. &
  9023. \begin{minipage}{0.65\textwidth}
  9024. \begin{lstlisting}
  9025. (inject #t Boolean)
  9026. \end{lstlisting}
  9027. \end{minipage}
  9028. \\[2ex]\hline
  9029. \begin{minipage}{0.27\textwidth}
  9030. \begin{lstlisting}
  9031. (+ |$e_1$| |$e_2$|)
  9032. \end{lstlisting}
  9033. \end{minipage}
  9034. &
  9035. $\Rightarrow$
  9036. &
  9037. \begin{minipage}{0.65\textwidth}
  9038. \begin{lstlisting}
  9039. (inject
  9040. (+ (project |$e'_1$| Integer)
  9041. (project |$e'_2$| Integer))
  9042. Integer)
  9043. \end{lstlisting}
  9044. \end{minipage}
  9045. \\[2ex]\hline
  9046. \begin{minipage}{0.27\textwidth}
  9047. \begin{lstlisting}
  9048. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9049. \end{lstlisting}
  9050. \end{minipage}
  9051. &
  9052. $\Rightarrow$
  9053. &
  9054. \begin{minipage}{0.65\textwidth}
  9055. \begin{lstlisting}
  9056. (inject
  9057. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9058. (Any|$\ldots$|Any -> Any))
  9059. \end{lstlisting}
  9060. \end{minipage}
  9061. \\[2ex]\hline
  9062. \begin{minipage}{0.27\textwidth}
  9063. \begin{lstlisting}
  9064. (|$e_0$| |$e_1 \ldots e_n$|)
  9065. \end{lstlisting}
  9066. \end{minipage}
  9067. &
  9068. $\Rightarrow$
  9069. &
  9070. \begin{minipage}{0.65\textwidth}
  9071. \begin{lstlisting}
  9072. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9073. \end{lstlisting}
  9074. \end{minipage}
  9075. \\[2ex]\hline
  9076. \begin{minipage}{0.27\textwidth}
  9077. \begin{lstlisting}
  9078. (vector-ref |$e_1$| |$e_2$|)
  9079. \end{lstlisting}
  9080. \end{minipage}
  9081. &
  9082. $\Rightarrow$
  9083. &
  9084. \begin{minipage}{0.65\textwidth}
  9085. \begin{lstlisting}
  9086. (any-vector-ref |$e_1'$| |$e_2'$|)
  9087. \end{lstlisting}
  9088. \end{minipage}
  9089. \\[2ex]\hline
  9090. \begin{minipage}{0.27\textwidth}
  9091. \begin{lstlisting}
  9092. (if |$e_1$| |$e_2$| |$e_3$|)
  9093. \end{lstlisting}
  9094. \end{minipage}
  9095. &
  9096. $\Rightarrow$
  9097. &
  9098. \begin{minipage}{0.65\textwidth}
  9099. \begin{lstlisting}
  9100. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9101. \end{lstlisting}
  9102. \end{minipage}
  9103. \\[2ex]\hline
  9104. \begin{minipage}{0.27\textwidth}
  9105. \begin{lstlisting}
  9106. (eq? |$e_1$| |$e_2$|)
  9107. \end{lstlisting}
  9108. \end{minipage}
  9109. &
  9110. $\Rightarrow$
  9111. &
  9112. \begin{minipage}{0.65\textwidth}
  9113. \begin{lstlisting}
  9114. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9115. \end{lstlisting}
  9116. \end{minipage}
  9117. \\[2ex]\hline
  9118. \begin{minipage}{0.27\textwidth}
  9119. \begin{lstlisting}
  9120. (not |$e_1$|)
  9121. \end{lstlisting}
  9122. \end{minipage}
  9123. &
  9124. $\Rightarrow$
  9125. &
  9126. \begin{minipage}{0.65\textwidth}
  9127. \begin{lstlisting}
  9128. (if (eq? |$e'_1$| (inject #f Boolean))
  9129. (inject #t Boolean) (inject #f Boolean))
  9130. \end{lstlisting}
  9131. \end{minipage}
  9132. \\[2ex]\hline
  9133. \end{tabular}
  9134. \caption{Cast Insertion}
  9135. \label{fig:compile-r7-Rany}
  9136. \end{figure}
  9137. \section{Reveal Casts}
  9138. \label{sec:reveal-casts-Rany}
  9139. % TODO: define R'_6
  9140. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9141. into an \code{if} expression that checks whether the value's tag
  9142. matches the target type; if it does, the value is converted to a value
  9143. of the target type by removing the tag; if it does not, the program
  9144. exits. To perform these actions we need a new primitive operation,
  9145. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9146. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9147. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9148. underlying value from a tagged value. The \code{ValueOf} form
  9149. includes the type for the underlying value which is used by the type
  9150. checker. Finally, the \code{Exit} form ends the execution of the
  9151. program.
  9152. If the target type of the projection is \code{Boolean} or
  9153. \code{Integer}, then \code{Project} can be translated as follows.
  9154. \begin{center}
  9155. \begin{minipage}{1.0\textwidth}
  9156. \begin{lstlisting}
  9157. (Project |$e$| |$\FType$|)
  9158. |$\Rightarrow$|
  9159. (Let |$\itm{tmp}$| |$e'$|
  9160. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9161. (Int |$\itm{tagof}(\FType)$|)))
  9162. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9163. (Exit)))
  9164. \end{lstlisting}
  9165. \end{minipage}
  9166. \end{center}
  9167. If the target type of the projection is a vector or function type,
  9168. then there is a bit more work to do. For vectors, check that the
  9169. length of the vector type matches the length of the vector (using the
  9170. \code{vector-length} primitive). For functions, check that the number
  9171. of parameters in the function type matches the function's arity (using
  9172. \code{procedure-arity}).
  9173. Regarding \code{inject}, we recommend compiling it to a slightly
  9174. lower-level primitive operation named \code{make-any}. This operation
  9175. takes a tag instead of a type.
  9176. \begin{center}
  9177. \begin{minipage}{1.0\textwidth}
  9178. \begin{lstlisting}
  9179. (Inject |$e$| |$\FType$|)
  9180. |$\Rightarrow$|
  9181. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9182. \end{lstlisting}
  9183. \end{minipage}
  9184. \end{center}
  9185. The type predicates (\code{boolean?}, etc.) can be translated into
  9186. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9187. translation of \code{Project}.
  9188. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9189. combine the projection action with the vector operation. Also, the
  9190. read and write operations allow arbitrary expressions for the index so
  9191. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9192. cannot guarantee that the index is within bounds. Thus, we insert code
  9193. to perform bounds checking at runtime. The translation for
  9194. \code{any-vector-ref} is as follows and the other two operations are
  9195. translated in a similar way.
  9196. \begin{lstlisting}
  9197. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9198. |$\Rightarrow$|
  9199. (Let |$v$| |$e'_1$|
  9200. (Let |$i$| |$e'_2$|
  9201. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9202. (If (Prim '< (list (Var |$i$|)
  9203. (Prim 'any-vector-length (list (Var |$v$|)))))
  9204. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9205. (Exit))))
  9206. \end{lstlisting}
  9207. \section{Remove Complex Operands}
  9208. \label{sec:rco-Rany}
  9209. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9210. The subexpression of \code{ValueOf} must be atomic.
  9211. \section{Explicate Control and \LangCAny{}}
  9212. \label{sec:explicate-Rany}
  9213. The output of \code{explicate-control} is the \LangCAny{} language whose
  9214. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9215. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9216. expression becomes a $\Tail$. Also, note that the index argument of
  9217. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9218. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9219. \begin{figure}[tp]
  9220. \fbox{
  9221. \begin{minipage}{0.96\textwidth}
  9222. \small
  9223. \[
  9224. \begin{array}{lcl}
  9225. \Exp &::= & \ldots
  9226. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9227. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9228. &\mid& \VALUEOF{\Exp}{\FType} \\
  9229. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9230. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9231. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9232. \mid \GOTO{\itm{label}} } \\
  9233. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9234. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9235. \mid \LP\key{Exit}\RP \\
  9236. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9237. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9238. \end{array}
  9239. \]
  9240. \end{minipage}
  9241. }
  9242. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9243. \label{fig:c5-syntax}
  9244. \end{figure}
  9245. \section{Select Instructions}
  9246. \label{sec:select-Rany}
  9247. In the \code{select-instructions} pass we translate the primitive
  9248. operations on the \code{Any} type to x86 instructions that involve
  9249. manipulating the 3 tag bits of the tagged value.
  9250. \paragraph{Make-any}
  9251. We recommend compiling the \key{make-any} primitive as follows if the
  9252. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9253. shifts the destination to the left by the number of bits specified its
  9254. source argument (in this case $3$, the length of the tag) and it
  9255. preserves the sign of the integer. We use the \key{orq} instruction to
  9256. combine the tag and the value to form the tagged value. \\
  9257. \begin{lstlisting}
  9258. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9259. |$\Rightarrow$|
  9260. movq |$e'$|, |\itm{lhs'}|
  9261. salq $3, |\itm{lhs'}|
  9262. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9263. \end{lstlisting}
  9264. The instruction selection for vectors and procedures is different
  9265. because their is no need to shift them to the left. The rightmost 3
  9266. bits are already zeros as described at the beginning of this
  9267. chapter. So we just combine the value and the tag using \key{orq}. \\
  9268. \begin{lstlisting}
  9269. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9270. |$\Rightarrow$|
  9271. movq |$e'$|, |\itm{lhs'}|
  9272. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9273. \end{lstlisting}
  9274. \paragraph{Tag-of-any}
  9275. Recall that the \code{tag-of-any} operation extracts the type tag from
  9276. a value of type \code{Any}. The type tag is the bottom three bits, so
  9277. we obtain the tag by taking the bitwise-and of the value with $111$
  9278. ($7$ in decimal).
  9279. \begin{lstlisting}
  9280. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9281. |$\Rightarrow$|
  9282. movq |$e'$|, |\itm{lhs'}|
  9283. andq $7, |\itm{lhs'}|
  9284. \end{lstlisting}
  9285. \paragraph{ValueOf}
  9286. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9287. depending on whether the type $T$ is a pointer (vector or procedure)
  9288. or not (Integer or Boolean). The following shows the instruction
  9289. selection for Integer and Boolean. We produce an untagged value by
  9290. shifting it to the right by 3 bits.
  9291. \begin{lstlisting}
  9292. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9293. |$\Rightarrow$|
  9294. movq |$e'$|, |\itm{lhs'}|
  9295. sarq $3, |\itm{lhs'}|
  9296. \end{lstlisting}
  9297. %
  9298. In the case for vectors and procedures, there is no need to
  9299. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9300. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9301. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9302. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9303. then apply \code{andq} with the tagged value to get the desired
  9304. result. \\
  9305. \begin{lstlisting}
  9306. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9307. |$\Rightarrow$|
  9308. movq $|$-8$|, |\itm{lhs'}|
  9309. andq |$e'$|, |\itm{lhs'}|
  9310. \end{lstlisting}
  9311. %% \paragraph{Type Predicates} We leave it to the reader to
  9312. %% devise a sequence of instructions to implement the type predicates
  9313. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9314. \paragraph{Any-vector-length}
  9315. \begin{lstlisting}
  9316. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9317. |$\Longrightarrow$|
  9318. movq |$\neg 111$|, %r11
  9319. andq |$a_1'$|, %r11
  9320. movq 0(%r11), %r11
  9321. andq $126, %r11
  9322. sarq $1, %r11
  9323. movq %r11, |$\itm{lhs'}$|
  9324. \end{lstlisting}
  9325. \paragraph{Any-vector-ref}
  9326. The index may be an arbitrary atom so instead of computing the offset
  9327. at compile time, instructions need to be generated to compute the
  9328. offset at runtime as follows. Note the use of the new instruction
  9329. \code{imulq}.
  9330. \begin{center}
  9331. \begin{minipage}{0.96\textwidth}
  9332. \begin{lstlisting}
  9333. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9334. |$\Longrightarrow$|
  9335. movq |$\neg 111$|, %r11
  9336. andq |$a_1'$|, %r11
  9337. movq |$a_2'$|, %rax
  9338. addq $1, %rax
  9339. imulq $8, %rax
  9340. addq %rax, %r11
  9341. movq 0(%r11) |$\itm{lhs'}$|
  9342. \end{lstlisting}
  9343. \end{minipage}
  9344. \end{center}
  9345. \paragraph{Any-vector-set!}
  9346. The code generation for \code{any-vector-set!} is similar to the other
  9347. \code{any-vector} operations.
  9348. \section{Register Allocation for \LangAny{}}
  9349. \label{sec:register-allocation-Rany}
  9350. \index{subject}{register allocation}
  9351. There is an interesting interaction between tagged values and garbage
  9352. collection that has an impact on register allocation. A variable of
  9353. type \code{Any} might refer to a vector and therefore it might be a
  9354. root that needs to be inspected and copied during garbage
  9355. collection. Thus, we need to treat variables of type \code{Any} in a
  9356. similar way to variables of type \code{Vector} for purposes of
  9357. register allocation. In particular,
  9358. \begin{itemize}
  9359. \item If a variable of type \code{Any} is live during a function call,
  9360. then it must be spilled. This can be accomplished by changing
  9361. \code{build-interference} to mark all variables of type \code{Any}
  9362. that are live after a \code{callq} as interfering with all the
  9363. registers.
  9364. \item If a variable of type \code{Any} is spilled, it must be spilled
  9365. to the root stack instead of the normal procedure call stack.
  9366. \end{itemize}
  9367. Another concern regarding the root stack is that the garbage collector
  9368. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9369. tagged value that points to a tuple, and (3) a tagged value that is
  9370. not a tuple. We enable this differentiation by choosing not to use the
  9371. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9372. reserved for identifying plain old pointers to tuples. That way, if
  9373. one of the first three bits is set, then we have a tagged value and
  9374. inspecting the tag can differentiation between vectors ($010$) and the
  9375. other kinds of values.
  9376. \begin{exercise}\normalfont
  9377. Expand your compiler to handle \LangAny{} as discussed in the last few
  9378. sections. Create 5 new programs that use the \code{Any} type and the
  9379. new operations (\code{inject}, \code{project}, \code{boolean?},
  9380. etc.). Test your compiler on these new programs and all of your
  9381. previously created test programs.
  9382. \end{exercise}
  9383. \begin{exercise}\normalfont
  9384. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9385. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9386. by removing type annotations. Add 5 more tests programs that
  9387. specifically rely on the language being dynamically typed. That is,
  9388. they should not be legal programs in a statically typed language, but
  9389. nevertheless, they should be valid \LangDyn{} programs that run to
  9390. completion without error.
  9391. \end{exercise}
  9392. \begin{figure}[p]
  9393. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9394. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9395. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9396. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9397. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9398. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9399. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9400. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9401. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9402. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9403. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9404. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9405. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9406. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9407. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9408. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9409. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9410. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9411. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9412. \path[->,bend left=15] (Rfun) edge [above] node
  9413. {\ttfamily\footnotesize shrink} (Rfun-2);
  9414. \path[->,bend left=15] (Rfun-2) edge [above] node
  9415. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9416. \path[->,bend left=15] (Rfun-3) edge [above] node
  9417. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9418. \path[->,bend right=15] (Rfun-4) edge [left] node
  9419. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9420. \path[->,bend left=15] (Rfun-5) edge [above] node
  9421. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9422. \path[->,bend left=15] (Rfun-6) edge [left] node
  9423. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9424. \path[->,bend left=15] (Rfun-7) edge [below] node
  9425. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9426. \path[->,bend right=15] (F1-2) edge [above] node
  9427. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9428. \path[->,bend right=15] (F1-3) edge [above] node
  9429. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9430. \path[->,bend right=15] (F1-4) edge [above] node
  9431. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9432. \path[->,bend right=15] (F1-5) edge [right] node
  9433. {\ttfamily\footnotesize explicate-control} (C3-2);
  9434. \path[->,bend left=15] (C3-2) edge [left] node
  9435. {\ttfamily\footnotesize select-instr.} (x86-2);
  9436. \path[->,bend right=15] (x86-2) edge [left] node
  9437. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9438. \path[->,bend right=15] (x86-2-1) edge [below] node
  9439. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9440. \path[->,bend right=15] (x86-2-2) edge [left] node
  9441. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9442. \path[->,bend left=15] (x86-3) edge [above] node
  9443. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9444. \path[->,bend left=15] (x86-4) edge [right] node
  9445. {\ttfamily\footnotesize print-x86} (x86-5);
  9446. \end{tikzpicture}
  9447. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9448. \label{fig:Rdyn-passes}
  9449. \end{figure}
  9450. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9451. for the compilation of \LangDyn{}.
  9452. % Further Reading
  9453. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9454. \chapter{Loops and Assignment}
  9455. \label{ch:Rwhile}
  9456. % TODO: define R'_8
  9457. % TODO: multi-graph
  9458. In this chapter we study two features that are the hallmarks of
  9459. imperative programming languages: loops and assignments to local
  9460. variables. The following example demonstrates these new features by
  9461. computing the sum of the first five positive integers.
  9462. % similar to loop_test_1.rkt
  9463. \begin{lstlisting}
  9464. (let ([sum 0])
  9465. (let ([i 5])
  9466. (begin
  9467. (while (> i 0)
  9468. (begin
  9469. (set! sum (+ sum i))
  9470. (set! i (- i 1))))
  9471. sum)))
  9472. \end{lstlisting}
  9473. The \code{while} loop consists of a condition and a body.
  9474. %
  9475. The \code{set!} consists of a variable and a right-hand-side expression.
  9476. %
  9477. The primary purpose of both the \code{while} loop and \code{set!} is
  9478. to cause side effects, so it is convenient to also include in a
  9479. language feature for sequencing side effects: the \code{begin}
  9480. expression. It consists of one or more subexpressions that are
  9481. evaluated left-to-right.
  9482. \section{The \LangLoop{} Language}
  9483. \begin{figure}[tp]
  9484. \centering
  9485. \fbox{
  9486. \begin{minipage}{0.96\textwidth}
  9487. \small
  9488. \[
  9489. \begin{array}{lcl}
  9490. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9491. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9492. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9493. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9494. \mid (\key{and}\;\Exp\;\Exp)
  9495. \mid (\key{or}\;\Exp\;\Exp)
  9496. \mid (\key{not}\;\Exp) } \\
  9497. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9498. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9499. (\key{vector-ref}\;\Exp\;\Int)} \\
  9500. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9501. \mid (\Exp \; \Exp\ldots) } \\
  9502. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9503. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9504. &\mid& \CSETBANG{\Var}{\Exp}
  9505. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9506. \mid \CWHILE{\Exp}{\Exp} \\
  9507. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9508. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  9509. \end{array}
  9510. \]
  9511. \end{minipage}
  9512. }
  9513. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  9514. \label{fig:Rwhile-concrete-syntax}
  9515. \end{figure}
  9516. \begin{figure}[tp]
  9517. \centering
  9518. \fbox{
  9519. \begin{minipage}{0.96\textwidth}
  9520. \small
  9521. \[
  9522. \begin{array}{lcl}
  9523. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9524. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9525. &\mid& \gray{ \BOOL{\itm{bool}}
  9526. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9527. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9528. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9529. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9530. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9531. \mid \WHILE{\Exp}{\Exp} \\
  9532. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9533. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9534. \end{array}
  9535. \]
  9536. \end{minipage}
  9537. }
  9538. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  9539. \label{fig:Rwhile-syntax}
  9540. \end{figure}
  9541. The concrete syntax of \LangLoop{} is defined in
  9542. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  9543. in Figure~\ref{fig:Rwhile-syntax}.
  9544. %
  9545. The definitional interpreter for \LangLoop{} is shown in
  9546. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9547. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9548. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9549. support assignment to variables and to make their lifetimes indefinite
  9550. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9551. box the value that is bound to each variable (in \code{Let}) and
  9552. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9553. the value.
  9554. %
  9555. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9556. variable in the environment to obtain a boxed value and then we change
  9557. it using \code{set-box!} to the result of evaluating the right-hand
  9558. side. The result value of a \code{SetBang} is \code{void}.
  9559. %
  9560. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9561. if the result is true, 2) evaluate the body.
  9562. The result value of a \code{while} loop is also \code{void}.
  9563. %
  9564. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9565. subexpressions \itm{es} for their effects and then evaluates
  9566. and returns the result from \itm{body}.
  9567. \begin{figure}[tbp]
  9568. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9569. (define interp-Rwhile-class
  9570. (class interp-Rany-class
  9571. (super-new)
  9572. (define/override ((interp-exp env) e)
  9573. (define recur (interp-exp env))
  9574. (match e
  9575. [(SetBang x rhs)
  9576. (set-box! (lookup x env) (recur rhs))]
  9577. [(WhileLoop cnd body)
  9578. (define (loop)
  9579. (cond [(recur cnd) (recur body) (loop)]
  9580. [else (void)]))
  9581. (loop)]
  9582. [(Begin es body)
  9583. (for ([e es]) (recur e))
  9584. (recur body)]
  9585. [else ((super interp-exp env) e)]))
  9586. ))
  9587. (define (interp-Rwhile p)
  9588. (send (new interp-Rwhile-class) interp-program p))
  9589. \end{lstlisting}
  9590. \caption{Interpreter for \LangLoop{}.}
  9591. \label{fig:interp-Rwhile}
  9592. \end{figure}
  9593. The type checker for \LangLoop{} is define in
  9594. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9595. variable and the right-hand-side must agree. The result type is
  9596. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9597. \code{Boolean}. The result type is also \code{Void}. For
  9598. \code{Begin}, the result type is the type of its last subexpression.
  9599. \begin{figure}[tbp]
  9600. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9601. (define type-check-Rwhile-class
  9602. (class type-check-Rany-class
  9603. (super-new)
  9604. (inherit check-type-equal?)
  9605. (define/override (type-check-exp env)
  9606. (lambda (e)
  9607. (define recur (type-check-exp env))
  9608. (match e
  9609. [(SetBang x rhs)
  9610. (define-values (rhs^ rhsT) (recur rhs))
  9611. (define varT (dict-ref env x))
  9612. (check-type-equal? rhsT varT e)
  9613. (values (SetBang x rhs^) 'Void)]
  9614. [(WhileLoop cnd body)
  9615. (define-values (cnd^ Tc) (recur cnd))
  9616. (check-type-equal? Tc 'Boolean e)
  9617. (define-values (body^ Tbody) ((type-check-exp env) body))
  9618. (values (WhileLoop cnd^ body^) 'Void)]
  9619. [(Begin es body)
  9620. (define-values (es^ ts)
  9621. (for/lists (l1 l2) ([e es]) (recur e)))
  9622. (define-values (body^ Tbody) (recur body))
  9623. (values (Begin es^ body^) Tbody)]
  9624. [else ((super type-check-exp env) e)])))
  9625. ))
  9626. (define (type-check-Rwhile p)
  9627. (send (new type-check-Rwhile-class) type-check-program p))
  9628. \end{lstlisting}
  9629. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9630. and \code{Begin} in \LangLoop{}.}
  9631. \label{fig:type-check-Rwhile}
  9632. \end{figure}
  9633. At first glance, the translation of these language features to x86
  9634. seems straightforward because the \LangCFun{} intermediate language already
  9635. supports all of the ingredients that we need: assignment, \code{goto},
  9636. conditional branching, and sequencing. However, there are two
  9637. complications that arise which we discuss in the next two
  9638. sections. After that we introduce one new compiler pass and the
  9639. changes necessary to the existing passes.
  9640. \section{Assignment and Lexically Scoped Functions}
  9641. \label{sec:assignment-scoping}
  9642. The addition of assignment raises a problem with our approach to
  9643. implementing lexically-scoped functions. Consider the following
  9644. example in which function \code{f} has a free variable \code{x} that
  9645. is changed after \code{f} is created but before the call to \code{f}.
  9646. % loop_test_11.rkt
  9647. \begin{lstlisting}
  9648. (let ([x 0])
  9649. (let ([y 0])
  9650. (let ([z 20])
  9651. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9652. (begin
  9653. (set! x 10)
  9654. (set! y 12)
  9655. (f y))))))
  9656. \end{lstlisting}
  9657. The correct output for this example is \code{42} because the call to
  9658. \code{f} is required to use the current value of \code{x} (which is
  9659. \code{10}). Unfortunately, the closure conversion pass
  9660. (Section~\ref{sec:closure-conversion}) generates code for the
  9661. \code{lambda} that copies the old value of \code{x} into a
  9662. closure. Thus, if we naively add support for assignment to our current
  9663. compiler, the output of this program would be \code{32}.
  9664. A first attempt at solving this problem would be to save a pointer to
  9665. \code{x} in the closure and change the occurrences of \code{x} inside
  9666. the lambda to dereference the pointer. Of course, this would require
  9667. assigning \code{x} to the stack and not to a register. However, the
  9668. problem goes a bit deeper. Consider the following example in which we
  9669. create a counter abstraction by creating a pair of functions that
  9670. share the free variable \code{x}.
  9671. % similar to loop_test_10.rkt
  9672. \begin{lstlisting}
  9673. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9674. (vector
  9675. (lambda: () : Integer x)
  9676. (lambda: () : Void (set! x (+ 1 x)))))
  9677. (let ([counter (f 0)])
  9678. (let ([get (vector-ref counter 0)])
  9679. (let ([inc (vector-ref counter 1)])
  9680. (begin
  9681. (inc)
  9682. (get)))))
  9683. \end{lstlisting}
  9684. In this example, the lifetime of \code{x} extends beyond the lifetime
  9685. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9686. stack frame for the call to \code{f}, it would be gone by the time we
  9687. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9688. \code{x}. This example demonstrates that when a variable occurs free
  9689. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9690. value of the variable needs to live on the heap. The verb ``box'' is
  9691. often used for allocating a single value on the heap, producing a
  9692. pointer, and ``unbox'' for dereferencing the pointer.
  9693. We recommend solving these problems by ``boxing'' the local variables
  9694. that are in the intersection of 1) variables that appear on the
  9695. left-hand-side of a \code{set!} and 2) variables that occur free
  9696. inside a \code{lambda}. We shall introduce a new pass named
  9697. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9698. perform this translation. But before diving into the compiler passes,
  9699. we one more problem to discuss.
  9700. \section{Cyclic Control Flow and Dataflow Analysis}
  9701. \label{sec:dataflow-analysis}
  9702. Up until this point the control-flow graphs generated in
  9703. \code{explicate-control} were guaranteed to be acyclic. However, each
  9704. \code{while} loop introduces a cycle in the control-flow graph.
  9705. But does that matter?
  9706. %
  9707. Indeed it does. Recall that for register allocation, the compiler
  9708. performs liveness analysis to determine which variables can share the
  9709. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9710. the control-flow graph in reverse topological order, but topological
  9711. order is only well-defined for acyclic graphs.
  9712. Let us return to the example of computing the sum of the first five
  9713. positive integers. Here is the program after instruction selection but
  9714. before register allocation.
  9715. \begin{center}
  9716. \begin{minipage}{0.45\textwidth}
  9717. \begin{lstlisting}
  9718. (define (main) : Integer
  9719. mainstart:
  9720. movq $0, sum1
  9721. movq $5, i2
  9722. jmp block5
  9723. block5:
  9724. movq i2, tmp3
  9725. cmpq tmp3, $0
  9726. jl block7
  9727. jmp block8
  9728. \end{lstlisting}
  9729. \end{minipage}
  9730. \begin{minipage}{0.45\textwidth}
  9731. \begin{lstlisting}
  9732. block7:
  9733. addq i2, sum1
  9734. movq $1, tmp4
  9735. negq tmp4
  9736. addq tmp4, i2
  9737. jmp block5
  9738. block8:
  9739. movq $27, %rax
  9740. addq sum1, %rax
  9741. jmp mainconclusion
  9742. )
  9743. \end{lstlisting}
  9744. \end{minipage}
  9745. \end{center}
  9746. Recall that liveness analysis works backwards, starting at the end
  9747. of each function. For this example we could start with \code{block8}
  9748. because we know what is live at the beginning of the conclusion,
  9749. just \code{rax} and \code{rsp}. So the live-before set
  9750. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9751. %
  9752. Next we might try to analyze \code{block5} or \code{block7}, but
  9753. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9754. we are stuck.
  9755. The way out of this impasse comes from the realization that one can
  9756. perform liveness analysis starting with an empty live-after set to
  9757. compute an under-approximation of the live-before set. By
  9758. \emph{under-approximation}, we mean that the set only contains
  9759. variables that are really live, but it may be missing some. Next, the
  9760. under-approximations for each block can be improved by 1) updating the
  9761. live-after set for each block using the approximate live-before sets
  9762. from the other blocks and 2) perform liveness analysis again on each
  9763. block. In fact, by iterating this process, the under-approximations
  9764. eventually become the correct solutions!
  9765. %
  9766. This approach of iteratively analyzing a control-flow graph is
  9767. applicable to many static analysis problems and goes by the name
  9768. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9769. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9770. Washington.
  9771. Let us apply this approach to the above example. We use the empty set
  9772. for the initial live-before set for each block. Let $m_0$ be the
  9773. following mapping from label names to sets of locations (variables and
  9774. registers).
  9775. \begin{center}
  9776. \begin{lstlisting}
  9777. mainstart: {}
  9778. block5: {}
  9779. block7: {}
  9780. block8: {}
  9781. \end{lstlisting}
  9782. \end{center}
  9783. Using the above live-before approximations, we determine the
  9784. live-after for each block and then apply liveness analysis to each
  9785. block. This produces our next approximation $m_1$ of the live-before
  9786. sets.
  9787. \begin{center}
  9788. \begin{lstlisting}
  9789. mainstart: {}
  9790. block5: {i2}
  9791. block7: {i2, sum1}
  9792. block8: {rsp, sum1}
  9793. \end{lstlisting}
  9794. \end{center}
  9795. For the second round, the live-after for \code{mainstart} is the
  9796. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9797. liveness analysis for \code{mainstart} computes the empty set. The
  9798. live-after for \code{block5} is the union of the live-before sets for
  9799. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9800. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9801. sum1\}}. The live-after for \code{block7} is the live-before for
  9802. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9803. So the liveness analysis for \code{block7} remains \code{\{i2,
  9804. sum1\}}. Together these yield the following approximation $m_2$ of
  9805. the live-before sets.
  9806. \begin{center}
  9807. \begin{lstlisting}
  9808. mainstart: {}
  9809. block5: {i2, rsp, sum1}
  9810. block7: {i2, sum1}
  9811. block8: {rsp, sum1}
  9812. \end{lstlisting}
  9813. \end{center}
  9814. In the preceding iteration, only \code{block5} changed, so we can
  9815. limit our attention to \code{mainstart} and \code{block7}, the two
  9816. blocks that jump to \code{block5}. As a result, the live-before sets
  9817. for \code{mainstart} and \code{block7} are updated to include
  9818. \code{rsp}, yielding the following approximation $m_3$.
  9819. \begin{center}
  9820. \begin{lstlisting}
  9821. mainstart: {rsp}
  9822. block5: {i2, rsp, sum1}
  9823. block7: {i2, rsp, sum1}
  9824. block8: {rsp, sum1}
  9825. \end{lstlisting}
  9826. \end{center}
  9827. Because \code{block7} changed, we analyze \code{block5} once more, but
  9828. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9829. our approximations have converged, so $m_3$ is the solution.
  9830. This iteration process is guaranteed to converge to a solution by the
  9831. Kleene Fixed-Point Theorem, a general theorem about functions on
  9832. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9833. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9834. elements, a least element $\bot$ (pronounced bottom), and a join
  9835. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9836. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9837. working with join semi-lattices.} When two elements are ordered $m_i
  9838. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9839. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9840. approximation than $m_i$. The bottom element $\bot$ represents the
  9841. complete lack of information, i.e., the worst approximation. The join
  9842. operator takes two lattice elements and combines their information,
  9843. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9844. bound}
  9845. A dataflow analysis typically involves two lattices: one lattice to
  9846. represent abstract states and another lattice that aggregates the
  9847. abstract states of all the blocks in the control-flow graph. For
  9848. liveness analysis, an abstract state is a set of locations. We form
  9849. the lattice $L$ by taking its elements to be sets of locations, the
  9850. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9851. set, and the join operator to be set union.
  9852. %
  9853. We form a second lattice $M$ by taking its elements to be mappings
  9854. from the block labels to sets of locations (elements of $L$). We
  9855. order the mappings point-wise, using the ordering of $L$. So given any
  9856. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9857. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9858. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9859. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9860. We can think of one iteration of liveness analysis as being a function
  9861. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9862. mapping.
  9863. \[
  9864. f(m_i) = m_{i+1}
  9865. \]
  9866. Next let us think for a moment about what a final solution $m_s$
  9867. should look like. If we perform liveness analysis using the solution
  9868. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9869. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9870. \[
  9871. f(m_s) = m_s
  9872. \]
  9873. Furthermore, the solution should only include locations that are
  9874. forced to be there by performing liveness analysis on the program, so
  9875. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9876. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9877. monotone (better inputs produce better outputs), then the least fixed
  9878. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9879. chain} obtained by starting at $\bot$ and iterating $f$ as
  9880. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9881. \[
  9882. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9883. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9884. \]
  9885. When a lattice contains only finitely-long ascending chains, then
  9886. every Kleene chain tops out at some fixed point after a number of
  9887. iterations of $f$. So that fixed point is also a least upper
  9888. bound of the chain.
  9889. \[
  9890. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9891. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9892. \]
  9893. The liveness analysis is indeed a monotone function and the lattice
  9894. $M$ only has finitely-long ascending chains because there are only a
  9895. finite number of variables and blocks in the program. Thus we are
  9896. guaranteed that iteratively applying liveness analysis to all blocks
  9897. in the program will eventually produce the least fixed point solution.
  9898. Next let us consider dataflow analysis in general and discuss the
  9899. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9900. %
  9901. The algorithm has four parameters: the control-flow graph \code{G}, a
  9902. function \code{transfer} that applies the analysis to one block, the
  9903. \code{bottom} and \code{join} operator for the lattice of abstract
  9904. states. The algorithm begins by creating the bottom mapping,
  9905. represented by a hash table. It then pushes all of the nodes in the
  9906. control-flow graph onto the work list (a queue). The algorithm repeats
  9907. the \code{while} loop as long as there are items in the work list. In
  9908. each iteration, a node is popped from the work list and processed. The
  9909. \code{input} for the node is computed by taking the join of the
  9910. abstract states of all the predecessor nodes. The \code{transfer}
  9911. function is then applied to obtain the \code{output} abstract
  9912. state. If the output differs from the previous state for this block,
  9913. the mapping for this block is updated and its successor nodes are
  9914. pushed onto the work list.
  9915. \begin{figure}[tb]
  9916. \begin{lstlisting}
  9917. (define (analyze-dataflow G transfer bottom join)
  9918. (define mapping (make-hash))
  9919. (for ([v (in-vertices G)])
  9920. (dict-set! mapping v bottom))
  9921. (define worklist (make-queue))
  9922. (for ([v (in-vertices G)])
  9923. (enqueue! worklist v))
  9924. (define trans-G (transpose G))
  9925. (while (not (queue-empty? worklist))
  9926. (define node (dequeue! worklist))
  9927. (define input (for/fold ([state bottom])
  9928. ([pred (in-neighbors trans-G node)])
  9929. (join state (dict-ref mapping pred))))
  9930. (define output (transfer node input))
  9931. (cond [(not (equal? output (dict-ref mapping node)))
  9932. (dict-set! mapping node output)
  9933. (for ([v (in-neighbors G node)])
  9934. (enqueue! worklist v))]))
  9935. mapping)
  9936. \end{lstlisting}
  9937. \caption{Generic work list algorithm for dataflow analysis}
  9938. \label{fig:generic-dataflow}
  9939. \end{figure}
  9940. Having discussed the two complications that arise from adding support
  9941. for assignment and loops, we turn to discussing the one new compiler
  9942. pass and the significant changes to existing passes.
  9943. \section{Convert Assignments}
  9944. \label{sec:convert-assignments}
  9945. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9946. the combination of assignments and lexically-scoped functions requires
  9947. that we box those variables that are both assigned-to and that appear
  9948. free inside a \code{lambda}. The purpose of the
  9949. \code{convert-assignments} pass is to carry out that transformation.
  9950. We recommend placing this pass after \code{uniquify} but before
  9951. \code{reveal-functions}.
  9952. Consider again the first example from
  9953. Section~\ref{sec:assignment-scoping}:
  9954. \begin{lstlisting}
  9955. (let ([x 0])
  9956. (let ([y 0])
  9957. (let ([z 20])
  9958. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9959. (begin
  9960. (set! x 10)
  9961. (set! y 12)
  9962. (f y))))))
  9963. \end{lstlisting}
  9964. The variables \code{x} and \code{y} are assigned-to. The variables
  9965. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  9966. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  9967. The boxing of \code{x} consists of three transformations: initialize
  9968. \code{x} with a vector, replace reads from \code{x} with
  9969. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  9970. \code{vector-set!}. The output of \code{convert-assignments} for this
  9971. example is as follows.
  9972. \begin{lstlisting}
  9973. (define (main) : Integer
  9974. (let ([x0 (vector 0)])
  9975. (let ([y1 0])
  9976. (let ([z2 20])
  9977. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  9978. (+ a3 (+ (vector-ref x0 0) z2)))])
  9979. (begin
  9980. (vector-set! x0 0 10)
  9981. (set! y1 12)
  9982. (f4 y1)))))))
  9983. \end{lstlisting}
  9984. \paragraph{Assigned \& Free}
  9985. We recommend defining an auxiliary function named
  9986. \code{assigned\&free} that takes an expression and simultaneously
  9987. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  9988. that occur free within lambda's, and 3) a new version of the
  9989. expression that records which bound variables occurred in the
  9990. intersection of $A$ and $F$. You can use the struct
  9991. \code{AssignedFree} to do this. Consider the case for
  9992. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  9993. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  9994. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  9995. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  9996. \begin{lstlisting}
  9997. (Let |$x$| |$rhs$| |$body$|)
  9998. |$\Rightarrow$|
  9999. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10000. \end{lstlisting}
  10001. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10002. The set of assigned variables for this \code{Let} is
  10003. $A_r \cup (A_b - \{x\})$
  10004. and the set of variables free in lambda's is
  10005. $F_r \cup (F_b - \{x\})$.
  10006. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10007. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10008. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10009. and $F_r$.
  10010. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10011. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10012. recursively processing \itm{body}. Wrap each of parameter that occurs
  10013. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10014. Let $P$ be the set of parameter names in \itm{params}. The result is
  10015. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10016. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10017. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10018. \paragraph{Convert Assignments}
  10019. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10020. functions for expressions and definitions. The function for
  10021. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10022. set of assigned-and-free variables (obtained from the result of
  10023. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10024. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10025. \code{vector-ref}.
  10026. \begin{lstlisting}
  10027. (Var |$x$|)
  10028. |$\Rightarrow$|
  10029. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10030. \end{lstlisting}
  10031. %
  10032. In the case for $\LET{\LP\code{AssignedFree}\,
  10033. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10034. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10035. \itm{body'} but with $x$ added to the set of assigned-and-free
  10036. variables. Translate the let-expression as follows to bind $x$ to a
  10037. boxed value.
  10038. \begin{lstlisting}
  10039. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10040. |$\Rightarrow$|
  10041. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10042. \end{lstlisting}
  10043. %
  10044. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10045. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10046. variables, translate the \code{set!} into a \code{vector-set!}
  10047. as follows.
  10048. \begin{lstlisting}
  10049. (SetBang |$x$| |$\itm{rhs}$|)
  10050. |$\Rightarrow$|
  10051. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10052. \end{lstlisting}
  10053. %
  10054. The case for \code{Lambda} is non-trivial, but it is similar to the
  10055. case for function definitions, which we discuss next.
  10056. The auxiliary function for definitions, \code{cnvt-assign-def},
  10057. applies assignment conversion to function definitions.
  10058. We translate a function definition as follows.
  10059. \begin{lstlisting}
  10060. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10061. |$\Rightarrow$|
  10062. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10063. \end{lstlisting}
  10064. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10065. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10066. \code{assigned\&free} on $\itm{body_1}$.
  10067. Let $P$ be the parameter names in \itm{params}.
  10068. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10069. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10070. as the set of assigned-and-free variables.
  10071. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10072. in a sequence of let-expressions that box the parameters
  10073. that are in $A_b \cap F_b$.
  10074. %
  10075. Regarding \itm{params'}, change the names of the parameters that are
  10076. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10077. variables can retain the original names). Recall the second example in
  10078. Section~\ref{sec:assignment-scoping} involving a counter
  10079. abstraction. The following is the output of assignment version for
  10080. function \code{f}.
  10081. \begin{lstlisting}
  10082. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10083. (vector
  10084. (lambda: () : Integer x1)
  10085. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10086. |$\Rightarrow$|
  10087. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10088. (let ([x1 (vector param_x1)])
  10089. (vector (lambda: () : Integer (vector-ref x1 0))
  10090. (lambda: () : Void
  10091. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10092. \end{lstlisting}
  10093. \section{Remove Complex Operands}
  10094. \label{sec:rco-loop}
  10095. The three new language forms, \code{while}, \code{set!}, and
  10096. \code{begin} are all complex expressions and their subexpressions are
  10097. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10098. output language \LangFunANF{} of this pass.
  10099. \begin{figure}[tp]
  10100. \centering
  10101. \fbox{
  10102. \begin{minipage}{0.96\textwidth}
  10103. \small
  10104. \[
  10105. \begin{array}{rcl}
  10106. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10107. \mid \VOID{} } \\
  10108. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10109. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10110. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10111. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10112. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10113. \end{array}
  10114. \]
  10115. \end{minipage}
  10116. }
  10117. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10118. \label{fig:Rwhile-anf-syntax}
  10119. \end{figure}
  10120. As usual, when a complex expression appears in a grammar position that
  10121. needs to be atomic, such as the argument of a primitive operator, we
  10122. must introduce a temporary variable and bind it to the complex
  10123. expression. This approach applies, unchanged, to handle the new
  10124. language forms. For example, in the following code there are two
  10125. \code{begin} expressions appearing as arguments to \code{+}. The
  10126. output of \code{rco-exp} is shown below, in which the \code{begin}
  10127. expressions have been bound to temporary variables. Recall that
  10128. \code{let} expressions in \LangLoopANF{} are allowed to have
  10129. arbitrary expressions in their right-hand-side expression, so it is
  10130. fine to place \code{begin} there.
  10131. \begin{lstlisting}
  10132. (let ([x0 10])
  10133. (let ([y1 0])
  10134. (+ (+ (begin (set! y1 (read)) x0)
  10135. (begin (set! x0 (read)) y1))
  10136. x0)))
  10137. |$\Rightarrow$|
  10138. (let ([x0 10])
  10139. (let ([y1 0])
  10140. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10141. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10142. (let ([tmp4 (+ tmp2 tmp3)])
  10143. (+ tmp4 x0))))))
  10144. \end{lstlisting}
  10145. \section{Explicate Control and \LangCLoop{}}
  10146. \label{sec:explicate-loop}
  10147. Recall that in the \code{explicate-control} pass we define one helper
  10148. function for each kind of position in the program. For the \LangVar{}
  10149. language of integers and variables we needed kinds of positions:
  10150. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10151. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10152. yet another kind of position: effect position. Except for the last
  10153. subexpression, the subexpressions inside a \code{begin} are evaluated
  10154. only for their effect. Their result values are discarded. We can
  10155. generate better code by taking this fact into account.
  10156. The output language of \code{explicate-control} is \LangCLoop{}
  10157. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10158. \LangCLam{}. The only syntactic difference is that \code{Call},
  10159. \code{vector-set!}, and \code{read} may also appear as statements.
  10160. The most significant difference between \LangCLam{} and \LangCLoop{}
  10161. is that the control-flow graphs of the later may contain cycles.
  10162. \begin{figure}[tp]
  10163. \fbox{
  10164. \begin{minipage}{0.96\textwidth}
  10165. \small
  10166. \[
  10167. \begin{array}{lcl}
  10168. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10169. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10170. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10171. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10172. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10173. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10174. \end{array}
  10175. \]
  10176. \end{minipage}
  10177. }
  10178. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10179. \label{fig:c7-syntax}
  10180. \end{figure}
  10181. The new auxiliary function \code{explicate-effect} takes an expression
  10182. (in an effect position) and a promise of a continuation block. The
  10183. function returns a promise for a $\Tail$ that includes the generated
  10184. code for the input expression followed by the continuation block. If
  10185. the expression is obviously pure, that is, never causes side effects,
  10186. then the expression can be removed, so the result is just the
  10187. continuation block.
  10188. %
  10189. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10190. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10191. the loop. Recursively process the \itm{body} (in effect position)
  10192. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10193. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10194. \itm{body'} as the then-branch and the continuation block as the
  10195. else-branch. The result should be added to the control-flow graph with
  10196. the label \itm{loop}. The result for the whole \code{while} loop is a
  10197. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10198. added to the control-flow graph if the loop is indeed used, which can
  10199. be accomplished using \code{delay}.
  10200. The auxiliary functions for tail, assignment, and predicate positions
  10201. need to be updated. The three new language forms, \code{while},
  10202. \code{set!}, and \code{begin}, can appear in assignment and tail
  10203. positions. Only \code{begin} may appear in predicate positions; the
  10204. other two have result type \code{Void}.
  10205. \section{Select Instructions}
  10206. \label{sec:select-instructions-loop}
  10207. Only three small additions are needed in the
  10208. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10209. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10210. stand-alone statements instead of only appearing on the right-hand
  10211. side of an assignment statement. The code generation is nearly
  10212. identical; just leave off the instruction for moving the result into
  10213. the left-hand side.
  10214. \section{Register Allocation}
  10215. \label{sec:register-allocation-loop}
  10216. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10217. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10218. which complicates the liveness analysis needed for register
  10219. allocation.
  10220. \subsection{Liveness Analysis}
  10221. \label{sec:liveness-analysis-r8}
  10222. We recommend using the generic \code{analyze-dataflow} function that
  10223. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10224. perform liveness analysis, replacing the code in
  10225. \code{uncover-live-CFG} that processed the basic blocks in topological
  10226. order (Section~\ref{sec:liveness-analysis-Rif}).
  10227. The \code{analyze-dataflow} function has four parameters.
  10228. \begin{enumerate}
  10229. \item The first parameter \code{G} should be a directed graph from the
  10230. \code{racket/graph} package (see the sidebar in
  10231. Section~\ref{sec:build-interference}) that represents the
  10232. control-flow graph.
  10233. \item The second parameter \code{transfer} is a function that applies
  10234. liveness analysis to a basic block. It takes two parameters: the
  10235. label for the block to analyze and the live-after set for that
  10236. block. The transfer function should return the live-before set for
  10237. the block. Also, as a side-effect, it should update the block's
  10238. $\itm{info}$ with the liveness information for each instruction. To
  10239. implement the \code{transfer} function, you should be able to reuse
  10240. the code you already have for analyzing basic blocks.
  10241. \item The third and fourth parameters of \code{analyze-dataflow} are
  10242. \code{bottom} and \code{join} for the lattice of abstract states,
  10243. i.e. sets of locations. The bottom of the lattice is the empty set
  10244. \code{(set)} and the join operator is \code{set-union}.
  10245. \end{enumerate}
  10246. \begin{figure}[p]
  10247. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10248. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10249. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10250. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10251. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10252. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10253. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10254. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10255. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10256. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10257. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10258. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10259. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10260. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10261. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10262. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10263. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10264. %% \path[->,bend left=15] (Rfun) edge [above] node
  10265. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10266. \path[->,bend left=15] (Rfun) edge [above] node
  10267. {\ttfamily\footnotesize shrink} (Rfun-2);
  10268. \path[->,bend left=15] (Rfun-2) edge [above] node
  10269. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10270. \path[->,bend left=15] (Rfun-3) edge [above] node
  10271. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10272. \path[->,bend left=15] (Rfun-4) edge [right] node
  10273. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10274. \path[->,bend left=15] (F1-1) edge [below] node
  10275. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10276. \path[->,bend right=15] (F1-2) edge [above] node
  10277. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10278. \path[->,bend right=15] (F1-3) edge [above] node
  10279. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10280. \path[->,bend right=15] (F1-4) edge [above] node
  10281. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10282. \path[->,bend right=15] (F1-5) edge [right] node
  10283. {\ttfamily\footnotesize explicate-control} (C3-2);
  10284. \path[->,bend left=15] (C3-2) edge [left] node
  10285. {\ttfamily\footnotesize select-instr.} (x86-2);
  10286. \path[->,bend right=15] (x86-2) edge [left] node
  10287. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10288. \path[->,bend right=15] (x86-2-1) edge [below] node
  10289. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10290. \path[->,bend right=15] (x86-2-2) edge [left] node
  10291. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10292. \path[->,bend left=15] (x86-3) edge [above] node
  10293. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10294. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10295. \end{tikzpicture}
  10296. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10297. \label{fig:Rwhile-passes}
  10298. \end{figure}
  10299. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10300. for the compilation of \LangLoop{}.
  10301. \section{Challenge: Arrays}
  10302. \label{sec:arrays}
  10303. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10304. elements whose length is determined at compile-time and where each
  10305. element of a tuple may have a different type (they are
  10306. heterogeous). This challenge is also about sequences, but this time
  10307. the length is determined at run-time and all the elements have the same
  10308. type (they are homogeneous). We use the term ``array'' for this later
  10309. kind of sequence.
  10310. The Racket language does not distinguish between tuples and arrays,
  10311. they are both represented by vectors. However, Typed Racket
  10312. distinguishes between tuples and arrays: the \code{Vector} type is for
  10313. tuples and the \code{Vectorof} type is for arrays.
  10314. %
  10315. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10316. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10317. and the \code{make-vector} primitive operator for creating an array,
  10318. whose arguments are the length of the array and an initial value for
  10319. all the elements in the array. The \code{vector-length},
  10320. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10321. for tuples become overloaded for use with arrays.
  10322. %
  10323. We also include integer multiplication in \LangArray{}, as it is
  10324. useful in many examples involving arrays such as computing the
  10325. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10326. \begin{figure}[tp]
  10327. \centering
  10328. \fbox{
  10329. \begin{minipage}{0.96\textwidth}
  10330. \small
  10331. \[
  10332. \begin{array}{lcl}
  10333. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  10334. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10335. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  10336. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10337. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10338. \mid \LP\key{and}\;\Exp\;\Exp\RP
  10339. \mid \LP\key{or}\;\Exp\;\Exp\RP
  10340. \mid \LP\key{not}\;\Exp\RP } \\
  10341. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10342. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  10343. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10344. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  10345. \mid \LP\Exp \; \Exp\ldots\RP } \\
  10346. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10347. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10348. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10349. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10350. \mid \CWHILE{\Exp}{\Exp} } \\
  10351. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  10352. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10353. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10354. \end{array}
  10355. \]
  10356. \end{minipage}
  10357. }
  10358. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10359. \label{fig:Rvecof-concrete-syntax}
  10360. \end{figure}
  10361. \begin{figure}[tp]
  10362. \begin{lstlisting}
  10363. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10364. [n : Integer]) : Integer
  10365. (let ([i 0])
  10366. (let ([prod 0])
  10367. (begin
  10368. (while (< i n)
  10369. (begin
  10370. (set! prod (+ prod (* (vector-ref A i)
  10371. (vector-ref B i))))
  10372. (set! i (+ i 1))
  10373. ))
  10374. prod))))
  10375. (let ([A (make-vector 2 2)])
  10376. (let ([B (make-vector 2 3)])
  10377. (+ (inner-product A B 2)
  10378. 30)))
  10379. \end{lstlisting}
  10380. \caption{Example program that computes the inner-product.}
  10381. \label{fig:inner-product}
  10382. \end{figure}
  10383. The type checker for \LangArray{} is define in
  10384. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10385. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10386. of the intializing expression. The length expression is required to
  10387. have type \code{Integer}. The type checking of the operators
  10388. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10389. updated to handle the situation where the vector has type
  10390. \code{Vectorof}. In these cases we translate the operators to their
  10391. \code{vectorof} form so that later passes can easily distinguish
  10392. between operations on tuples versus arrays. We override the
  10393. \code{operator-types} method to provide the type signature for
  10394. multiplication: it takes two integers and returns an integer. To
  10395. support injection and projection of arrays to the \code{Any} type
  10396. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10397. predicate.
  10398. \begin{figure}[tbp]
  10399. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10400. (define type-check-Rvecof-class
  10401. (class type-check-Rwhile-class
  10402. (super-new)
  10403. (inherit check-type-equal?)
  10404. (define/override (flat-ty? ty)
  10405. (match ty
  10406. ['(Vectorof Any) #t]
  10407. [else (super flat-ty? ty)]))
  10408. (define/override (operator-types)
  10409. (append '((* . ((Integer Integer) . Integer)))
  10410. (super operator-types)))
  10411. (define/override (type-check-exp env)
  10412. (lambda (e)
  10413. (define recur (type-check-exp env))
  10414. (match e
  10415. [(Prim 'make-vector (list e1 e2))
  10416. (define-values (e1^ t1) (recur e1))
  10417. (define-values (e2^ elt-type) (recur e2))
  10418. (define vec-type `(Vectorof ,elt-type))
  10419. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10420. vec-type)]
  10421. [(Prim 'vector-ref (list e1 e2))
  10422. (define-values (e1^ t1) (recur e1))
  10423. (define-values (e2^ t2) (recur e2))
  10424. (match* (t1 t2)
  10425. [(`(Vectorof ,elt-type) 'Integer)
  10426. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10427. [(other wise) ((super type-check-exp env) e)])]
  10428. [(Prim 'vector-set! (list e1 e2 e3) )
  10429. (define-values (e-vec t-vec) (recur e1))
  10430. (define-values (e2^ t2) (recur e2))
  10431. (define-values (e-arg^ t-arg) (recur e3))
  10432. (match t-vec
  10433. [`(Vectorof ,elt-type)
  10434. (check-type-equal? elt-type t-arg e)
  10435. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10436. [else ((super type-check-exp env) e)])]
  10437. [(Prim 'vector-length (list e1))
  10438. (define-values (e1^ t1) (recur e1))
  10439. (match t1
  10440. [`(Vectorof ,t)
  10441. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10442. [else ((super type-check-exp env) e)])]
  10443. [else ((super type-check-exp env) e)])))
  10444. ))
  10445. (define (type-check-Rvecof p)
  10446. (send (new type-check-Rvecof-class) type-check-program p))
  10447. \end{lstlisting}
  10448. \caption{Type checker for the \LangArray{} language.}
  10449. \label{fig:type-check-Rvecof}
  10450. \end{figure}
  10451. The interpreter for \LangArray{} is defined in
  10452. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10453. implemented with Racket's \code{make-vector} function and
  10454. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10455. integers.
  10456. \begin{figure}[tbp]
  10457. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10458. (define interp-Rvecof-class
  10459. (class interp-Rwhile-class
  10460. (super-new)
  10461. (define/override (interp-op op)
  10462. (verbose "Rvecof/interp-op" op)
  10463. (match op
  10464. ['make-vector make-vector]
  10465. ['* fx*]
  10466. [else (super interp-op op)]))
  10467. ))
  10468. (define (interp-Rvecof p)
  10469. (send (new interp-Rvecof-class) interp-program p))
  10470. \end{lstlisting}
  10471. \caption{Interpreter for \LangArray{}.}
  10472. \label{fig:interp-Rvecof}
  10473. \end{figure}
  10474. \subsection{Data Representation}
  10475. \label{sec:array-rep}
  10476. Just like tuples, we store arrays on the heap which means that the
  10477. garbage collector will need to inspect arrays. An immediate thought is
  10478. to use the same representation for arrays that we use for tuples.
  10479. However, we limit tuples to a length of $50$ so that their length and
  10480. pointer mask can fit into the 64-bit tag at the beginning of each
  10481. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10482. millions of elements, so we need more bits to store the length.
  10483. However, because arrays are homogeneous, we only need $1$ bit for the
  10484. pointer mask instead of one bit per array elements. Finally, the
  10485. garbage collector will need to be able to distinguish between tuples
  10486. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10487. arrive at the following layout for the 64-bit tag at the beginning of
  10488. an array:
  10489. \begin{itemize}
  10490. \item The right-most bit is the forwarding bit, just like in a tuple.
  10491. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10492. it is not.
  10493. \item The next bit to the left is the pointer mask. A $0$ indicates
  10494. that none of the elements are pointers to the heap and a $1$
  10495. indicates that all of the elements are pointers.
  10496. \item The next $61$ bits store the length of the array.
  10497. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10498. array ($1$).
  10499. \end{itemize}
  10500. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10501. differentiate the kinds of values that have been injected into the
  10502. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10503. to indicate that the value is an array.
  10504. In the following subsections we provide hints regarding how to update
  10505. the passes to handle arrays.
  10506. \subsection{Reveal Casts}
  10507. The array-access operators \code{vectorof-ref} and
  10508. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10509. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10510. that the type checker cannot tell whether the index will be in bounds,
  10511. so the bounds check must be performed at run time. Recall that the
  10512. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10513. an \code{If} arround a vector reference for update to check whether
  10514. the index is less than the length. You should do the same for
  10515. \code{vectorof-ref} and \code{vectorof-set!} .
  10516. In addition, the handling of the \code{any-vector} operators in
  10517. \code{reveal-casts} needs to be updated to account for arrays that are
  10518. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10519. generated code should test whether the tag is for tuples (\code{010})
  10520. or arrays (\code{110}) and then dispatch to either
  10521. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10522. we add a case in \code{select-instructions} to generate the
  10523. appropriate instructions for accessing the array length from the
  10524. header of an array.
  10525. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10526. the generated code needs to check that the index is less than the
  10527. vector length, so like the code for \code{any-vector-length}, check
  10528. the tag to determine whether to use \code{any-vector-length} or
  10529. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10530. is complete, the generated code can use \code{any-vector-ref} and
  10531. \code{any-vector-set!} for both tuples and arrays because the
  10532. instructions used for those operators do not look at the tag at the
  10533. front of the tuple or array.
  10534. \subsection{Expose Allocation}
  10535. This pass should translate the \code{make-vector} operator into
  10536. lower-level operations. In particular, the new AST node
  10537. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10538. length specified by the $\Exp$, but does not initialize the elements
  10539. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10540. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10541. element type for the array. Regarding the initialization of the array,
  10542. we recommend generated a \code{while} loop that uses
  10543. \code{vector-set!} to put the initializing value into every element of
  10544. the array.
  10545. \subsection{Remove Complex Operands}
  10546. Add cases in the \code{rco-atom} and \code{rco-exp} for
  10547. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10548. complex and its subexpression must be atomic.
  10549. \subsection{Explicate Control}
  10550. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  10551. \code{explicate-assign}.
  10552. \subsection{Select Instructions}
  10553. Generate instructions for \code{AllocateArray} similar to those for
  10554. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10555. that the tag at the front of the array should instead use the
  10556. representation discussed in Section~\ref{sec:array-rep}.
  10557. Regarding \code{vectorof-length}, extract the length from the tag
  10558. according to the representation discussed in
  10559. Section~\ref{sec:array-rep}.
  10560. The instructions generated for \code{vectorof-ref} differ from those
  10561. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10562. that the index is not a constant so the offset must be computed at
  10563. runtime, similar to the instructions generated for
  10564. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10565. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10566. appear in an assignment and as a stand-alone statement, so make sure
  10567. to handle both situations in this pass.
  10568. Finally, the instructions for \code{any-vectorof-length} should be
  10569. similar to those for \code{vectorof-length}, except that one must
  10570. first project the array by writing zeroes into the $3$-bit tag
  10571. \begin{exercise}\normalfont
  10572. Implement a compiler for the \LangArray{} language by extending your
  10573. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10574. programs, including the one in Figure~\ref{fig:inner-product} and also
  10575. a program that multiplies two matrices. Note that matrices are
  10576. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10577. arrays by laying out each row in the array, one after the next.
  10578. \end{exercise}
  10579. % Further Reading: dataflow analysis
  10580. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10581. \chapter{Gradual Typing}
  10582. \label{ch:Rgrad}
  10583. \index{subject}{gradual typing}
  10584. This chapter studies a language, \LangGrad{}, in which the programmer
  10585. can choose between static and dynamic type checking in different parts
  10586. of a program, thereby mixing the statically typed \LangLoop{} language
  10587. with the dynamically typed \LangDyn{}. There are several approaches to
  10588. mixing static and dynamic typing, including multi-language
  10589. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10590. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10591. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  10592. programmer controls the amount of static versus dynamic checking by
  10593. adding or removing type annotations on parameters and
  10594. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10595. %
  10596. The concrete syntax of \LangGrad{} is defined in
  10597. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  10598. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  10599. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10600. non-terminals that make type annotations optional. The return types
  10601. are not optional in the abstract syntax; the parser fills in
  10602. \code{Any} when the return type is not specified in the concrete
  10603. syntax.
  10604. \begin{figure}[tp]
  10605. \centering
  10606. \fbox{
  10607. \begin{minipage}{0.96\textwidth}
  10608. \small
  10609. \[
  10610. \begin{array}{lcl}
  10611. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10612. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10613. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10614. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10615. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10616. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10617. \mid (\key{and}\;\Exp\;\Exp)
  10618. \mid (\key{or}\;\Exp\;\Exp)
  10619. \mid (\key{not}\;\Exp) } \\
  10620. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10621. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10622. (\key{vector-ref}\;\Exp\;\Int)} \\
  10623. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10624. \mid (\Exp \; \Exp\ldots) } \\
  10625. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10626. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10627. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10628. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10629. \mid \CWHILE{\Exp}{\Exp} } \\
  10630. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10631. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  10632. \end{array}
  10633. \]
  10634. \end{minipage}
  10635. }
  10636. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10637. \label{fig:Rgrad-concrete-syntax}
  10638. \end{figure}
  10639. \begin{figure}[tp]
  10640. \centering
  10641. \fbox{
  10642. \begin{minipage}{0.96\textwidth}
  10643. \small
  10644. \[
  10645. \begin{array}{lcl}
  10646. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10647. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10648. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10649. &\mid& \gray{ \BOOL{\itm{bool}}
  10650. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10651. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10652. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10653. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10654. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10655. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10656. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10657. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10658. \end{array}
  10659. \]
  10660. \end{minipage}
  10661. }
  10662. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10663. \label{fig:Rgrad-syntax}
  10664. \end{figure}
  10665. Both the type checker and the interpreter for \LangGrad{} require some
  10666. interesting changes to enable gradual typing, which we discuss in the
  10667. next two sections in the context of the \code{map-vec} example from
  10668. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  10669. revised the \code{map-vec} example, omitting the type annotations from
  10670. the \code{add1} function.
  10671. \begin{figure}[btp]
  10672. % gradual_test_9.rkt
  10673. \begin{lstlisting}
  10674. (define (map-vec [f : (Integer -> Integer)]
  10675. [v : (Vector Integer Integer)])
  10676. : (Vector Integer Integer)
  10677. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10678. (define (add1 x) (+ x 1))
  10679. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10680. \end{lstlisting}
  10681. \caption{A partially-typed version of the \code{map-vec} example.}
  10682. \label{fig:gradual-map-vec}
  10683. \end{figure}
  10684. \section{Type Checking \LangGrad{} and \LangCast{}}
  10685. \label{sec:gradual-type-check}
  10686. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10687. parameter and return types. For example, the \code{x} parameter of
  10688. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10689. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10690. consider the \code{+} operator inside \code{add1}. It expects both
  10691. arguments to have type \code{Integer}, but its first argument \code{x}
  10692. has type \code{Any}. In a gradually typed language, such differences
  10693. are allowed so long as the types are \emph{consistent}, that is, they
  10694. are equal except in places where there is an \code{Any} type. The type
  10695. \code{Any} is consistent with every other type.
  10696. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10697. \begin{figure}[tbp]
  10698. \begin{lstlisting}
  10699. (define/public (consistent? t1 t2)
  10700. (match* (t1 t2)
  10701. [('Integer 'Integer) #t]
  10702. [('Boolean 'Boolean) #t]
  10703. [('Void 'Void) #t]
  10704. [('Any t2) #t]
  10705. [(t1 'Any) #t]
  10706. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10707. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10708. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10709. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10710. (consistent? rt1 rt2))]
  10711. [(other wise) #f]))
  10712. \end{lstlisting}
  10713. \caption{The consistency predicate on types.}
  10714. \label{fig:consistent}
  10715. \end{figure}
  10716. Returning to the \code{map-vec} example of
  10717. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10718. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10719. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10720. because the two types are consistent. In particular, \code{->} is
  10721. equal to \code{->} and because \code{Any} is consistent with
  10722. \code{Integer}.
  10723. Next consider a program with an error, such as applying the
  10724. \code{map-vec} to a function that sometimes returns a Boolean, as
  10725. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10726. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10727. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10728. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10729. Integer)}. One might say that a gradual type checker is optimistic
  10730. in that it accepts programs that might execute without a runtime type
  10731. error.
  10732. %
  10733. Unfortunately, running this program with input \code{1} triggers an
  10734. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10735. performs checking at runtime to ensure the integrity of the static
  10736. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10737. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10738. new \code{Cast} form that is inserted by the type checker. Thus, the
  10739. output of the type checker is a program in the \LangCast{} language, which
  10740. adds \code{Cast} to \LangLoop{}, as shown in
  10741. Figure~\ref{fig:Rgrad-prime-syntax}.
  10742. \begin{figure}[tp]
  10743. \centering
  10744. \fbox{
  10745. \begin{minipage}{0.96\textwidth}
  10746. \small
  10747. \[
  10748. \begin{array}{lcl}
  10749. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10750. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10751. \end{array}
  10752. \]
  10753. \end{minipage}
  10754. }
  10755. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10756. \label{fig:Rgrad-prime-syntax}
  10757. \end{figure}
  10758. \begin{figure}[tbp]
  10759. \begin{lstlisting}
  10760. (define (map-vec [f : (Integer -> Integer)]
  10761. [v : (Vector Integer Integer)])
  10762. : (Vector Integer Integer)
  10763. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10764. (define (add1 x) (+ x 1))
  10765. (define (true) #t)
  10766. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10767. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10768. \end{lstlisting}
  10769. \caption{A variant of the \code{map-vec} example with an error.}
  10770. \label{fig:map-vec-maybe-add1}
  10771. \end{figure}
  10772. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10773. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10774. inserted every time the type checker sees two types that are
  10775. consistent but not equal. In the \code{add1} function, \code{x} is
  10776. cast to \code{Integer} and the result of the \code{+} is cast to
  10777. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10778. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10779. \begin{figure}[btp]
  10780. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10781. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10782. : (Vector Integer Integer)
  10783. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10784. (define (add1 [x : Any]) : Any
  10785. (cast (+ (cast x Any Integer) 1) Integer Any))
  10786. (define (true) : Any (cast #t Boolean Any))
  10787. (define (maybe-add1 [x : Any]) : Any
  10788. (if (eq? 0 (read)) (add1 x) (true)))
  10789. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10790. (vector 0 41)) 0)
  10791. \end{lstlisting}
  10792. \caption{Output of type checking \code{map-vec}
  10793. and \code{maybe-add1}.}
  10794. \label{fig:map-vec-cast}
  10795. \end{figure}
  10796. The type checker for \LangGrad{} is defined in
  10797. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10798. and \ref{fig:type-check-Rgradual-3}.
  10799. \begin{figure}[tbp]
  10800. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10801. (define type-check-gradual-class
  10802. (class type-check-Rwhile-class
  10803. (super-new)
  10804. (inherit operator-types type-predicates)
  10805. (define/override (type-check-exp env)
  10806. (lambda (e)
  10807. (define recur (type-check-exp env))
  10808. (match e
  10809. [(Prim 'vector-length (list e1))
  10810. (define-values (e1^ t) (recur e1))
  10811. (match t
  10812. [`(Vector ,ts ...)
  10813. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10814. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10815. [(Prim 'vector-ref (list e1 e2))
  10816. (define-values (e1^ t1) (recur e1))
  10817. (define-values (e2^ t2) (recur e2))
  10818. (check-consistent? t2 'Integer e)
  10819. (match t1
  10820. [`(Vector ,ts ...)
  10821. (match e2^
  10822. [(Int i)
  10823. (unless (and (0 . <= . i) (i . < . (length ts)))
  10824. (error 'type-check "invalid index ~a in ~a" i e))
  10825. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10826. [else (define e1^^ (make-cast e1^ t1 'Any))
  10827. (define e2^^ (make-cast e2^ t2 'Integer))
  10828. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10829. ['Any
  10830. (define e2^^ (make-cast e2^ t2 'Integer))
  10831. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10832. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10833. [(Prim 'vector-set! (list e1 e2 e3) )
  10834. (define-values (e1^ t1) (recur e1))
  10835. (define-values (e2^ t2) (recur e2))
  10836. (define-values (e3^ t3) (recur e3))
  10837. (check-consistent? t2 'Integer e)
  10838. (match t1
  10839. [`(Vector ,ts ...)
  10840. (match e2^
  10841. [(Int i)
  10842. (unless (and (0 . <= . i) (i . < . (length ts)))
  10843. (error 'type-check "invalid index ~a in ~a" i e))
  10844. (check-consistent? (list-ref ts i) t3 e)
  10845. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10846. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10847. [else
  10848. (define e1^^ (make-cast e1^ t1 'Any))
  10849. (define e2^^ (make-cast e2^ t2 'Integer))
  10850. (define e3^^ (make-cast e3^ t3 'Any))
  10851. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10852. ['Any
  10853. (define e2^^ (make-cast e2^ t2 'Integer))
  10854. (define e3^^ (make-cast e3^ t3 'Any))
  10855. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10856. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10857. \end{lstlisting}
  10858. \caption{Type checker for the \LangGrad{} language, part 1.}
  10859. \label{fig:type-check-Rgradual-1}
  10860. \end{figure}
  10861. \begin{figure}[tbp]
  10862. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10863. [(Prim 'eq? (list e1 e2))
  10864. (define-values (e1^ t1) (recur e1))
  10865. (define-values (e2^ t2) (recur e2))
  10866. (check-consistent? t1 t2 e)
  10867. (define T (meet t1 t2))
  10868. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10869. 'Boolean)]
  10870. [(Prim 'not (list e1))
  10871. (define-values (e1^ t1) (recur e1))
  10872. (match t1
  10873. ['Any
  10874. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10875. (Bool #t) (Bool #f)))]
  10876. [else
  10877. (define-values (t-ret new-es^)
  10878. (type-check-op 'not (list t1) (list e1^) e))
  10879. (values (Prim 'not new-es^) t-ret)])]
  10880. [(Prim 'and (list e1 e2))
  10881. (recur (If e1 e2 (Bool #f)))]
  10882. [(Prim 'or (list e1 e2))
  10883. (define tmp (gensym 'tmp))
  10884. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10885. [(Prim op es)
  10886. #:when (not (set-member? explicit-prim-ops op))
  10887. (define-values (new-es ts)
  10888. (for/lists (exprs types) ([e es])
  10889. (recur e)))
  10890. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10891. (values (Prim op new-es^) t-ret)]
  10892. [(If e1 e2 e3)
  10893. (define-values (e1^ T1) (recur e1))
  10894. (define-values (e2^ T2) (recur e2))
  10895. (define-values (e3^ T3) (recur e3))
  10896. (check-consistent? T2 T3 e)
  10897. (match T1
  10898. ['Boolean
  10899. (define Tif (join T2 T3))
  10900. (values (If e1^ (make-cast e2^ T2 Tif)
  10901. (make-cast e3^ T3 Tif)) Tif)]
  10902. ['Any
  10903. (define Tif (meet T2 T3))
  10904. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10905. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10906. Tif)]
  10907. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10908. [(HasType e1 T)
  10909. (define-values (e1^ T1) (recur e1))
  10910. (check-consistent? T1 T)
  10911. (values (make-cast e1^ T1 T) T)]
  10912. [(SetBang x e1)
  10913. (define-values (e1^ T1) (recur e1))
  10914. (define varT (dict-ref env x))
  10915. (check-consistent? T1 varT e)
  10916. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10917. [(WhileLoop e1 e2)
  10918. (define-values (e1^ T1) (recur e1))
  10919. (check-consistent? T1 'Boolean e)
  10920. (define-values (e2^ T2) ((type-check-exp env) e2))
  10921. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10922. \end{lstlisting}
  10923. \caption{Type checker for the \LangGrad{} language, part 2.}
  10924. \label{fig:type-check-Rgradual-2}
  10925. \end{figure}
  10926. \begin{figure}[tbp]
  10927. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10928. [(Apply e1 e2s)
  10929. (define-values (e1^ T1) (recur e1))
  10930. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10931. (match T1
  10932. [`(,T1ps ... -> ,T1rt)
  10933. (for ([T2 T2s] [Tp T1ps])
  10934. (check-consistent? T2 Tp e))
  10935. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10936. (make-cast e2 src tgt)))
  10937. (values (Apply e1^ e2s^^) T1rt)]
  10938. [`Any
  10939. (define e1^^ (make-cast e1^ 'Any
  10940. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10941. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10942. (make-cast e2 src 'Any)))
  10943. (values (Apply e1^^ e2s^^) 'Any)]
  10944. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10945. [(Lambda params Tr e1)
  10946. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10947. (match p
  10948. [`[,x : ,T] (values x T)]
  10949. [(? symbol? x) (values x 'Any)])))
  10950. (define-values (e1^ T1)
  10951. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10952. (check-consistent? Tr T1 e)
  10953. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10954. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10955. [else ((super type-check-exp env) e)]
  10956. )))
  10957. \end{lstlisting}
  10958. \caption{Type checker for the \LangGrad{} language, part 3.}
  10959. \label{fig:type-check-Rgradual-3}
  10960. \end{figure}
  10961. \begin{figure}[tbp]
  10962. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10963. (define/public (join t1 t2)
  10964. (match* (t1 t2)
  10965. [('Integer 'Integer) 'Integer]
  10966. [('Boolean 'Boolean) 'Boolean]
  10967. [('Void 'Void) 'Void]
  10968. [('Any t2) t2]
  10969. [(t1 'Any) t1]
  10970. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10971. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  10972. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10973. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  10974. -> ,(join rt1 rt2))]))
  10975. (define/public (meet t1 t2)
  10976. (match* (t1 t2)
  10977. [('Integer 'Integer) 'Integer]
  10978. [('Boolean 'Boolean) 'Boolean]
  10979. [('Void 'Void) 'Void]
  10980. [('Any t2) 'Any]
  10981. [(t1 'Any) 'Any]
  10982. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10983. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  10984. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10985. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  10986. -> ,(meet rt1 rt2))]))
  10987. (define/public (make-cast e src tgt)
  10988. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  10989. (define/public (check-consistent? t1 t2 e)
  10990. (unless (consistent? t1 t2)
  10991. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  10992. (define/override (type-check-op op arg-types args e)
  10993. (match (dict-ref (operator-types) op)
  10994. [`(,param-types . ,return-type)
  10995. (for ([at arg-types] [pt param-types])
  10996. (check-consistent? at pt e))
  10997. (values return-type
  10998. (for/list ([e args] [s arg-types] [t param-types])
  10999. (make-cast e s t)))]
  11000. [else (error 'type-check-op "unrecognized ~a" op)]))
  11001. (define explicit-prim-ops
  11002. (set-union
  11003. (type-predicates)
  11004. (set 'procedure-arity 'eq?
  11005. 'vector 'vector-length 'vector-ref 'vector-set!
  11006. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11007. (define/override (fun-def-type d)
  11008. (match d
  11009. [(Def f params rt info body)
  11010. (define ps
  11011. (for/list ([p params])
  11012. (match p
  11013. [`[,x : ,T] T]
  11014. [(? symbol?) 'Any]
  11015. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11016. `(,@ps -> ,rt)]
  11017. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11018. \end{lstlisting}
  11019. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11020. \label{fig:type-check-Rgradual-aux}
  11021. \end{figure}
  11022. \clearpage
  11023. \section{Interpreting \LangCast{}}
  11024. \label{sec:interp-casts}
  11025. The runtime behavior of first-order casts is straightforward, that is,
  11026. casts involving simple types such as \code{Integer} and
  11027. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11028. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11029. puts the integer into a tagged value
  11030. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11031. \code{Integer} is accomplished with the \code{Project} operator, that
  11032. is, by checking the value's tag and either retrieving the underlying
  11033. integer or signaling an error if it the tag is not the one for
  11034. integers (Figure~\ref{fig:apply-project}).
  11035. %
  11036. Things get more interesting for higher-order casts, that is, casts
  11037. involving function or vector types.
  11038. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11039. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11040. this cast at runtime, we can't know in general whether the function
  11041. will always return an integer.\footnote{Predicting the return value of
  11042. a function is equivalent to the halting problem, which is
  11043. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11044. of the cast until the function is applied. This is accomplished by
  11045. wrapping \code{maybe-add1} in a new function that casts its parameter
  11046. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11047. casts the return value from \code{Any} to \code{Integer}.
  11048. Turning our attention to casts involving vector types, we consider the
  11049. example in Figure~\ref{fig:map-vec-bang} that defines a
  11050. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11051. type \code{(Vector Any Any)} and that updates \code{v} in place
  11052. instead of returning a new vector. So we name this function
  11053. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11054. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11055. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11056. cast between vector types would be a build a new vector whose elements
  11057. are the result of casting each of the original elements to the
  11058. appropriate target type. However, this approach is only valid for
  11059. immutable vectors; and our vectors are mutable. In the example of
  11060. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11061. the updates inside of \code{map-vec!} would happen to the new vector
  11062. and not the original one.
  11063. \begin{figure}[tbp]
  11064. % gradual_test_11.rkt
  11065. \begin{lstlisting}
  11066. (define (map-vec! [f : (Any -> Any)]
  11067. [v : (Vector Any Any)]) : Void
  11068. (begin
  11069. (vector-set! v 0 (f (vector-ref v 0)))
  11070. (vector-set! v 1 (f (vector-ref v 1)))))
  11071. (define (add1 x) (+ x 1))
  11072. (let ([v (vector 0 41)])
  11073. (begin (map-vec! add1 v) (vector-ref v 1)))
  11074. \end{lstlisting}
  11075. \caption{An example involving casts on vectors.}
  11076. \label{fig:map-vec-bang}
  11077. \end{figure}
  11078. Instead the interpreter needs to create a new kind of value, a
  11079. \emph{vector proxy}, that intercepts every vector operation. On a
  11080. read, the proxy reads from the underlying vector and then applies a
  11081. cast to the resulting value. On a write, the proxy casts the argument
  11082. value and then performs the write to the underlying vector. For the
  11083. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11084. \code{0} from \code{Integer} to \code{Any}. For the first
  11085. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11086. to \code{Integer}.
  11087. The final category of cast that we need to consider are casts between
  11088. the \code{Any} type and either a function or a vector
  11089. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11090. in which parameter \code{v} does not have a type annotation, so it is
  11091. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11092. type \code{(Vector Integer Integer)} so the type checker inserts a
  11093. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11094. thought is to use \code{Inject}, but that doesn't work because
  11095. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11096. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11097. to \code{Any}.
  11098. \begin{figure}[tbp]
  11099. \begin{lstlisting}
  11100. (define (map-vec! [f : (Any -> Any)] v) : Void
  11101. (begin
  11102. (vector-set! v 0 (f (vector-ref v 0)))
  11103. (vector-set! v 1 (f (vector-ref v 1)))))
  11104. (define (add1 x) (+ x 1))
  11105. (let ([v (vector 0 41)])
  11106. (begin (map-vec! add1 v) (vector-ref v 1)))
  11107. \end{lstlisting}
  11108. \caption{Casting a vector to \code{Any}.}
  11109. \label{fig:map-vec-any}
  11110. \end{figure}
  11111. The \LangCast{} interpreter uses an auxiliary function named
  11112. \code{apply-cast} to cast a value from a source type to a target type,
  11113. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11114. of the kinds of casts that we've discussed in this section.
  11115. \begin{figure}[tbp]
  11116. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11117. (define/public (apply-cast v s t)
  11118. (match* (s t)
  11119. [(t1 t2) #:when (equal? t1 t2) v]
  11120. [('Any t2)
  11121. (match t2
  11122. [`(,ts ... -> ,rt)
  11123. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11124. (define v^ (apply-project v any->any))
  11125. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11126. [`(Vector ,ts ...)
  11127. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11128. (define v^ (apply-project v vec-any))
  11129. (apply-cast v^ vec-any `(Vector ,@ts))]
  11130. [else (apply-project v t2)])]
  11131. [(t1 'Any)
  11132. (match t1
  11133. [`(,ts ... -> ,rt)
  11134. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11135. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11136. (apply-inject v^ (any-tag any->any))]
  11137. [`(Vector ,ts ...)
  11138. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11139. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11140. (apply-inject v^ (any-tag vec-any))]
  11141. [else (apply-inject v (any-tag t1))])]
  11142. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11143. (define x (gensym 'x))
  11144. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11145. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11146. (define cast-writes
  11147. (for/list ([t1 ts1] [t2 ts2])
  11148. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11149. `(vector-proxy ,(vector v (apply vector cast-reads)
  11150. (apply vector cast-writes)))]
  11151. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11152. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11153. `(function ,xs ,(Cast
  11154. (Apply (Value v)
  11155. (for/list ([x xs][t1 ts1][t2 ts2])
  11156. (Cast (Var x) t2 t1)))
  11157. rt1 rt2) ())]
  11158. ))
  11159. \end{lstlisting}
  11160. \caption{The \code{apply-cast} auxiliary method.}
  11161. \label{fig:apply-cast}
  11162. \end{figure}
  11163. The interpreter for \LangCast{} is defined in
  11164. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11165. dispatching to \code{apply-cast}. To handle the addition of vector
  11166. proxies, we update the vector primitives in \code{interp-op} using the
  11167. functions in Figure~\ref{fig:guarded-vector}.
  11168. \begin{figure}[tbp]
  11169. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11170. (define interp-Rcast-class
  11171. (class interp-Rwhile-class
  11172. (super-new)
  11173. (inherit apply-fun apply-inject apply-project)
  11174. (define/override (interp-op op)
  11175. (match op
  11176. ['vector-length guarded-vector-length]
  11177. ['vector-ref guarded-vector-ref]
  11178. ['vector-set! guarded-vector-set!]
  11179. ['any-vector-ref (lambda (v i)
  11180. (match v [`(tagged ,v^ ,tg)
  11181. (guarded-vector-ref v^ i)]))]
  11182. ['any-vector-set! (lambda (v i a)
  11183. (match v [`(tagged ,v^ ,tg)
  11184. (guarded-vector-set! v^ i a)]))]
  11185. ['any-vector-length (lambda (v)
  11186. (match v [`(tagged ,v^ ,tg)
  11187. (guarded-vector-length v^)]))]
  11188. [else (super interp-op op)]
  11189. ))
  11190. (define/override ((interp-exp env) e)
  11191. (define (recur e) ((interp-exp env) e))
  11192. (match e
  11193. [(Value v) v]
  11194. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11195. [else ((super interp-exp env) e)]))
  11196. ))
  11197. (define (interp-Rcast p)
  11198. (send (new interp-Rcast-class) interp-program p))
  11199. \end{lstlisting}
  11200. \caption{The interpreter for \LangCast{}.}
  11201. \label{fig:interp-Rcast}
  11202. \end{figure}
  11203. \begin{figure}[tbp]
  11204. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11205. (define (guarded-vector-ref vec i)
  11206. (match vec
  11207. [`(vector-proxy ,proxy)
  11208. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11209. (define rd (vector-ref (vector-ref proxy 1) i))
  11210. (apply-fun rd (list val) 'guarded-vector-ref)]
  11211. [else (vector-ref vec i)]))
  11212. (define (guarded-vector-set! vec i arg)
  11213. (match vec
  11214. [`(vector-proxy ,proxy)
  11215. (define wr (vector-ref (vector-ref proxy 2) i))
  11216. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11217. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11218. [else (vector-set! vec i arg)]))
  11219. (define (guarded-vector-length vec)
  11220. (match vec
  11221. [`(vector-proxy ,proxy)
  11222. (guarded-vector-length (vector-ref proxy 0))]
  11223. [else (vector-length vec)]))
  11224. \end{lstlisting}
  11225. \caption{The guarded-vector auxiliary functions.}
  11226. \label{fig:guarded-vector}
  11227. \end{figure}
  11228. \section{Lower Casts}
  11229. \label{sec:lower-casts}
  11230. The next step in the journey towards x86 is the \code{lower-casts}
  11231. pass that translates the casts in \LangCast{} to the lower-level
  11232. \code{Inject} and \code{Project} operators and a new operator for
  11233. creating vector proxies, extending the \LangLoop{} language to create
  11234. \LangProxy{}. We recommend creating an auxiliary function named
  11235. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11236. and a target type, and translates it to expression in \LangProxy{} that has
  11237. the same behavior as casting the expression from the source to the
  11238. target type in the interpreter.
  11239. The \code{lower-cast} function can follow a code structure similar to
  11240. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11241. the interpreter for \LangCast{} because it must handle the same cases as
  11242. \code{apply-cast} and it needs to mimic the behavior of
  11243. \code{apply-cast}. The most interesting cases are those concerning the
  11244. casts between two vector types and between two function types.
  11245. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11246. type to another vector type is accomplished by creating a proxy that
  11247. intercepts the operations on the underlying vector. Here we make the
  11248. creation of the proxy explicit with the \code{vector-proxy} primitive
  11249. operation. It takes three arguments, the first is an expression for
  11250. the vector, the second is a vector of functions for casting an element
  11251. that is being read from the vector, and the third is a vector of
  11252. functions for casting an element that is being written to the vector.
  11253. You can create the functions using \code{Lambda}. Also, as we shall
  11254. see in the next section, we need to differentiate these vectors from
  11255. the user-created ones, so we recommend using a new primitive operator
  11256. named \code{raw-vector} instead of \code{vector} to create these
  11257. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11258. the output of \code{lower-casts} on the example in
  11259. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11260. integers to a vector of \code{Any}.
  11261. \begin{figure}[tbp]
  11262. \begin{lstlisting}
  11263. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11264. (begin
  11265. (vector-set! v 0 (f (vector-ref v 0)))
  11266. (vector-set! v 1 (f (vector-ref v 1)))))
  11267. (define (add1 [x : Any]) : Any
  11268. (inject (+ (project x Integer) 1) Integer))
  11269. (let ([v (vector 0 41)])
  11270. (begin
  11271. (map-vec! add1 (vector-proxy v
  11272. (raw-vector (lambda: ([x9 : Integer]) : Any
  11273. (inject x9 Integer))
  11274. (lambda: ([x9 : Integer]) : Any
  11275. (inject x9 Integer)))
  11276. (raw-vector (lambda: ([x9 : Any]) : Integer
  11277. (project x9 Integer))
  11278. (lambda: ([x9 : Any]) : Integer
  11279. (project x9 Integer)))))
  11280. (vector-ref v 1)))
  11281. \end{lstlisting}
  11282. \caption{Output of \code{lower-casts} on the example in
  11283. Figure~\ref{fig:map-vec-bang}.}
  11284. \label{fig:map-vec-bang-lower-cast}
  11285. \end{figure}
  11286. A cast from one function type to another function type is accomplished
  11287. by generating a \code{Lambda} whose parameter and return types match
  11288. the target function type. The body of the \code{Lambda} should cast
  11289. the parameters from the target type to the source type (yes,
  11290. backwards! functions are contravariant\index{subject}{contravariant} in the
  11291. parameters), then call the underlying function, and finally cast the
  11292. result from the source return type to the target return type.
  11293. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11294. \code{lower-casts} pass on the \code{map-vec} example in
  11295. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11296. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11297. \begin{figure}[tbp]
  11298. \begin{lstlisting}
  11299. (define (map-vec [f : (Integer -> Integer)]
  11300. [v : (Vector Integer Integer)])
  11301. : (Vector Integer Integer)
  11302. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11303. (define (add1 [x : Any]) : Any
  11304. (inject (+ (project x Integer) 1) Integer))
  11305. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11306. (project (add1 (inject x9 Integer)) Integer))
  11307. (vector 0 41)) 1)
  11308. \end{lstlisting}
  11309. \caption{Output of \code{lower-casts} on the example in
  11310. Figure~\ref{fig:gradual-map-vec}.}
  11311. \label{fig:map-vec-lower-cast}
  11312. \end{figure}
  11313. \section{Differentiate Proxies}
  11314. \label{sec:differentiate-proxies}
  11315. So far the job of differentiating vectors and vector proxies has been
  11316. the job of the interpreter. For example, the interpreter for \LangCast{}
  11317. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11318. function in Figure~\ref{fig:guarded-vector}. In the
  11319. \code{differentiate-proxies} pass we shift this responsibility to the
  11320. generated code.
  11321. We begin by designing the output language $R^p_8$. In
  11322. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11323. proxies. In $R^p_8$ we return the \code{Vector} type to
  11324. its original meaning, as the type of real vectors, and we introduce a
  11325. new type, \code{PVector}, whose values can be either real vectors or
  11326. vector proxies. This new type comes with a suite of new primitive
  11327. operations for creating and using values of type \code{PVector}. We
  11328. don't need to introduce a new type to represent vector proxies. A
  11329. proxy is represented by a vector containing three things: 1) the
  11330. underlying vector, 2) a vector of functions for casting elements that
  11331. are read from the vector, and 3) a vector of functions for casting
  11332. values to be written to the vector. So we define the following
  11333. abbreviation for the type of a vector proxy:
  11334. \[
  11335. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  11336. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  11337. \to (\key{PVector}~ T' \ldots)
  11338. \]
  11339. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  11340. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  11341. %
  11342. Next we describe each of the new primitive operations.
  11343. \begin{description}
  11344. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  11345. (\key{PVector} $T \ldots$)]\ \\
  11346. %
  11347. This operation brands a vector as a value of the \code{PVector} type.
  11348. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  11349. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  11350. %
  11351. This operation brands a vector proxy as value of the \code{PVector} type.
  11352. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  11353. \code{Boolean}] \ \\
  11354. %
  11355. returns true if the value is a vector proxy and false if it is a
  11356. real vector.
  11357. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  11358. (\key{Vector} $T \ldots$)]\ \\
  11359. %
  11360. Assuming that the input is a vector (and not a proxy), this
  11361. operation returns the vector.
  11362. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  11363. $\to$ \code{Boolean}]\ \\
  11364. %
  11365. Given a vector proxy, this operation returns the length of the
  11366. underlying vector.
  11367. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  11368. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  11369. %
  11370. Given a vector proxy, this operation returns the $i$th element of
  11371. the underlying vector.
  11372. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  11373. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  11374. proxy, this operation writes a value to the $i$th element of the
  11375. underlying vector.
  11376. \end{description}
  11377. Now to discuss the translation that differentiates vectors from
  11378. proxies. First, every type annotation in the program must be
  11379. translated (recursively) to replace \code{Vector} with \code{PVector}.
  11380. Next, we must insert uses of \code{PVector} operations in the
  11381. appropriate places. For example, we wrap every vector creation with an
  11382. \code{inject-vector}.
  11383. \begin{lstlisting}
  11384. (vector |$e_1 \ldots e_n$|)
  11385. |$\Rightarrow$|
  11386. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  11387. \end{lstlisting}
  11388. The \code{raw-vector} operator that we introduced in the previous
  11389. section does not get injected.
  11390. \begin{lstlisting}
  11391. (raw-vector |$e_1 \ldots e_n$|)
  11392. |$\Rightarrow$|
  11393. (vector |$e'_1 \ldots e'_n$|)
  11394. \end{lstlisting}
  11395. The \code{vector-proxy} primitive translates as follows.
  11396. \begin{lstlisting}
  11397. (vector-proxy |$e_1~e_2~e_3$|)
  11398. |$\Rightarrow$|
  11399. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  11400. \end{lstlisting}
  11401. We translate the vector operations into conditional expressions that
  11402. check whether the value is a proxy and then dispatch to either the
  11403. appropriate proxy vector operation or the regular vector operation.
  11404. For example, the following is the translation for \code{vector-ref}.
  11405. \begin{lstlisting}
  11406. (vector-ref |$e_1$| |$i$|)
  11407. |$\Rightarrow$|
  11408. (let ([|$v~e_1$|])
  11409. (if (proxy? |$v$|)
  11410. (proxy-vector-ref |$v$| |$i$|)
  11411. (vector-ref (project-vector |$v$|) |$i$|)
  11412. \end{lstlisting}
  11413. Note in the case of a real vector, we must apply \code{project-vector}
  11414. before the \code{vector-ref}.
  11415. \section{Reveal Casts}
  11416. \label{sec:reveal-casts-gradual}
  11417. Recall that the \code{reveal-casts} pass
  11418. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  11419. \code{Inject} and \code{Project} into lower-level operations. In
  11420. particular, \code{Project} turns into a conditional expression that
  11421. inspects the tag and retrieves the underlying value. Here we need to
  11422. augment the translation of \code{Project} to handle the situation when
  11423. the target type is \code{PVector}. Instead of using
  11424. \code{vector-length} we need to use \code{proxy-vector-length}.
  11425. \begin{lstlisting}
  11426. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11427. |$\Rightarrow$|
  11428. (let |$\itm{tmp}$| |$e'$|
  11429. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11430. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11431. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11432. (exit)))
  11433. \end{lstlisting}
  11434. \section{Closure Conversion}
  11435. \label{sec:closure-conversion-gradual}
  11436. The closure conversion pass only requires one minor adjustment. The
  11437. auxiliary function that translates type annotations needs to be
  11438. updated to handle the \code{PVector} type.
  11439. \section{Explicate Control}
  11440. \label{sec:explicate-control-gradual}
  11441. Update the \code{explicate-control} pass to handle the new primitive
  11442. operations on the \code{PVector} type.
  11443. \section{Select Instructions}
  11444. \label{sec:select-instructions-gradual}
  11445. Recall that the \code{select-instructions} pass is responsible for
  11446. lowering the primitive operations into x86 instructions. So we need
  11447. to translate the new \code{PVector} operations to x86. To do so, the
  11448. first question we need to answer is how will we differentiate the two
  11449. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11450. We need just one bit to accomplish this, and use the bit in position
  11451. $57$ of the 64-bit tag at the front of every vector (see
  11452. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11453. for \code{inject-vector} we leave it that way.
  11454. \begin{lstlisting}
  11455. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11456. |$\Rightarrow$|
  11457. movq |$e'_1$|, |$\itm{lhs'}$|
  11458. \end{lstlisting}
  11459. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  11460. \begin{lstlisting}
  11461. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11462. |$\Rightarrow$|
  11463. movq |$e'_1$|, %r11
  11464. movq |$(1 << 57)$|, %rax
  11465. orq 0(%r11), %rax
  11466. movq %rax, 0(%r11)
  11467. movq %r11, |$\itm{lhs'}$|
  11468. \end{lstlisting}
  11469. The \code{proxy?} operation consumes the information so carefully
  11470. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11471. isolates the $57$th bit to tell whether the value is a real vector or
  11472. a proxy.
  11473. \begin{lstlisting}
  11474. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11475. |$\Rightarrow$|
  11476. movq |$e_1'$|, %r11
  11477. movq 0(%r11), %rax
  11478. sarq $57, %rax
  11479. andq $1, %rax
  11480. movq %rax, |$\itm{lhs'}$|
  11481. \end{lstlisting}
  11482. The \code{project-vector} operation is straightforward to translate,
  11483. so we leave it up to the reader.
  11484. Regarding the \code{proxy-vector} operations, the runtime provides
  11485. procedures that implement them (they are recursive functions!) so
  11486. here we simply need to translate these vector operations into the
  11487. appropriate function call. For example, here is the translation for
  11488. \code{proxy-vector-ref}.
  11489. \begin{lstlisting}
  11490. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11491. |$\Rightarrow$|
  11492. movq |$e_1'$|, %rdi
  11493. movq |$e_2'$|, %rsi
  11494. callq proxy_vector_ref
  11495. movq %rax, |$\itm{lhs'}$|
  11496. \end{lstlisting}
  11497. We have another batch of vector operations to deal with, those for the
  11498. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11499. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11500. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11501. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11502. Section~\ref{sec:select-Rany} we selected instructions for these
  11503. operations based on the idea that the underlying value was a real
  11504. vector. But in the current setting, the underlying value is of type
  11505. \code{PVector}. So \code{any-vector-ref} can be translates to
  11506. pseudo-x86 as follows. We begin by projecting the underlying value out
  11507. of the tagged value and then call the \code{proxy\_vector\_ref}
  11508. procedure in the runtime.
  11509. \begin{lstlisting}
  11510. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11511. movq |$\neg 111$|, %rdi
  11512. andq |$e_1'$|, %rdi
  11513. movq |$e_2'$|, %rsi
  11514. callq proxy_vector_ref
  11515. movq %rax, |$\itm{lhs'}$|
  11516. \end{lstlisting}
  11517. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11518. be translated in a similar way.
  11519. \begin{exercise}\normalfont
  11520. Implement a compiler for the gradually-typed \LangGrad{} language by
  11521. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11522. partially-typed test programs. In addition to testing with these
  11523. new programs, also test your compiler on all the tests for \LangLoop{}
  11524. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11525. on the \LangDyn{} programs but you can adapt them by inserting
  11526. a cast to the \code{Any} type around each subexpression
  11527. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11528. you can induce one by wrapping the subexpression \code{e}
  11529. with a call to an un-annotated identity function, like this:
  11530. \code{((lambda (x) x) e)}.
  11531. \end{exercise}
  11532. \begin{figure}[p]
  11533. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11534. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11535. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11536. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11537. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11538. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11539. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11540. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11541. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11542. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11543. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11544. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11545. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11546. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11547. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11548. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11549. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11550. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11551. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11552. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11553. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11554. \path[->,bend right=15] (Rgradual) edge [above] node
  11555. {\ttfamily\footnotesize type-check} (Rgradualp);
  11556. \path[->,bend right=15] (Rgradualp) edge [above] node
  11557. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11558. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11559. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11560. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11561. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11562. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11563. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11564. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11565. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11566. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11567. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11568. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11569. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11570. \path[->,bend left=15] (F1-1) edge [below] node
  11571. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11572. \path[->,bend right=15] (F1-2) edge [above] node
  11573. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11574. \path[->,bend right=15] (F1-3) edge [above] node
  11575. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11576. \path[->,bend right=15] (F1-4) edge [above] node
  11577. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11578. \path[->,bend right=15] (F1-5) edge [right] node
  11579. {\ttfamily\footnotesize explicate-control} (C3-2);
  11580. \path[->,bend left=15] (C3-2) edge [left] node
  11581. {\ttfamily\footnotesize select-instr.} (x86-2);
  11582. \path[->,bend right=15] (x86-2) edge [left] node
  11583. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11584. \path[->,bend right=15] (x86-2-1) edge [below] node
  11585. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11586. \path[->,bend right=15] (x86-2-2) edge [left] node
  11587. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11588. \path[->,bend left=15] (x86-3) edge [above] node
  11589. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11590. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11591. \end{tikzpicture}
  11592. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11593. \label{fig:Rgradual-passes}
  11594. \end{figure}
  11595. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11596. for the compilation of \LangGrad{}.
  11597. \section{Further Reading}
  11598. This chapter just scratches the surface of gradual typing. The basic
  11599. approach described here is missing two key ingredients that one would
  11600. want in a implementation of gradual typing: blame
  11601. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11602. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11603. problem addressed by blame tracking is that when a cast on a
  11604. higher-order value fails, it often does so at a point in the program
  11605. that is far removed from the original cast. Blame tracking is a
  11606. technique for propagating extra information through casts and proxies
  11607. so that when a cast fails, the error message can point back to the
  11608. original location of the cast in the source program.
  11609. The problem addressed by space-efficient casts also relates to
  11610. higher-order casts. It turns out that in partially typed programs, a
  11611. function or vector can flow through very-many casts at runtime. With
  11612. the approach described in this chapter, each cast adds another
  11613. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11614. considerable space, but it also makes the function calls and vector
  11615. operations slow. For example, a partially-typed version of quicksort
  11616. could, in the worst case, build a chain of proxies of length $O(n)$
  11617. around the vector, changing the overall time complexity of the
  11618. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11619. solution to this problem by representing casts using the coercion
  11620. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11621. long chains of proxies by compressing them into a concise normal
  11622. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11623. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11624. the Grift compiler.
  11625. \begin{center}
  11626. \url{https://github.com/Gradual-Typing/Grift}
  11627. \end{center}
  11628. There are also interesting interactions between gradual typing and
  11629. other language features, such as parametetric polymorphism,
  11630. information-flow types, and type inference, to name a few. We
  11631. recommend the reader to the online gradual typing bibliography:
  11632. \begin{center}
  11633. \url{http://samth.github.io/gradual-typing-bib/}
  11634. \end{center}
  11635. % TODO: challenge problem:
  11636. % type analysis and type specialization?
  11637. % coercions?
  11638. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11639. \chapter{Parametric Polymorphism}
  11640. \label{ch:Rpoly}
  11641. \index{subject}{parametric polymorphism}
  11642. \index{subject}{generics}
  11643. This chapter studies the compilation of parametric
  11644. polymorphism\index{subject}{parametric polymorphism}
  11645. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  11646. Racket. Parametric polymorphism enables improved code reuse by
  11647. parameterizing functions and data structures with respect to the types
  11648. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11649. revisits the \code{map-vec} example but this time gives it a more
  11650. fitting type. This \code{map-vec} function is parameterized with
  11651. respect to the element type of the vector. The type of \code{map-vec}
  11652. is the following polymorphic type as specified by the \code{All} and
  11653. the type parameter \code{a}.
  11654. \begin{lstlisting}
  11655. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11656. \end{lstlisting}
  11657. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11658. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11659. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11660. \code{a}, but we could have just as well applied \code{map-vec} to a
  11661. vector of Booleans (and a function on Booleans).
  11662. \begin{figure}[tbp]
  11663. % poly_test_2.rkt
  11664. \begin{lstlisting}
  11665. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11666. (define (map-vec f v)
  11667. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11668. (define (add1 [x : Integer]) : Integer (+ x 1))
  11669. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11670. \end{lstlisting}
  11671. \caption{The \code{map-vec} example using parametric polymorphism.}
  11672. \label{fig:map-vec-poly}
  11673. \end{figure}
  11674. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  11675. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  11676. syntax. We add a second form for function definitions in which a type
  11677. declaration comes before the \code{define}. In the abstract syntax,
  11678. the return type in the \code{Def} is \code{Any}, but that should be
  11679. ignored in favor of the return type in the type declaration. (The
  11680. \code{Any} comes from using the same parser as in
  11681. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  11682. enables the use of an \code{All} type for a function, thereby making
  11683. it polymorphic. The grammar for types is extended to include
  11684. polymorphic types and type variables.
  11685. \begin{figure}[tp]
  11686. \centering
  11687. \fbox{
  11688. \begin{minipage}{0.96\textwidth}
  11689. \small
  11690. \[
  11691. \begin{array}{lcl}
  11692. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11693. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11694. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11695. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11696. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11697. \end{array}
  11698. \]
  11699. \end{minipage}
  11700. }
  11701. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11702. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11703. \label{fig:Rpoly-concrete-syntax}
  11704. \end{figure}
  11705. \begin{figure}[tp]
  11706. \centering
  11707. \fbox{
  11708. \begin{minipage}{0.96\textwidth}
  11709. \small
  11710. \[
  11711. \begin{array}{lcl}
  11712. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11713. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11714. &\mid& \DECL{\Var}{\Type} \\
  11715. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11716. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11717. \end{array}
  11718. \]
  11719. \end{minipage}
  11720. }
  11721. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11722. (Figure~\ref{fig:Rwhile-syntax}).}
  11723. \label{fig:Rpoly-syntax}
  11724. \end{figure}
  11725. By including polymorphic types in the $\Type$ non-terminal we choose
  11726. to make them first-class which has interesting repercussions on the
  11727. compiler. Many languages with polymorphism, such as
  11728. C++~\citep{stroustrup88:_param_types} and Standard
  11729. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11730. it is useful to see an example of first-class polymorphism. In
  11731. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11732. whose parameter is a polymorphic function. The occurrence of a
  11733. polymorphic type underneath a function type is enabled by the normal
  11734. recursive structure of the grammar for $\Type$ and the categorization
  11735. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11736. applies the polymorphic function to a Boolean and to an integer.
  11737. \begin{figure}[tbp]
  11738. \begin{lstlisting}
  11739. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11740. (define (apply-twice f)
  11741. (if (f #t) (f 42) (f 777)))
  11742. (: id (All (a) (a -> a)))
  11743. (define (id x) x)
  11744. (apply-twice id)
  11745. \end{lstlisting}
  11746. \caption{An example illustrating first-class polymorphism.}
  11747. \label{fig:apply-twice}
  11748. \end{figure}
  11749. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11750. three new responsibilities (compared to \LangLoop{}). The type checking of
  11751. function application is extended to handle the case where the operator
  11752. expression is a polymorphic function. In that case the type arguments
  11753. are deduced by matching the type of the parameters with the types of
  11754. the arguments.
  11755. %
  11756. The \code{match-types} auxiliary function carries out this deduction
  11757. by recursively descending through a parameter type \code{pt} and the
  11758. corresponding argument type \code{at}, making sure that they are equal
  11759. except when there is a type parameter on the left (in the parameter
  11760. type). If it's the first time that the type parameter has been
  11761. encountered, then the algorithm deduces an association of the type
  11762. parameter to the corresponding type on the right (in the argument
  11763. type). If it's not the first time that the type parameter has been
  11764. encountered, the algorithm looks up its deduced type and makes sure
  11765. that it is equal to the type on the right.
  11766. %
  11767. Once the type arguments are deduced, the operator expression is
  11768. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11769. type of the operator, but more importantly, records the deduced type
  11770. arguments. The return type of the application is the return type of
  11771. the polymorphic function, but with the type parameters replaced by the
  11772. deduced type arguments, using the \code{subst-type} function.
  11773. The second responsibility of the type checker is extending the
  11774. function \code{type-equal?} to handle the \code{All} type. This is
  11775. not quite a simple as equal on other types, such as function and
  11776. vector types, because two polymorphic types can be syntactically
  11777. different even though they are equivalent types. For example,
  11778. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11779. Two polymorphic types should be considered equal if they differ only
  11780. in the choice of the names of the type parameters. The
  11781. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11782. renames the type parameters of the first type to match the type
  11783. parameters of the second type.
  11784. The third responsibility of the type checker is making sure that only
  11785. defined type variables appear in type annotations. The
  11786. \code{check-well-formed} function defined in
  11787. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11788. sure that each type variable has been defined.
  11789. The output language of the type checker is \LangInst{}, defined in
  11790. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  11791. declaration and polymorphic function into a single definition, using
  11792. the \code{Poly} form, to make polymorphic functions more convenient to
  11793. process in next pass of the compiler.
  11794. \begin{figure}[tp]
  11795. \centering
  11796. \fbox{
  11797. \begin{minipage}{0.96\textwidth}
  11798. \small
  11799. \[
  11800. \begin{array}{lcl}
  11801. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11802. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11803. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11804. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11805. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11806. \end{array}
  11807. \]
  11808. \end{minipage}
  11809. }
  11810. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11811. (Figure~\ref{fig:Rwhile-syntax}).}
  11812. \label{fig:Rpoly-prime-syntax}
  11813. \end{figure}
  11814. The output of the type checker on the polymorphic \code{map-vec}
  11815. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11816. \begin{figure}[tbp]
  11817. % poly_test_2.rkt
  11818. \begin{lstlisting}
  11819. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11820. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11821. (define (add1 [x : Integer]) : Integer (+ x 1))
  11822. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11823. (Integer))
  11824. add1 (vector 0 41)) 1)
  11825. \end{lstlisting}
  11826. \caption{Output of the type checker on the \code{map-vec} example.}
  11827. \label{fig:map-vec-type-check}
  11828. \end{figure}
  11829. \begin{figure}[tbp]
  11830. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11831. (define type-check-poly-class
  11832. (class type-check-Rwhile-class
  11833. (super-new)
  11834. (inherit check-type-equal?)
  11835. (define/override (type-check-apply env e1 es)
  11836. (define-values (e^ ty) ((type-check-exp env) e1))
  11837. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11838. ((type-check-exp env) e)))
  11839. (match ty
  11840. [`(,ty^* ... -> ,rt)
  11841. (for ([arg-ty ty*] [param-ty ty^*])
  11842. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11843. (values e^ es^ rt)]
  11844. [`(All ,xs (,tys ... -> ,rt))
  11845. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11846. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11847. (match-types env^^ param-ty arg-ty)))
  11848. (define targs
  11849. (for/list ([x xs])
  11850. (match (dict-ref env^^ x (lambda () #f))
  11851. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11852. x (Apply e1 es))]
  11853. [ty ty])))
  11854. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11855. [else (error 'type-check "expected a function, not ~a" ty)]))
  11856. (define/override ((type-check-exp env) e)
  11857. (match e
  11858. [(Lambda `([,xs : ,Ts] ...) rT body)
  11859. (for ([T Ts]) ((check-well-formed env) T))
  11860. ((check-well-formed env) rT)
  11861. ((super type-check-exp env) e)]
  11862. [(HasType e1 ty)
  11863. ((check-well-formed env) ty)
  11864. ((super type-check-exp env) e)]
  11865. [else ((super type-check-exp env) e)]))
  11866. (define/override ((type-check-def env) d)
  11867. (verbose 'type-check "poly/def" d)
  11868. (match d
  11869. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11870. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11871. (for ([p ps]) ((check-well-formed ts-env) p))
  11872. ((check-well-formed ts-env) rt)
  11873. (define new-env (append ts-env (map cons xs ps) env))
  11874. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11875. (check-type-equal? ty^ rt body)
  11876. (Generic ts (Def f p:t* rt info body^))]
  11877. [else ((super type-check-def env) d)]))
  11878. (define/override (type-check-program p)
  11879. (match p
  11880. [(Program info body)
  11881. (type-check-program (ProgramDefsExp info '() body))]
  11882. [(ProgramDefsExp info ds body)
  11883. (define ds^ (combine-decls-defs ds))
  11884. (define new-env (for/list ([d ds^])
  11885. (cons (def-name d) (fun-def-type d))))
  11886. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11887. (define-values (body^ ty) ((type-check-exp new-env) body))
  11888. (check-type-equal? ty 'Integer body)
  11889. (ProgramDefsExp info ds^^ body^)]))
  11890. ))
  11891. \end{lstlisting}
  11892. \caption{Type checker for the \LangPoly{} language.}
  11893. \label{fig:type-check-Rvar0}
  11894. \end{figure}
  11895. \begin{figure}[tbp]
  11896. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11897. (define/override (type-equal? t1 t2)
  11898. (match* (t1 t2)
  11899. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11900. (define env (map cons xs ys))
  11901. (type-equal? (subst-type env T1) T2)]
  11902. [(other wise)
  11903. (super type-equal? t1 t2)]))
  11904. (define/public (match-types env pt at)
  11905. (match* (pt at)
  11906. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11907. [('Void 'Void) env] [('Any 'Any) env]
  11908. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11909. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11910. (match-types env^ pt1 at1))]
  11911. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11912. (define env^ (match-types env prt art))
  11913. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11914. (match-types env^^ pt1 at1))]
  11915. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11916. (define env^ (append (map cons pxs axs) env))
  11917. (match-types env^ pt1 at1)]
  11918. [((? symbol? x) at)
  11919. (match (dict-ref env x (lambda () #f))
  11920. [#f (error 'type-check "undefined type variable ~a" x)]
  11921. ['Type (cons (cons x at) env)]
  11922. [t^ (check-type-equal? at t^ 'matching) env])]
  11923. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11924. (define/public (subst-type env pt)
  11925. (match pt
  11926. ['Integer 'Integer] ['Boolean 'Boolean]
  11927. ['Void 'Void] ['Any 'Any]
  11928. [`(Vector ,ts ...)
  11929. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11930. [`(,ts ... -> ,rt)
  11931. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11932. [`(All ,xs ,t)
  11933. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11934. [(? symbol? x) (dict-ref env x)]
  11935. [else (error 'type-check "expected a type not ~a" pt)]))
  11936. (define/public (combine-decls-defs ds)
  11937. (match ds
  11938. ['() '()]
  11939. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11940. (unless (equal? name f)
  11941. (error 'type-check "name mismatch, ~a != ~a" name f))
  11942. (match type
  11943. [`(All ,xs (,ps ... -> ,rt))
  11944. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11945. (cons (Generic xs (Def name params^ rt info body))
  11946. (combine-decls-defs ds^))]
  11947. [`(,ps ... -> ,rt)
  11948. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11949. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  11950. [else (error 'type-check "expected a function type, not ~a" type) ])]
  11951. [`(,(Def f params rt info body) . ,ds^)
  11952. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  11953. \end{lstlisting}
  11954. \caption{Auxiliary functions for type checking \LangPoly{}.}
  11955. \label{fig:type-check-Rvar0-aux}
  11956. \end{figure}
  11957. \begin{figure}[tbp]
  11958. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  11959. (define/public ((check-well-formed env) ty)
  11960. (match ty
  11961. ['Integer (void)]
  11962. ['Boolean (void)]
  11963. ['Void (void)]
  11964. [(? symbol? a)
  11965. (match (dict-ref env a (lambda () #f))
  11966. ['Type (void)]
  11967. [else (error 'type-check "undefined type variable ~a" a)])]
  11968. [`(Vector ,ts ...)
  11969. (for ([t ts]) ((check-well-formed env) t))]
  11970. [`(,ts ... -> ,t)
  11971. (for ([t ts]) ((check-well-formed env) t))
  11972. ((check-well-formed env) t)]
  11973. [`(All ,xs ,t)
  11974. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11975. ((check-well-formed env^) t)]
  11976. [else (error 'type-check "unrecognized type ~a" ty)]))
  11977. \end{lstlisting}
  11978. \caption{Well-formed types.}
  11979. \label{fig:well-formed-types}
  11980. \end{figure}
  11981. % TODO: interpreter for R'_10
  11982. \section{Compiling Polymorphism}
  11983. \label{sec:compiling-poly}
  11984. Broadly speaking, there are four approaches to compiling parametric
  11985. polymorphism, which we describe below.
  11986. \begin{description}
  11987. \item[Monomorphization] generates a different version of a polymorphic
  11988. function for each set of type arguments that it is used with,
  11989. producing type-specialized code. This approach results in the most
  11990. efficient code but requires whole-program compilation (no separate
  11991. compilation) and increases code size. For our current purposes
  11992. monomorphization is a non-starter because, with first-class
  11993. polymorphism, it is sometimes not possible to determine which
  11994. generic functions are used with which type arguments during
  11995. compilation. (It can be done at runtime, with just-in-time
  11996. compilation.) This approach is used to compile C++
  11997. templates~\citep{stroustrup88:_param_types} and polymorphic
  11998. functions in NESL~\citep{Blelloch:1993aa} and
  11999. ML~\citep{Weeks:2006aa}.
  12000. \item[Uniform representation] generates one version of each
  12001. polymorphic function but requires all values have a common ``boxed''
  12002. format, such as the tagged values of type \code{Any} in
  12003. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12004. similarly to code in a dynamically typed language (like \LangDyn{}),
  12005. in which primitive operators require their arguments to be projected
  12006. from \code{Any} and their results are injected into \code{Any}. (In
  12007. object-oriented languages, the projection is accomplished via
  12008. virtual method dispatch.) The uniform representation approach is
  12009. compatible with separate compilation and with first-class
  12010. polymorphism. However, it produces the least-efficient code because
  12011. it introduces overhead in the entire program, including
  12012. non-polymorphic code. This approach is used in implementations of
  12013. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12014. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12015. Java~\citep{Bracha:1998fk}.
  12016. \item[Mixed representation] generates one version of each polymorphic
  12017. function, using a boxed representation for type
  12018. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12019. and conversions are performed at the boundaries between monomorphic
  12020. and polymorphic (e.g. when a polymorphic function is instantiated
  12021. and called). This approach is compatible with separate compilation
  12022. and first-class polymorphism and maintains the efficiency of
  12023. monomorphic code. The tradeoff is increased overhead at the boundary
  12024. between monomorphic and polymorphic code. This approach is used in
  12025. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12026. Java 5 with the addition of autoboxing.
  12027. \item[Type passing] uses the unboxed representation in both
  12028. monomorphic and polymorphic code. Each polymorphic function is
  12029. compiled to a single function with extra parameters that describe
  12030. the type arguments. The type information is used by the generated
  12031. code to know how to access the unboxed values at runtime. This
  12032. approach is used in implementation of the Napier88
  12033. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12034. passing is compatible with separate compilation and first-class
  12035. polymorphism and maintains the efficiency for monomorphic
  12036. code. There is runtime overhead in polymorphic code from dispatching
  12037. on type information.
  12038. \end{description}
  12039. In this chapter we use the mixed representation approach, partly
  12040. because of its favorable attributes, and partly because it is
  12041. straightforward to implement using the tools that we have already
  12042. built to support gradual typing. To compile polymorphic functions, we
  12043. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12044. \LangCast{}.
  12045. \section{Erase Types}
  12046. \label{sec:erase-types}
  12047. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12048. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12049. shows the output of the \code{erase-types} pass on the polymorphic
  12050. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12051. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12052. \code{All} types are removed from the type of \code{map-vec}.
  12053. \begin{figure}[tbp]
  12054. \begin{lstlisting}
  12055. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12056. : (Vector Any Any)
  12057. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12058. (define (add1 [x : Integer]) : Integer (+ x 1))
  12059. (vector-ref ((cast map-vec
  12060. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12061. ((Integer -> Integer) (Vector Integer Integer)
  12062. -> (Vector Integer Integer)))
  12063. add1 (vector 0 41)) 1)
  12064. \end{lstlisting}
  12065. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12066. \label{fig:map-vec-erase}
  12067. \end{figure}
  12068. This process of type erasure creates a challenge at points of
  12069. instantiation. For example, consider the instantiation of
  12070. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12071. The type of \code{map-vec} is
  12072. \begin{lstlisting}
  12073. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12074. \end{lstlisting}
  12075. and it is instantiated to
  12076. \begin{lstlisting}
  12077. ((Integer -> Integer) (Vector Integer Integer)
  12078. -> (Vector Integer Integer))
  12079. \end{lstlisting}
  12080. After erasure, the type of \code{map-vec} is
  12081. \begin{lstlisting}
  12082. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12083. \end{lstlisting}
  12084. but we need to convert it to the instantiated type. This is easy to
  12085. do in the target language \LangCast{} with a single \code{cast}. In
  12086. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12087. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12088. the instantiated type. The source and target type of a cast must be
  12089. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12090. because both the source and target are obtained from the same
  12091. polymorphic type of \code{map-vec}, replacing the type parameters with
  12092. \code{Any} in the former and with the deduced type arguments in the
  12093. later. (Recall that the \code{Any} type is consistent with any type.)
  12094. To implement the \code{erase-types} pass, we recommend defining a
  12095. recursive auxiliary function named \code{erase-type} that applies the
  12096. following two transformations. It replaces type variables with
  12097. \code{Any}
  12098. \begin{lstlisting}
  12099. |$x$|
  12100. |$\Rightarrow$|
  12101. Any
  12102. \end{lstlisting}
  12103. and it removes the polymorphic \code{All} types.
  12104. \begin{lstlisting}
  12105. (All |$xs$| |$T_1$|)
  12106. |$\Rightarrow$|
  12107. |$T'_1$|
  12108. \end{lstlisting}
  12109. Apply the \code{erase-type} function to all of the type annotations in
  12110. the program.
  12111. Regarding the translation of expressions, the case for \code{Inst} is
  12112. the interesting one. We translate it into a \code{Cast}, as shown
  12113. below. The type of the subexpression $e$ is the polymorphic type
  12114. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12115. $T$, the type $T'$. The target type $T''$ is the result of
  12116. substituting the arguments types $ts$ for the type parameters $xs$ in
  12117. $T$ followed by doing type erasure.
  12118. \begin{lstlisting}
  12119. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12120. |$\Rightarrow$|
  12121. (Cast |$e'$| |$T'$| |$T''$|)
  12122. \end{lstlisting}
  12123. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12124. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12125. Finally, each polymorphic function is translated to a regular
  12126. functions in which type erasure has been applied to all the type
  12127. annotations and the body.
  12128. \begin{lstlisting}
  12129. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12130. |$\Rightarrow$|
  12131. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12132. \end{lstlisting}
  12133. \begin{exercise}\normalfont
  12134. Implement a compiler for the polymorphic language \LangPoly{} by
  12135. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12136. programs that use polymorphic functions. Some of them should make
  12137. use of first-class polymorphism.
  12138. \end{exercise}
  12139. \begin{figure}[p]
  12140. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12141. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12142. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12143. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12144. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12145. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12146. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12147. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12148. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12149. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12150. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12151. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12152. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12153. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12154. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12155. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12156. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12157. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12158. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12159. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12160. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12161. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12162. \path[->,bend right=15] (Rpoly) edge [above] node
  12163. {\ttfamily\footnotesize type-check} (Rpolyp);
  12164. \path[->,bend right=15] (Rpolyp) edge [above] node
  12165. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12166. \path[->,bend right=15] (Rgradualp) edge [above] node
  12167. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12168. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12169. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12170. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12171. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12172. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12173. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12174. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12175. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12176. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12177. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12178. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12179. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12180. \path[->,bend left=15] (F1-1) edge [below] node
  12181. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12182. \path[->,bend right=15] (F1-2) edge [above] node
  12183. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12184. \path[->,bend right=15] (F1-3) edge [above] node
  12185. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12186. \path[->,bend right=15] (F1-4) edge [above] node
  12187. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12188. \path[->,bend right=15] (F1-5) edge [right] node
  12189. {\ttfamily\footnotesize explicate-control} (C3-2);
  12190. \path[->,bend left=15] (C3-2) edge [left] node
  12191. {\ttfamily\footnotesize select-instr.} (x86-2);
  12192. \path[->,bend right=15] (x86-2) edge [left] node
  12193. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12194. \path[->,bend right=15] (x86-2-1) edge [below] node
  12195. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12196. \path[->,bend right=15] (x86-2-2) edge [left] node
  12197. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12198. \path[->,bend left=15] (x86-3) edge [above] node
  12199. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12200. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12201. \end{tikzpicture}
  12202. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12203. \label{fig:Rpoly-passes}
  12204. \end{figure}
  12205. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12206. for the compilation of \LangPoly{}.
  12207. % TODO: challenge problem: specialization of instantiations
  12208. % Further Reading
  12209. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12210. \clearpage
  12211. \appendix
  12212. \chapter{Appendix}
  12213. \section{Interpreters}
  12214. \label{appendix:interp}
  12215. \index{subject}{interpreter}
  12216. We provide interpreters for each of the source languages \LangInt{},
  12217. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  12218. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12219. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12220. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12221. and x86 are in the \key{interp.rkt} file.
  12222. \section{Utility Functions}
  12223. \label{appendix:utilities}
  12224. The utility functions described in this section are in the
  12225. \key{utilities.rkt} file of the support code.
  12226. \paragraph{\code{interp-tests}}
  12227. The \key{interp-tests} function runs the compiler passes and the
  12228. interpreters on each of the specified tests to check whether each pass
  12229. is correct. The \key{interp-tests} function has the following
  12230. parameters:
  12231. \begin{description}
  12232. \item[name (a string)] a name to identify the compiler,
  12233. \item[typechecker] a function of exactly one argument that either
  12234. raises an error using the \code{error} function when it encounters a
  12235. type error, or returns \code{\#f} when it encounters a type
  12236. error. If there is no type error, the type checker returns the
  12237. program.
  12238. \item[passes] a list with one entry per pass. An entry is a list with
  12239. four things:
  12240. \begin{enumerate}
  12241. \item a string giving the name of the pass,
  12242. \item the function that implements the pass (a translator from AST
  12243. to AST),
  12244. \item a function that implements the interpreter (a function from
  12245. AST to result value) for the output language,
  12246. \item and a type checker for the output language. Type checkers for
  12247. the $R$ and $C$ languages are provided in the support code. For
  12248. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12249. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12250. type checker entry is optional. The support code does not provide
  12251. type checkers for the x86 languages.
  12252. \end{enumerate}
  12253. \item[source-interp] an interpreter for the source language. The
  12254. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12255. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12256. \item[tests] a list of test numbers that specifies which tests to
  12257. run. (see below)
  12258. \end{description}
  12259. %
  12260. The \key{interp-tests} function assumes that the subdirectory
  12261. \key{tests} has a collection of Racket programs whose names all start
  12262. with the family name, followed by an underscore and then the test
  12263. number, ending with the file extension \key{.rkt}. Also, for each test
  12264. program that calls \code{read} one or more times, there is a file with
  12265. the same name except that the file extension is \key{.in} that
  12266. provides the input for the Racket program. If the test program is
  12267. expected to fail type checking, then there should be an empty file of
  12268. the same name but with extension \key{.tyerr}.
  12269. \paragraph{\code{compiler-tests}}
  12270. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12271. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12272. machine code and checks that the output is $42$. The parameters to the
  12273. \code{compiler-tests} function are similar to those of the
  12274. \code{interp-tests} function, and consist of
  12275. \begin{itemize}
  12276. \item a compiler name (a string),
  12277. \item a type checker,
  12278. \item description of the passes,
  12279. \item name of a test-family, and
  12280. \item a list of test numbers.
  12281. \end{itemize}
  12282. \paragraph{\code{compile-file}}
  12283. takes a description of the compiler passes (see the comment for
  12284. \key{interp-tests}) and returns a function that, given a program file
  12285. name (a string ending in \key{.rkt}), applies all of the passes and
  12286. writes the output to a file whose name is the same as the program file
  12287. name but with \key{.rkt} replaced with \key{.s}.
  12288. \paragraph{\code{read-program}}
  12289. takes a file path and parses that file (it must be a Racket program)
  12290. into an abstract syntax tree.
  12291. \paragraph{\code{parse-program}}
  12292. takes an S-expression representation of an abstract syntax tree and converts it into
  12293. the struct-based representation.
  12294. \paragraph{\code{assert}}
  12295. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12296. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12297. \paragraph{\code{lookup}}
  12298. % remove discussion of lookup? -Jeremy
  12299. takes a key and an alist, and returns the first value that is
  12300. associated with the given key, if there is one. If not, an error is
  12301. triggered. The alist may contain both immutable pairs (built with
  12302. \key{cons}) and mutable pairs (built with \key{mcons}).
  12303. %The \key{map2} function ...
  12304. \section{x86 Instruction Set Quick-Reference}
  12305. \label{sec:x86-quick-reference}
  12306. \index{subject}{x86}
  12307. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12308. do. We write $A \to B$ to mean that the value of $A$ is written into
  12309. location $B$. Address offsets are given in bytes. The instruction
  12310. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12311. registers (such as \code{\%rax}), or memory references (such as
  12312. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12313. reference per instruction. Other operands must be immediates or
  12314. registers.
  12315. \begin{table}[tbp]
  12316. \centering
  12317. \begin{tabular}{l|l}
  12318. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12319. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12320. \texttt{negq} $A$ & $- A \to A$ \\
  12321. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12322. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12323. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12324. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12325. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12326. \texttt{retq} & Pops the return address and jumps to it \\
  12327. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12328. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12329. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12330. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12331. be an immediate) \\
  12332. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12333. matches the condition code of the instruction, otherwise go to the
  12334. next instructions. The condition codes are \key{e} for ``equal'',
  12335. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  12336. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  12337. \texttt{jl} $L$ & \\
  12338. \texttt{jle} $L$ & \\
  12339. \texttt{jg} $L$ & \\
  12340. \texttt{jge} $L$ & \\
  12341. \texttt{jmp} $L$ & Jump to label $L$ \\
  12342. \texttt{movq} $A$, $B$ & $A \to B$ \\
  12343. \texttt{movzbq} $A$, $B$ &
  12344. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  12345. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  12346. and the extra bytes of $B$ are set to zero.} \\
  12347. & \\
  12348. & \\
  12349. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  12350. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  12351. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  12352. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  12353. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  12354. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  12355. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  12356. description of the condition codes. $A$ must be a single byte register
  12357. (e.g., \texttt{al} or \texttt{cl}).} \\
  12358. \texttt{setl} $A$ & \\
  12359. \texttt{setle} $A$ & \\
  12360. \texttt{setg} $A$ & \\
  12361. \texttt{setge} $A$ &
  12362. \end{tabular}
  12363. \vspace{5pt}
  12364. \caption{Quick-reference for the x86 instructions used in this book.}
  12365. \label{tab:x86-instr}
  12366. \end{table}
  12367. \cleardoublepage
  12368. \section{Concrete Syntax for Intermediate Languages}
  12369. The concrete syntax of \LangAny{} is defined in
  12370. Figure~\ref{fig:Rany-concrete-syntax}.
  12371. \begin{figure}[tp]
  12372. \centering
  12373. \fbox{
  12374. \begin{minipage}{0.97\textwidth}\small
  12375. \[
  12376. \begin{array}{lcl}
  12377. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  12378. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  12379. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  12380. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  12381. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  12382. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  12383. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  12384. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  12385. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  12386. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  12387. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  12388. \mid \LP\key{void?}\;\Exp\RP \\
  12389. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  12390. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12391. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  12392. \end{array}
  12393. \]
  12394. \end{minipage}
  12395. }
  12396. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  12397. (Figure~\ref{fig:Rlam-syntax}).}
  12398. \label{fig:Rany-concrete-syntax}
  12399. \end{figure}
  12400. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  12401. defined in Figures~\ref{fig:c0-concrete-syntax},
  12402. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  12403. and \ref{fig:c3-concrete-syntax}, respectively.
  12404. \begin{figure}[tbp]
  12405. \fbox{
  12406. \begin{minipage}{0.96\textwidth}
  12407. \[
  12408. \begin{array}{lcl}
  12409. \Atm &::=& \Int \mid \Var \\
  12410. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  12411. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  12412. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  12413. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  12414. \end{array}
  12415. \]
  12416. \end{minipage}
  12417. }
  12418. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12419. \label{fig:c0-concrete-syntax}
  12420. \end{figure}
  12421. \begin{figure}[tbp]
  12422. \fbox{
  12423. \begin{minipage}{0.96\textwidth}
  12424. \small
  12425. \[
  12426. \begin{array}{lcl}
  12427. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12428. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12429. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12430. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12431. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12432. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12433. \mid \key{goto}~\itm{label}\key{;}\\
  12434. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12435. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12436. \end{array}
  12437. \]
  12438. \end{minipage}
  12439. }
  12440. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12441. \label{fig:c1-concrete-syntax}
  12442. \end{figure}
  12443. \begin{figure}[tbp]
  12444. \fbox{
  12445. \begin{minipage}{0.96\textwidth}
  12446. \small
  12447. \[
  12448. \begin{array}{lcl}
  12449. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  12450. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12451. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12452. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12453. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12454. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12455. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12456. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12457. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12458. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12459. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12460. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12461. \end{array}
  12462. \]
  12463. \end{minipage}
  12464. }
  12465. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12466. \label{fig:c2-concrete-syntax}
  12467. \end{figure}
  12468. \begin{figure}[tp]
  12469. \fbox{
  12470. \begin{minipage}{0.96\textwidth}
  12471. \small
  12472. \[
  12473. \begin{array}{lcl}
  12474. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12475. \\
  12476. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12477. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12478. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12479. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12480. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12481. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12482. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12483. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12484. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12485. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12486. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12487. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12488. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12489. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12490. \LangCFunM{} & ::= & \Def\ldots
  12491. \end{array}
  12492. \]
  12493. \end{minipage}
  12494. }
  12495. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12496. \label{fig:c3-concrete-syntax}
  12497. \end{figure}
  12498. \backmatter
  12499. \addtocontents{toc}{\vspace{11pt}}
  12500. %% \addtocontents{toc}{\vspace{11pt}}
  12501. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  12502. \nocite{*}\let\bibname\refname
  12503. \addcontentsline{toc}{fmbm}{\refname}
  12504. \printbibliography
  12505. \printindex{authors}{Author Index}
  12506. \printindex{subject}{Subject Index}
  12507. \end{document}